blob: 83a271e23ebf63dccd471dc89b6e35ee1742eac0 [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);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000502 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou19fef692013-05-25 13:23:03 +0200503 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000504#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200505 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000506#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200507 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000508
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100509#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000510 if (server_hostname != NULL)
511 SSL_set_tlsext_host_name(self->ssl, server_hostname);
512#endif
513
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000514 /* If the socket is in non-blocking mode or timeout mode, set the BIO
515 * to non-blocking mode (blocking is the default)
516 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000517 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000518 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
519 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
520 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000521
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000522 PySSL_BEGIN_ALLOW_THREADS
523 if (socket_type == PY_SSL_CLIENT)
524 SSL_set_connect_state(self->ssl);
525 else
526 SSL_set_accept_state(self->ssl);
527 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000528
Antoine Pitroud6494802011-07-21 01:11:30 +0200529 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000530 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100531 if (self->Socket == NULL) {
532 Py_DECREF(self);
533 return NULL;
534 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000535 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000536}
537
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000538/* SSL object methods */
539
Antoine Pitrou152efa22010-05-16 18:19:27 +0000540static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000541{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000542 int ret;
543 int err;
544 int sockstate, nonblocking;
545 PySocketSockObject *sock
546 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000547
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000548 if (((PyObject*)sock) == Py_None) {
549 _setSSLError("Underlying socket connection gone",
550 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
551 return NULL;
552 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000553 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000554
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000555 /* just in case the blocking state of the socket has been changed */
556 nonblocking = (sock->sock_timeout >= 0.0);
557 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
558 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000559
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000560 /* Actually negotiate SSL connection */
561 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000562 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000563 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000564 ret = SSL_do_handshake(self->ssl);
565 err = SSL_get_error(self->ssl, ret);
566 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000567 if (PyErr_CheckSignals())
568 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000569 if (err == SSL_ERROR_WANT_READ) {
570 sockstate = check_socket_and_wait_for_timeout(sock, 0);
571 } else if (err == SSL_ERROR_WANT_WRITE) {
572 sockstate = check_socket_and_wait_for_timeout(sock, 1);
573 } else {
574 sockstate = SOCKET_OPERATION_OK;
575 }
576 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000577 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000578 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000579 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000580 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
581 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000582 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000583 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000584 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
585 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000586 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000587 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000588 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
589 break;
590 }
591 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000592 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000593 if (ret < 1)
594 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000595
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000596 if (self->peer_cert)
597 X509_free (self->peer_cert);
598 PySSL_BEGIN_ALLOW_THREADS
599 self->peer_cert = SSL_get_peer_certificate(self->ssl);
600 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200601 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000602
603 Py_INCREF(Py_None);
604 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000605
606error:
607 Py_DECREF(sock);
608 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000609}
610
Thomas Woutersed03b412007-08-28 21:37:11 +0000611static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000612_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000613
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000614 char namebuf[X509_NAME_MAXLEN];
615 int buflen;
616 PyObject *name_obj;
617 PyObject *value_obj;
618 PyObject *attr;
619 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000620
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000621 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
622 if (buflen < 0) {
623 _setSSLError(NULL, 0, __FILE__, __LINE__);
624 goto fail;
625 }
626 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
627 if (name_obj == NULL)
628 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000629
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000630 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
631 if (buflen < 0) {
632 _setSSLError(NULL, 0, __FILE__, __LINE__);
633 Py_DECREF(name_obj);
634 goto fail;
635 }
636 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000637 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000638 OPENSSL_free(valuebuf);
639 if (value_obj == NULL) {
640 Py_DECREF(name_obj);
641 goto fail;
642 }
643 attr = PyTuple_New(2);
644 if (attr == NULL) {
645 Py_DECREF(name_obj);
646 Py_DECREF(value_obj);
647 goto fail;
648 }
649 PyTuple_SET_ITEM(attr, 0, name_obj);
650 PyTuple_SET_ITEM(attr, 1, value_obj);
651 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000652
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000653 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000654 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000655}
656
657static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000658_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000659{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000660 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
661 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
662 PyObject *rdnt;
663 PyObject *attr = NULL; /* tuple to hold an attribute */
664 int entry_count = X509_NAME_entry_count(xname);
665 X509_NAME_ENTRY *entry;
666 ASN1_OBJECT *name;
667 ASN1_STRING *value;
668 int index_counter;
669 int rdn_level = -1;
670 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000671
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000672 dn = PyList_New(0);
673 if (dn == NULL)
674 return NULL;
675 /* now create another tuple to hold the top-level RDN */
676 rdn = PyList_New(0);
677 if (rdn == NULL)
678 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000679
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000680 for (index_counter = 0;
681 index_counter < entry_count;
682 index_counter++)
683 {
684 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000685
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000686 /* check to see if we've gotten to a new RDN */
687 if (rdn_level >= 0) {
688 if (rdn_level != entry->set) {
689 /* yes, new RDN */
690 /* add old RDN to DN */
691 rdnt = PyList_AsTuple(rdn);
692 Py_DECREF(rdn);
693 if (rdnt == NULL)
694 goto fail0;
695 retcode = PyList_Append(dn, rdnt);
696 Py_DECREF(rdnt);
697 if (retcode < 0)
698 goto fail0;
699 /* create new RDN */
700 rdn = PyList_New(0);
701 if (rdn == NULL)
702 goto fail0;
703 }
704 }
705 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000706
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000707 /* now add this attribute to the current RDN */
708 name = X509_NAME_ENTRY_get_object(entry);
709 value = X509_NAME_ENTRY_get_data(entry);
710 attr = _create_tuple_for_attribute(name, value);
711 /*
712 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
713 entry->set,
714 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
715 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
716 */
717 if (attr == NULL)
718 goto fail1;
719 retcode = PyList_Append(rdn, attr);
720 Py_DECREF(attr);
721 if (retcode < 0)
722 goto fail1;
723 }
724 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100725 if (rdn != NULL) {
726 if (PyList_GET_SIZE(rdn) > 0) {
727 rdnt = PyList_AsTuple(rdn);
728 Py_DECREF(rdn);
729 if (rdnt == NULL)
730 goto fail0;
731 retcode = PyList_Append(dn, rdnt);
732 Py_DECREF(rdnt);
733 if (retcode < 0)
734 goto fail0;
735 }
736 else {
737 Py_DECREF(rdn);
738 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000739 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000740
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000741 /* convert list to tuple */
742 rdnt = PyList_AsTuple(dn);
743 Py_DECREF(dn);
744 if (rdnt == NULL)
745 return NULL;
746 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000747
748 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000749 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000750
751 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000752 Py_XDECREF(dn);
753 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000754}
755
756static PyObject *
757_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000758
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000759 /* this code follows the procedure outlined in
760 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
761 function to extract the STACK_OF(GENERAL_NAME),
762 then iterates through the stack to add the
763 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000764
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000765 int i, j;
766 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200767 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000768 X509_EXTENSION *ext = NULL;
769 GENERAL_NAMES *names = NULL;
770 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000771 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000772 BIO *biobuf = NULL;
773 char buf[2048];
774 char *vptr;
775 int len;
776 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000777#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000778 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000779#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000780 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000781#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000782
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000783 if (certificate == NULL)
784 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000785
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000786 /* get a memory buffer */
787 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000788
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200789 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000790 while ((i = X509_get_ext_by_NID(
791 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000792
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000793 if (peer_alt_names == Py_None) {
794 peer_alt_names = PyList_New(0);
795 if (peer_alt_names == NULL)
796 goto fail;
797 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000798
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000799 /* now decode the altName */
800 ext = X509_get_ext(certificate, i);
801 if(!(method = X509V3_EXT_get(ext))) {
802 PyErr_SetString
803 (PySSLErrorObject,
804 ERRSTR("No method for internalizing subjectAltName!"));
805 goto fail;
806 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000807
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000808 p = ext->value->data;
809 if (method->it)
810 names = (GENERAL_NAMES*)
811 (ASN1_item_d2i(NULL,
812 &p,
813 ext->value->length,
814 ASN1_ITEM_ptr(method->it)));
815 else
816 names = (GENERAL_NAMES*)
817 (method->d2i(NULL,
818 &p,
819 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000820
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000821 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000822 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200823 int gntype;
824 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000825
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000826 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200827 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200828 switch (gntype) {
829 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000830 /* we special-case DirName as a tuple of
831 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000832
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000833 t = PyTuple_New(2);
834 if (t == NULL) {
835 goto fail;
836 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000837
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000838 v = PyUnicode_FromString("DirName");
839 if (v == NULL) {
840 Py_DECREF(t);
841 goto fail;
842 }
843 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000844
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000845 v = _create_tuple_for_X509_NAME (name->d.dirn);
846 if (v == NULL) {
847 Py_DECREF(t);
848 goto fail;
849 }
850 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200851 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000852
Christian Heimes824f7f32013-08-17 00:54:47 +0200853 case GEN_EMAIL:
854 case GEN_DNS:
855 case GEN_URI:
856 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
857 correctly, CVE-2013-4238 */
858 t = PyTuple_New(2);
859 if (t == NULL)
860 goto fail;
861 switch (gntype) {
862 case GEN_EMAIL:
863 v = PyUnicode_FromString("email");
864 as = name->d.rfc822Name;
865 break;
866 case GEN_DNS:
867 v = PyUnicode_FromString("DNS");
868 as = name->d.dNSName;
869 break;
870 case GEN_URI:
871 v = PyUnicode_FromString("URI");
872 as = name->d.uniformResourceIdentifier;
873 break;
874 }
875 if (v == NULL) {
876 Py_DECREF(t);
877 goto fail;
878 }
879 PyTuple_SET_ITEM(t, 0, v);
880 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
881 ASN1_STRING_length(as));
882 if (v == NULL) {
883 Py_DECREF(t);
884 goto fail;
885 }
886 PyTuple_SET_ITEM(t, 1, v);
887 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000888
Christian Heimes824f7f32013-08-17 00:54:47 +0200889 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000890 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200891 switch (gntype) {
892 /* check for new general name type */
893 case GEN_OTHERNAME:
894 case GEN_X400:
895 case GEN_EDIPARTY:
896 case GEN_IPADD:
897 case GEN_RID:
898 break;
899 default:
900 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
901 "Unknown general name type %d",
902 gntype) == -1) {
903 goto fail;
904 }
905 break;
906 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000907 (void) BIO_reset(biobuf);
908 GENERAL_NAME_print(biobuf, name);
909 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
910 if (len < 0) {
911 _setSSLError(NULL, 0, __FILE__, __LINE__);
912 goto fail;
913 }
914 vptr = strchr(buf, ':');
915 if (vptr == NULL)
916 goto fail;
917 t = PyTuple_New(2);
918 if (t == NULL)
919 goto fail;
920 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
921 if (v == NULL) {
922 Py_DECREF(t);
923 goto fail;
924 }
925 PyTuple_SET_ITEM(t, 0, v);
926 v = PyUnicode_FromStringAndSize((vptr + 1),
927 (len - (vptr - buf + 1)));
928 if (v == NULL) {
929 Py_DECREF(t);
930 goto fail;
931 }
932 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200933 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000934 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000935
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000936 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000937
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 if (PyList_Append(peer_alt_names, t) < 0) {
939 Py_DECREF(t);
940 goto fail;
941 }
942 Py_DECREF(t);
943 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100944 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000945 }
946 BIO_free(biobuf);
947 if (peer_alt_names != Py_None) {
948 v = PyList_AsTuple(peer_alt_names);
949 Py_DECREF(peer_alt_names);
950 return v;
951 } else {
952 return peer_alt_names;
953 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000954
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000955
956 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000957 if (biobuf != NULL)
958 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000959
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000960 if (peer_alt_names != Py_None) {
961 Py_XDECREF(peer_alt_names);
962 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000963
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000964 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000965}
966
967static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000968_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000969
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000970 PyObject *retval = NULL;
971 BIO *biobuf = NULL;
972 PyObject *peer;
973 PyObject *peer_alt_names = NULL;
974 PyObject *issuer;
975 PyObject *version;
976 PyObject *sn_obj;
977 ASN1_INTEGER *serialNumber;
978 char buf[2048];
979 int len;
980 ASN1_TIME *notBefore, *notAfter;
981 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000982
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000983 retval = PyDict_New();
984 if (retval == NULL)
985 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000986
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000987 peer = _create_tuple_for_X509_NAME(
988 X509_get_subject_name(certificate));
989 if (peer == NULL)
990 goto fail0;
991 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
992 Py_DECREF(peer);
993 goto fail0;
994 }
995 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000996
Antoine Pitroufb046912010-11-09 20:21:19 +0000997 issuer = _create_tuple_for_X509_NAME(
998 X509_get_issuer_name(certificate));
999 if (issuer == NULL)
1000 goto fail0;
1001 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001002 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001003 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001004 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001005 Py_DECREF(issuer);
1006
1007 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001008 if (version == NULL)
1009 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001010 if (PyDict_SetItemString(retval, "version", version) < 0) {
1011 Py_DECREF(version);
1012 goto fail0;
1013 }
1014 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001015
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001016 /* get a memory buffer */
1017 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001018
Antoine Pitroufb046912010-11-09 20:21:19 +00001019 (void) BIO_reset(biobuf);
1020 serialNumber = X509_get_serialNumber(certificate);
1021 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1022 i2a_ASN1_INTEGER(biobuf, serialNumber);
1023 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1024 if (len < 0) {
1025 _setSSLError(NULL, 0, __FILE__, __LINE__);
1026 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001027 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001028 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1029 if (sn_obj == NULL)
1030 goto fail1;
1031 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1032 Py_DECREF(sn_obj);
1033 goto fail1;
1034 }
1035 Py_DECREF(sn_obj);
1036
1037 (void) BIO_reset(biobuf);
1038 notBefore = X509_get_notBefore(certificate);
1039 ASN1_TIME_print(biobuf, notBefore);
1040 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1041 if (len < 0) {
1042 _setSSLError(NULL, 0, __FILE__, __LINE__);
1043 goto fail1;
1044 }
1045 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1046 if (pnotBefore == NULL)
1047 goto fail1;
1048 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1049 Py_DECREF(pnotBefore);
1050 goto fail1;
1051 }
1052 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001053
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001054 (void) BIO_reset(biobuf);
1055 notAfter = X509_get_notAfter(certificate);
1056 ASN1_TIME_print(biobuf, notAfter);
1057 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1058 if (len < 0) {
1059 _setSSLError(NULL, 0, __FILE__, __LINE__);
1060 goto fail1;
1061 }
1062 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1063 if (pnotAfter == NULL)
1064 goto fail1;
1065 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1066 Py_DECREF(pnotAfter);
1067 goto fail1;
1068 }
1069 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001070
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001071 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001072
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001073 peer_alt_names = _get_peer_alt_names(certificate);
1074 if (peer_alt_names == NULL)
1075 goto fail1;
1076 else if (peer_alt_names != Py_None) {
1077 if (PyDict_SetItemString(retval, "subjectAltName",
1078 peer_alt_names) < 0) {
1079 Py_DECREF(peer_alt_names);
1080 goto fail1;
1081 }
1082 Py_DECREF(peer_alt_names);
1083 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001084
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001085 BIO_free(biobuf);
1086 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001087
1088 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001089 if (biobuf != NULL)
1090 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001091 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001092 Py_XDECREF(retval);
1093 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001094}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001095
Christian Heimes9a5395a2013-06-17 15:44:12 +02001096static PyObject *
1097_certificate_to_der(X509 *certificate)
1098{
1099 unsigned char *bytes_buf = NULL;
1100 int len;
1101 PyObject *retval;
1102
1103 bytes_buf = NULL;
1104 len = i2d_X509(certificate, &bytes_buf);
1105 if (len < 0) {
1106 _setSSLError(NULL, 0, __FILE__, __LINE__);
1107 return NULL;
1108 }
1109 /* this is actually an immutable bytes sequence */
1110 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1111 OPENSSL_free(bytes_buf);
1112 return retval;
1113}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001114
1115static PyObject *
1116PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1117
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001118 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001119 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001120 X509 *x=NULL;
1121 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001122
Antoine Pitroufb046912010-11-09 20:21:19 +00001123 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1124 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001125 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001126
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001127 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1128 PyErr_SetString(PySSLErrorObject,
1129 "Can't malloc memory to read file");
1130 goto fail0;
1131 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001132
Victor Stinner3800e1e2010-05-16 21:23:48 +00001133 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001134 PyErr_SetString(PySSLErrorObject,
1135 "Can't open file");
1136 goto fail0;
1137 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001138
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001139 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1140 if (x == NULL) {
1141 PyErr_SetString(PySSLErrorObject,
1142 "Error decoding PEM-encoded file");
1143 goto fail0;
1144 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001145
Antoine Pitroufb046912010-11-09 20:21:19 +00001146 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001147 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001148
1149 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001150 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001151 if (cert != NULL) BIO_free(cert);
1152 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001153}
1154
1155
1156static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001157PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001158{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001159 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001160 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001161
Antoine Pitrou721738f2012-08-15 23:20:39 +02001162 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001163 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001164
Antoine Pitrou20b85552013-09-29 19:50:53 +02001165 if (!self->handshake_done) {
1166 PyErr_SetString(PyExc_ValueError,
1167 "handshake not done yet");
1168 return NULL;
1169 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001170 if (!self->peer_cert)
1171 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001172
Antoine Pitrou721738f2012-08-15 23:20:39 +02001173 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001174 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001175 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001176 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001177 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001178 if ((verification & SSL_VERIFY_PEER) == 0)
1179 return PyDict_New();
1180 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001181 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001182 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001183}
1184
1185PyDoc_STRVAR(PySSL_peercert_doc,
1186"peer_certificate([der=False]) -> certificate\n\
1187\n\
1188Returns the certificate for the peer. If no certificate was provided,\n\
1189returns None. If a certificate was provided, but not validated, returns\n\
1190an empty dictionary. Otherwise returns a dict containing information\n\
1191about the peer certificate.\n\
1192\n\
1193If the optional argument is True, returns a DER-encoded copy of the\n\
1194peer certificate, or None if no certificate was provided. This will\n\
1195return the certificate even if it wasn't validated.");
1196
Antoine Pitrou152efa22010-05-16 18:19:27 +00001197static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001198
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001199 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001200 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001201 char *cipher_name;
1202 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001203
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001204 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001205 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001206 current = SSL_get_current_cipher(self->ssl);
1207 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001208 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001209
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001210 retval = PyTuple_New(3);
1211 if (retval == NULL)
1212 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001213
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001214 cipher_name = (char *) SSL_CIPHER_get_name(current);
1215 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001216 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001217 PyTuple_SET_ITEM(retval, 0, Py_None);
1218 } else {
1219 v = PyUnicode_FromString(cipher_name);
1220 if (v == NULL)
1221 goto fail0;
1222 PyTuple_SET_ITEM(retval, 0, v);
1223 }
1224 cipher_protocol = SSL_CIPHER_get_version(current);
1225 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001226 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001227 PyTuple_SET_ITEM(retval, 1, Py_None);
1228 } else {
1229 v = PyUnicode_FromString(cipher_protocol);
1230 if (v == NULL)
1231 goto fail0;
1232 PyTuple_SET_ITEM(retval, 1, v);
1233 }
1234 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1235 if (v == NULL)
1236 goto fail0;
1237 PyTuple_SET_ITEM(retval, 2, v);
1238 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001239
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001240 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001241 Py_DECREF(retval);
1242 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001243}
1244
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001245#ifdef OPENSSL_NPN_NEGOTIATED
1246static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1247 const unsigned char *out;
1248 unsigned int outlen;
1249
Victor Stinner4569cd52013-06-23 14:58:43 +02001250 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001251 &out, &outlen);
1252
1253 if (out == NULL)
1254 Py_RETURN_NONE;
1255 return PyUnicode_FromStringAndSize((char *) out, outlen);
1256}
1257#endif
1258
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001259static PyObject *PySSL_compression(PySSLSocket *self) {
1260#ifdef OPENSSL_NO_COMP
1261 Py_RETURN_NONE;
1262#else
1263 const COMP_METHOD *comp_method;
1264 const char *short_name;
1265
1266 if (self->ssl == NULL)
1267 Py_RETURN_NONE;
1268 comp_method = SSL_get_current_compression(self->ssl);
1269 if (comp_method == NULL || comp_method->type == NID_undef)
1270 Py_RETURN_NONE;
1271 short_name = OBJ_nid2sn(comp_method->type);
1272 if (short_name == NULL)
1273 Py_RETURN_NONE;
1274 return PyUnicode_DecodeFSDefault(short_name);
1275#endif
1276}
1277
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001278static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1279 Py_INCREF(self->ctx);
1280 return self->ctx;
1281}
1282
1283static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1284 void *closure) {
1285
1286 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001287#if !HAVE_SNI
1288 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1289 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001290 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001291#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001292 Py_INCREF(value);
1293 Py_DECREF(self->ctx);
1294 self->ctx = (PySSLContext *) value;
1295 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001296#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001297 } else {
1298 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1299 return -1;
1300 }
1301
1302 return 0;
1303}
1304
1305PyDoc_STRVAR(PySSL_set_context_doc,
1306"_setter_context(ctx)\n\
1307\
1308This changes the context associated with the SSLSocket. This is typically\n\
1309used from within a callback function set by the set_servername_callback\n\
1310on the SSLContext to change the certificate information associated with the\n\
1311SSLSocket before the cryptographic exchange handshake messages\n");
1312
1313
1314
Antoine Pitrou152efa22010-05-16 18:19:27 +00001315static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001316{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001317 if (self->peer_cert) /* Possible not to have one? */
1318 X509_free (self->peer_cert);
1319 if (self->ssl)
1320 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001321 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001322 Py_XDECREF(self->ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001323 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001324}
1325
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001326/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001327 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001328 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001329 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001330
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001331static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001332check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001333{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001334 fd_set fds;
1335 struct timeval tv;
1336 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001337
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001338 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1339 if (s->sock_timeout < 0.0)
1340 return SOCKET_IS_BLOCKING;
1341 else if (s->sock_timeout == 0.0)
1342 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001343
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001344 /* Guard against closed socket */
1345 if (s->sock_fd < 0)
1346 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001347
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001348 /* Prefer poll, if available, since you can poll() any fd
1349 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001350#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001351 {
1352 struct pollfd pollfd;
1353 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001354
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001355 pollfd.fd = s->sock_fd;
1356 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001357
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001358 /* s->sock_timeout is in seconds, timeout in ms */
1359 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1360 PySSL_BEGIN_ALLOW_THREADS
1361 rc = poll(&pollfd, 1, timeout);
1362 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001363
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001364 goto normal_return;
1365 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001366#endif
1367
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001368 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001369 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001370 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001371
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001372 /* Construct the arguments to select */
1373 tv.tv_sec = (int)s->sock_timeout;
1374 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1375 FD_ZERO(&fds);
1376 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001377
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001378 /* See if the socket is ready */
1379 PySSL_BEGIN_ALLOW_THREADS
1380 if (writing)
1381 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1382 else
1383 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1384 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001385
Bill Janssen6e027db2007-11-15 22:23:56 +00001386#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001387normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001388#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001389 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1390 (when we are able to write or when there's something to read) */
1391 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001392}
1393
Antoine Pitrou152efa22010-05-16 18:19:27 +00001394static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001395{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001396 Py_buffer buf;
1397 int len;
1398 int sockstate;
1399 int err;
1400 int nonblocking;
1401 PySocketSockObject *sock
1402 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001403
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001404 if (((PyObject*)sock) == Py_None) {
1405 _setSSLError("Underlying socket connection gone",
1406 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1407 return NULL;
1408 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001409 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001410
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001411 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1412 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001413 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001414 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001415
Victor Stinner6efa9652013-06-25 00:42:31 +02001416 if (buf.len > INT_MAX) {
1417 PyErr_Format(PyExc_OverflowError,
1418 "string longer than %d bytes", INT_MAX);
1419 goto error;
1420 }
1421
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001422 /* just in case the blocking state of the socket has been changed */
1423 nonblocking = (sock->sock_timeout >= 0.0);
1424 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1425 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1426
1427 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1428 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001429 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001430 "The write operation timed out");
1431 goto error;
1432 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1433 PyErr_SetString(PySSLErrorObject,
1434 "Underlying socket has been closed.");
1435 goto error;
1436 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1437 PyErr_SetString(PySSLErrorObject,
1438 "Underlying socket too large for select().");
1439 goto error;
1440 }
1441 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001442 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001443 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001444 err = SSL_get_error(self->ssl, len);
1445 PySSL_END_ALLOW_THREADS
1446 if (PyErr_CheckSignals()) {
1447 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001448 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001449 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001450 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001451 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001452 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001453 } else {
1454 sockstate = SOCKET_OPERATION_OK;
1455 }
1456 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001457 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001458 "The write operation timed out");
1459 goto error;
1460 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1461 PyErr_SetString(PySSLErrorObject,
1462 "Underlying socket has been closed.");
1463 goto error;
1464 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1465 break;
1466 }
1467 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001468
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001469 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001470 PyBuffer_Release(&buf);
1471 if (len > 0)
1472 return PyLong_FromLong(len);
1473 else
1474 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001475
1476error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001477 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001478 PyBuffer_Release(&buf);
1479 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001480}
1481
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001482PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001483"write(s) -> len\n\
1484\n\
1485Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001486of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001487
Antoine Pitrou152efa22010-05-16 18:19:27 +00001488static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001489{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001490 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001491
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001492 PySSL_BEGIN_ALLOW_THREADS
1493 count = SSL_pending(self->ssl);
1494 PySSL_END_ALLOW_THREADS
1495 if (count < 0)
1496 return PySSL_SetError(self, count, __FILE__, __LINE__);
1497 else
1498 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001499}
1500
1501PyDoc_STRVAR(PySSL_SSLpending_doc,
1502"pending() -> count\n\
1503\n\
1504Returns the number of already decrypted bytes available for read,\n\
1505pending on the connection.\n");
1506
Antoine Pitrou152efa22010-05-16 18:19:27 +00001507static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001508{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001509 PyObject *dest = NULL;
1510 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001511 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001512 int len, count;
1513 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001514 int sockstate;
1515 int err;
1516 int nonblocking;
1517 PySocketSockObject *sock
1518 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001519
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001520 if (((PyObject*)sock) == Py_None) {
1521 _setSSLError("Underlying socket connection gone",
1522 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1523 return NULL;
1524 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001525 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001526
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001527 buf.obj = NULL;
1528 buf.buf = NULL;
1529 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001530 goto error;
1531
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001532 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1533 dest = PyBytes_FromStringAndSize(NULL, len);
1534 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001535 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001536 mem = PyBytes_AS_STRING(dest);
1537 }
1538 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001539 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001540 mem = buf.buf;
1541 if (len <= 0 || len > buf.len) {
1542 len = (int) buf.len;
1543 if (buf.len != len) {
1544 PyErr_SetString(PyExc_OverflowError,
1545 "maximum length can't fit in a C 'int'");
1546 goto error;
1547 }
1548 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001549 }
1550
1551 /* just in case the blocking state of the socket has been changed */
1552 nonblocking = (sock->sock_timeout >= 0.0);
1553 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1554 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1555
1556 /* first check if there are bytes ready to be read */
1557 PySSL_BEGIN_ALLOW_THREADS
1558 count = SSL_pending(self->ssl);
1559 PySSL_END_ALLOW_THREADS
1560
1561 if (!count) {
1562 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1563 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001564 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001565 "The read operation timed out");
1566 goto error;
1567 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1568 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001569 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001570 goto error;
1571 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1572 count = 0;
1573 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001574 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001575 }
1576 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001577 PySSL_BEGIN_ALLOW_THREADS
1578 count = SSL_read(self->ssl, mem, len);
1579 err = SSL_get_error(self->ssl, count);
1580 PySSL_END_ALLOW_THREADS
1581 if (PyErr_CheckSignals())
1582 goto error;
1583 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001584 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001585 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001586 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001587 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1588 (SSL_get_shutdown(self->ssl) ==
1589 SSL_RECEIVED_SHUTDOWN))
1590 {
1591 count = 0;
1592 goto done;
1593 } else {
1594 sockstate = SOCKET_OPERATION_OK;
1595 }
1596 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001597 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001598 "The read operation timed out");
1599 goto error;
1600 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1601 break;
1602 }
1603 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1604 if (count <= 0) {
1605 PySSL_SetError(self, count, __FILE__, __LINE__);
1606 goto error;
1607 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001608
1609done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001610 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001611 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001612 _PyBytes_Resize(&dest, count);
1613 return dest;
1614 }
1615 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001616 PyBuffer_Release(&buf);
1617 return PyLong_FromLong(count);
1618 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001619
1620error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001621 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001622 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001623 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001624 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001625 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001626 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001627}
1628
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001629PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001630"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001631\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001632Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001633
Antoine Pitrou152efa22010-05-16 18:19:27 +00001634static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001635{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001636 int err, ssl_err, sockstate, nonblocking;
1637 int zeros = 0;
1638 PySocketSockObject *sock
1639 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001640
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001641 /* Guard against closed socket */
1642 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1643 _setSSLError("Underlying socket connection gone",
1644 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1645 return NULL;
1646 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001647 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001648
1649 /* Just in case the blocking state of the socket has been changed */
1650 nonblocking = (sock->sock_timeout >= 0.0);
1651 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1652 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1653
1654 while (1) {
1655 PySSL_BEGIN_ALLOW_THREADS
1656 /* Disable read-ahead so that unwrap can work correctly.
1657 * Otherwise OpenSSL might read in too much data,
1658 * eating clear text data that happens to be
1659 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001660 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001661 * function is used and the shutdown_seen_zero != 0
1662 * condition is met.
1663 */
1664 if (self->shutdown_seen_zero)
1665 SSL_set_read_ahead(self->ssl, 0);
1666 err = SSL_shutdown(self->ssl);
1667 PySSL_END_ALLOW_THREADS
1668 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1669 if (err > 0)
1670 break;
1671 if (err == 0) {
1672 /* Don't loop endlessly; instead preserve legacy
1673 behaviour of trying SSL_shutdown() only twice.
1674 This looks necessary for OpenSSL < 0.9.8m */
1675 if (++zeros > 1)
1676 break;
1677 /* Shutdown was sent, now try receiving */
1678 self->shutdown_seen_zero = 1;
1679 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001680 }
1681
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001682 /* Possibly retry shutdown until timeout or failure */
1683 ssl_err = SSL_get_error(self->ssl, err);
1684 if (ssl_err == SSL_ERROR_WANT_READ)
1685 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1686 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1687 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1688 else
1689 break;
1690 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1691 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001692 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001693 "The read operation timed out");
1694 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001695 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001696 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001697 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001698 }
1699 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1700 PyErr_SetString(PySSLErrorObject,
1701 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001702 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001703 }
1704 else if (sockstate != SOCKET_OPERATION_OK)
1705 /* Retain the SSL error code */
1706 break;
1707 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001708
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001709 if (err < 0) {
1710 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001711 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001712 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001713 else
1714 /* It's already INCREF'ed */
1715 return (PyObject *) sock;
1716
1717error:
1718 Py_DECREF(sock);
1719 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001720}
1721
1722PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1723"shutdown(s) -> socket\n\
1724\n\
1725Does the SSL shutdown handshake with the remote end, and returns\n\
1726the underlying socket object.");
1727
Antoine Pitroud6494802011-07-21 01:11:30 +02001728#if HAVE_OPENSSL_FINISHED
1729static PyObject *
1730PySSL_tls_unique_cb(PySSLSocket *self)
1731{
1732 PyObject *retval = NULL;
1733 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001734 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001735
1736 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1737 /* if session is resumed XOR we are the client */
1738 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1739 }
1740 else {
1741 /* if a new session XOR we are the server */
1742 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1743 }
1744
1745 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001746 if (len == 0)
1747 Py_RETURN_NONE;
1748
1749 retval = PyBytes_FromStringAndSize(buf, len);
1750
1751 return retval;
1752}
1753
1754PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1755"tls_unique_cb() -> bytes\n\
1756\n\
1757Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1758\n\
1759If the TLS handshake is not yet complete, None is returned");
1760
1761#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001762
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001763static PyGetSetDef ssl_getsetlist[] = {
1764 {"context", (getter) PySSL_get_context,
1765 (setter) PySSL_set_context, PySSL_set_context_doc},
1766 {NULL}, /* sentinel */
1767};
1768
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001769static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001770 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1771 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1772 PySSL_SSLwrite_doc},
1773 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1774 PySSL_SSLread_doc},
1775 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1776 PySSL_SSLpending_doc},
1777 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1778 PySSL_peercert_doc},
1779 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001780#ifdef OPENSSL_NPN_NEGOTIATED
1781 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1782#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001783 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001784 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1785 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001786#if HAVE_OPENSSL_FINISHED
1787 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1788 PySSL_tls_unique_cb_doc},
1789#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001790 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001791};
1792
Antoine Pitrou152efa22010-05-16 18:19:27 +00001793static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001794 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001795 "_ssl._SSLSocket", /*tp_name*/
1796 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001797 0, /*tp_itemsize*/
1798 /* methods */
1799 (destructor)PySSL_dealloc, /*tp_dealloc*/
1800 0, /*tp_print*/
1801 0, /*tp_getattr*/
1802 0, /*tp_setattr*/
1803 0, /*tp_reserved*/
1804 0, /*tp_repr*/
1805 0, /*tp_as_number*/
1806 0, /*tp_as_sequence*/
1807 0, /*tp_as_mapping*/
1808 0, /*tp_hash*/
1809 0, /*tp_call*/
1810 0, /*tp_str*/
1811 0, /*tp_getattro*/
1812 0, /*tp_setattro*/
1813 0, /*tp_as_buffer*/
1814 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1815 0, /*tp_doc*/
1816 0, /*tp_traverse*/
1817 0, /*tp_clear*/
1818 0, /*tp_richcompare*/
1819 0, /*tp_weaklistoffset*/
1820 0, /*tp_iter*/
1821 0, /*tp_iternext*/
1822 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001823 0, /*tp_members*/
1824 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001825};
1826
Antoine Pitrou152efa22010-05-16 18:19:27 +00001827
1828/*
1829 * _SSLContext objects
1830 */
1831
1832static PyObject *
1833context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1834{
1835 char *kwlist[] = {"protocol", NULL};
1836 PySSLContext *self;
1837 int proto_version = PY_SSL_VERSION_SSL23;
1838 SSL_CTX *ctx = NULL;
1839
1840 if (!PyArg_ParseTupleAndKeywords(
1841 args, kwds, "i:_SSLContext", kwlist,
1842 &proto_version))
1843 return NULL;
1844
1845 PySSL_BEGIN_ALLOW_THREADS
1846 if (proto_version == PY_SSL_VERSION_TLS1)
1847 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01001848#if HAVE_TLSv1_2
1849 else if (proto_version == PY_SSL_VERSION_TLS1_1)
1850 ctx = SSL_CTX_new(TLSv1_1_method());
1851 else if (proto_version == PY_SSL_VERSION_TLS1_2)
1852 ctx = SSL_CTX_new(TLSv1_2_method());
1853#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001854 else if (proto_version == PY_SSL_VERSION_SSL3)
1855 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001856#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001857 else if (proto_version == PY_SSL_VERSION_SSL2)
1858 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001859#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001860 else if (proto_version == PY_SSL_VERSION_SSL23)
1861 ctx = SSL_CTX_new(SSLv23_method());
1862 else
1863 proto_version = -1;
1864 PySSL_END_ALLOW_THREADS
1865
1866 if (proto_version == -1) {
1867 PyErr_SetString(PyExc_ValueError,
1868 "invalid protocol version");
1869 return NULL;
1870 }
1871 if (ctx == NULL) {
1872 PyErr_SetString(PySSLErrorObject,
1873 "failed to allocate SSL context");
1874 return NULL;
1875 }
1876
1877 assert(type != NULL && type->tp_alloc != NULL);
1878 self = (PySSLContext *) type->tp_alloc(type, 0);
1879 if (self == NULL) {
1880 SSL_CTX_free(ctx);
1881 return NULL;
1882 }
1883 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02001884#ifdef OPENSSL_NPN_NEGOTIATED
1885 self->npn_protocols = NULL;
1886#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001887#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02001888 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001889#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001890 /* Defaults */
1891 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001892 SSL_CTX_set_options(self->ctx,
1893 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001894
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001895#define SID_CTX "Python"
1896 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1897 sizeof(SID_CTX));
1898#undef SID_CTX
1899
Antoine Pitrou152efa22010-05-16 18:19:27 +00001900 return (PyObject *)self;
1901}
1902
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001903static int
1904context_traverse(PySSLContext *self, visitproc visit, void *arg)
1905{
1906#ifndef OPENSSL_NO_TLSEXT
1907 Py_VISIT(self->set_hostname);
1908#endif
1909 return 0;
1910}
1911
1912static int
1913context_clear(PySSLContext *self)
1914{
1915#ifndef OPENSSL_NO_TLSEXT
1916 Py_CLEAR(self->set_hostname);
1917#endif
1918 return 0;
1919}
1920
Antoine Pitrou152efa22010-05-16 18:19:27 +00001921static void
1922context_dealloc(PySSLContext *self)
1923{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001924 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001925 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001926#ifdef OPENSSL_NPN_NEGOTIATED
1927 PyMem_Free(self->npn_protocols);
1928#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001929 Py_TYPE(self)->tp_free(self);
1930}
1931
1932static PyObject *
1933set_ciphers(PySSLContext *self, PyObject *args)
1934{
1935 int ret;
1936 const char *cipherlist;
1937
1938 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1939 return NULL;
1940 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1941 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001942 /* Clearing the error queue is necessary on some OpenSSL versions,
1943 otherwise the error will be reported again when another SSL call
1944 is done. */
1945 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001946 PyErr_SetString(PySSLErrorObject,
1947 "No cipher can be selected.");
1948 return NULL;
1949 }
1950 Py_RETURN_NONE;
1951}
1952
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001953#ifdef OPENSSL_NPN_NEGOTIATED
1954/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
1955static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001956_advertiseNPN_cb(SSL *s,
1957 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001958 void *args)
1959{
1960 PySSLContext *ssl_ctx = (PySSLContext *) args;
1961
1962 if (ssl_ctx->npn_protocols == NULL) {
1963 *data = (unsigned char *) "";
1964 *len = 0;
1965 } else {
1966 *data = (unsigned char *) ssl_ctx->npn_protocols;
1967 *len = ssl_ctx->npn_protocols_len;
1968 }
1969
1970 return SSL_TLSEXT_ERR_OK;
1971}
1972/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
1973static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001974_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001975 unsigned char **out, unsigned char *outlen,
1976 const unsigned char *server, unsigned int server_len,
1977 void *args)
1978{
1979 PySSLContext *ssl_ctx = (PySSLContext *) args;
1980
1981 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
1982 int client_len;
1983
1984 if (client == NULL) {
1985 client = (unsigned char *) "";
1986 client_len = 0;
1987 } else {
1988 client_len = ssl_ctx->npn_protocols_len;
1989 }
1990
1991 SSL_select_next_proto(out, outlen,
1992 server, server_len,
1993 client, client_len);
1994
1995 return SSL_TLSEXT_ERR_OK;
1996}
1997#endif
1998
1999static PyObject *
2000_set_npn_protocols(PySSLContext *self, PyObject *args)
2001{
2002#ifdef OPENSSL_NPN_NEGOTIATED
2003 Py_buffer protos;
2004
2005 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2006 return NULL;
2007
Christian Heimes5cb31c92012-09-20 12:42:54 +02002008 if (self->npn_protocols != NULL) {
2009 PyMem_Free(self->npn_protocols);
2010 }
2011
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002012 self->npn_protocols = PyMem_Malloc(protos.len);
2013 if (self->npn_protocols == NULL) {
2014 PyBuffer_Release(&protos);
2015 return PyErr_NoMemory();
2016 }
2017 memcpy(self->npn_protocols, protos.buf, protos.len);
2018 self->npn_protocols_len = (int) protos.len;
2019
2020 /* set both server and client callbacks, because the context can
2021 * be used to create both types of sockets */
2022 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2023 _advertiseNPN_cb,
2024 self);
2025 SSL_CTX_set_next_proto_select_cb(self->ctx,
2026 _selectNPN_cb,
2027 self);
2028
2029 PyBuffer_Release(&protos);
2030 Py_RETURN_NONE;
2031#else
2032 PyErr_SetString(PyExc_NotImplementedError,
2033 "The NPN extension requires OpenSSL 1.0.1 or later.");
2034 return NULL;
2035#endif
2036}
2037
Antoine Pitrou152efa22010-05-16 18:19:27 +00002038static PyObject *
2039get_verify_mode(PySSLContext *self, void *c)
2040{
2041 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2042 case SSL_VERIFY_NONE:
2043 return PyLong_FromLong(PY_SSL_CERT_NONE);
2044 case SSL_VERIFY_PEER:
2045 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2046 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2047 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2048 }
2049 PyErr_SetString(PySSLErrorObject,
2050 "invalid return value from SSL_CTX_get_verify_mode");
2051 return NULL;
2052}
2053
2054static int
2055set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2056{
2057 int n, mode;
2058 if (!PyArg_Parse(arg, "i", &n))
2059 return -1;
2060 if (n == PY_SSL_CERT_NONE)
2061 mode = SSL_VERIFY_NONE;
2062 else if (n == PY_SSL_CERT_OPTIONAL)
2063 mode = SSL_VERIFY_PEER;
2064 else if (n == PY_SSL_CERT_REQUIRED)
2065 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2066 else {
2067 PyErr_SetString(PyExc_ValueError,
2068 "invalid value for verify_mode");
2069 return -1;
2070 }
2071 SSL_CTX_set_verify(self->ctx, mode, NULL);
2072 return 0;
2073}
2074
2075static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002076get_options(PySSLContext *self, void *c)
2077{
2078 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2079}
2080
2081static int
2082set_options(PySSLContext *self, PyObject *arg, void *c)
2083{
2084 long new_opts, opts, set, clear;
2085 if (!PyArg_Parse(arg, "l", &new_opts))
2086 return -1;
2087 opts = SSL_CTX_get_options(self->ctx);
2088 clear = opts & ~new_opts;
2089 set = ~opts & new_opts;
2090 if (clear) {
2091#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2092 SSL_CTX_clear_options(self->ctx, clear);
2093#else
2094 PyErr_SetString(PyExc_ValueError,
2095 "can't clear options before OpenSSL 0.9.8m");
2096 return -1;
2097#endif
2098 }
2099 if (set)
2100 SSL_CTX_set_options(self->ctx, set);
2101 return 0;
2102}
2103
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002104typedef struct {
2105 PyThreadState *thread_state;
2106 PyObject *callable;
2107 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002108 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002109 int error;
2110} _PySSLPasswordInfo;
2111
2112static int
2113_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2114 const char *bad_type_error)
2115{
2116 /* Set the password and size fields of a _PySSLPasswordInfo struct
2117 from a unicode, bytes, or byte array object.
2118 The password field will be dynamically allocated and must be freed
2119 by the caller */
2120 PyObject *password_bytes = NULL;
2121 const char *data = NULL;
2122 Py_ssize_t size;
2123
2124 if (PyUnicode_Check(password)) {
2125 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2126 if (!password_bytes) {
2127 goto error;
2128 }
2129 data = PyBytes_AS_STRING(password_bytes);
2130 size = PyBytes_GET_SIZE(password_bytes);
2131 } else if (PyBytes_Check(password)) {
2132 data = PyBytes_AS_STRING(password);
2133 size = PyBytes_GET_SIZE(password);
2134 } else if (PyByteArray_Check(password)) {
2135 data = PyByteArray_AS_STRING(password);
2136 size = PyByteArray_GET_SIZE(password);
2137 } else {
2138 PyErr_SetString(PyExc_TypeError, bad_type_error);
2139 goto error;
2140 }
2141
Victor Stinner9ee02032013-06-23 15:08:23 +02002142 if (size > (Py_ssize_t)INT_MAX) {
2143 PyErr_Format(PyExc_ValueError,
2144 "password cannot be longer than %d bytes", INT_MAX);
2145 goto error;
2146 }
2147
Victor Stinner11ebff22013-07-07 17:07:52 +02002148 PyMem_Free(pw_info->password);
2149 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002150 if (!pw_info->password) {
2151 PyErr_SetString(PyExc_MemoryError,
2152 "unable to allocate password buffer");
2153 goto error;
2154 }
2155 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002156 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002157
2158 Py_XDECREF(password_bytes);
2159 return 1;
2160
2161error:
2162 Py_XDECREF(password_bytes);
2163 return 0;
2164}
2165
2166static int
2167_password_callback(char *buf, int size, int rwflag, void *userdata)
2168{
2169 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2170 PyObject *fn_ret = NULL;
2171
2172 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2173
2174 if (pw_info->callable) {
2175 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2176 if (!fn_ret) {
2177 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2178 core python API, so we could use it to add a frame here */
2179 goto error;
2180 }
2181
2182 if (!_pwinfo_set(pw_info, fn_ret,
2183 "password callback must return a string")) {
2184 goto error;
2185 }
2186 Py_CLEAR(fn_ret);
2187 }
2188
2189 if (pw_info->size > size) {
2190 PyErr_Format(PyExc_ValueError,
2191 "password cannot be longer than %d bytes", size);
2192 goto error;
2193 }
2194
2195 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2196 memcpy(buf, pw_info->password, pw_info->size);
2197 return pw_info->size;
2198
2199error:
2200 Py_XDECREF(fn_ret);
2201 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2202 pw_info->error = 1;
2203 return -1;
2204}
2205
Antoine Pitroub5218772010-05-21 09:56:06 +00002206static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002207load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2208{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002209 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2210 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002211 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002212 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2213 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2214 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002215 int r;
2216
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002217 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002218 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002219 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002220 "O|OO:load_cert_chain", kwlist,
2221 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002222 return NULL;
2223 if (keyfile == Py_None)
2224 keyfile = NULL;
2225 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2226 PyErr_SetString(PyExc_TypeError,
2227 "certfile should be a valid filesystem path");
2228 return NULL;
2229 }
2230 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2231 PyErr_SetString(PyExc_TypeError,
2232 "keyfile should be a valid filesystem path");
2233 goto error;
2234 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002235 if (password && password != Py_None) {
2236 if (PyCallable_Check(password)) {
2237 pw_info.callable = password;
2238 } else if (!_pwinfo_set(&pw_info, password,
2239 "password should be a string or callable")) {
2240 goto error;
2241 }
2242 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2243 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2244 }
2245 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002246 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2247 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002248 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002249 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002250 if (pw_info.error) {
2251 ERR_clear_error();
2252 /* the password callback has already set the error information */
2253 }
2254 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002255 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002256 PyErr_SetFromErrno(PyExc_IOError);
2257 }
2258 else {
2259 _setSSLError(NULL, 0, __FILE__, __LINE__);
2260 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002261 goto error;
2262 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002263 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002264 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002265 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2266 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002267 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2268 Py_CLEAR(keyfile_bytes);
2269 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002270 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002271 if (pw_info.error) {
2272 ERR_clear_error();
2273 /* the password callback has already set the error information */
2274 }
2275 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002276 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002277 PyErr_SetFromErrno(PyExc_IOError);
2278 }
2279 else {
2280 _setSSLError(NULL, 0, __FILE__, __LINE__);
2281 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002282 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002283 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002284 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002285 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002286 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002287 if (r != 1) {
2288 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002289 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002290 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002291 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2292 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002293 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002294 Py_RETURN_NONE;
2295
2296error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002297 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2298 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002299 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002300 Py_XDECREF(keyfile_bytes);
2301 Py_XDECREF(certfile_bytes);
2302 return NULL;
2303}
2304
2305static PyObject *
2306load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2307{
2308 char *kwlist[] = {"cafile", "capath", NULL};
2309 PyObject *cafile = NULL, *capath = NULL;
2310 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2311 const char *cafile_buf = NULL, *capath_buf = NULL;
2312 int r;
2313
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002314 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002315 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2316 "|OO:load_verify_locations", kwlist,
2317 &cafile, &capath))
2318 return NULL;
2319 if (cafile == Py_None)
2320 cafile = NULL;
2321 if (capath == Py_None)
2322 capath = NULL;
2323 if (cafile == NULL && capath == NULL) {
2324 PyErr_SetString(PyExc_TypeError,
2325 "cafile and capath cannot be both omitted");
2326 return NULL;
2327 }
2328 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2329 PyErr_SetString(PyExc_TypeError,
2330 "cafile should be a valid filesystem path");
2331 return NULL;
2332 }
2333 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00002334 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002335 PyErr_SetString(PyExc_TypeError,
2336 "capath should be a valid filesystem path");
2337 return NULL;
2338 }
2339 if (cafile)
2340 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2341 if (capath)
2342 capath_buf = PyBytes_AS_STRING(capath_bytes);
2343 PySSL_BEGIN_ALLOW_THREADS
2344 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2345 PySSL_END_ALLOW_THREADS
2346 Py_XDECREF(cafile_bytes);
2347 Py_XDECREF(capath_bytes);
2348 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002349 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002350 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002351 PyErr_SetFromErrno(PyExc_IOError);
2352 }
2353 else {
2354 _setSSLError(NULL, 0, __FILE__, __LINE__);
2355 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002356 return NULL;
2357 }
2358 Py_RETURN_NONE;
2359}
2360
2361static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002362load_dh_params(PySSLContext *self, PyObject *filepath)
2363{
2364 FILE *f;
2365 DH *dh;
2366
Victor Stinnerdaf45552013-08-28 00:53:59 +02002367 f = _Py_fopen_obj(filepath, "rb");
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002368 if (f == NULL) {
2369 if (!PyErr_Occurred())
2370 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2371 return NULL;
2372 }
2373 errno = 0;
2374 PySSL_BEGIN_ALLOW_THREADS
2375 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002376 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002377 PySSL_END_ALLOW_THREADS
2378 if (dh == NULL) {
2379 if (errno != 0) {
2380 ERR_clear_error();
2381 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2382 }
2383 else {
2384 _setSSLError(NULL, 0, __FILE__, __LINE__);
2385 }
2386 return NULL;
2387 }
2388 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2389 _setSSLError(NULL, 0, __FILE__, __LINE__);
2390 DH_free(dh);
2391 Py_RETURN_NONE;
2392}
2393
2394static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002395context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2396{
Antoine Pitroud5323212010-10-22 18:19:07 +00002397 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002398 PySocketSockObject *sock;
2399 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002400 char *hostname = NULL;
2401 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002402
Antoine Pitroud5323212010-10-22 18:19:07 +00002403 /* server_hostname is either None (or absent), or to be encoded
2404 using the idna encoding. */
2405 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002406 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002407 &sock, &server_side,
2408 Py_TYPE(Py_None), &hostname_obj)) {
2409 PyErr_Clear();
2410 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2411 PySocketModule.Sock_Type,
2412 &sock, &server_side,
2413 "idna", &hostname))
2414 return NULL;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002415#if !HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00002416 PyMem_Free(hostname);
2417 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2418 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002419 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002420#endif
2421 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002422
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002423 res = (PyObject *) newPySSLSocket(self, sock, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +00002424 hostname);
2425 if (hostname != NULL)
2426 PyMem_Free(hostname);
2427 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002428}
2429
Antoine Pitroub0182c82010-10-12 20:09:02 +00002430static PyObject *
2431session_stats(PySSLContext *self, PyObject *unused)
2432{
2433 int r;
2434 PyObject *value, *stats = PyDict_New();
2435 if (!stats)
2436 return NULL;
2437
2438#define ADD_STATS(SSL_NAME, KEY_NAME) \
2439 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2440 if (value == NULL) \
2441 goto error; \
2442 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2443 Py_DECREF(value); \
2444 if (r < 0) \
2445 goto error;
2446
2447 ADD_STATS(number, "number");
2448 ADD_STATS(connect, "connect");
2449 ADD_STATS(connect_good, "connect_good");
2450 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2451 ADD_STATS(accept, "accept");
2452 ADD_STATS(accept_good, "accept_good");
2453 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2454 ADD_STATS(accept, "accept");
2455 ADD_STATS(hits, "hits");
2456 ADD_STATS(misses, "misses");
2457 ADD_STATS(timeouts, "timeouts");
2458 ADD_STATS(cache_full, "cache_full");
2459
2460#undef ADD_STATS
2461
2462 return stats;
2463
2464error:
2465 Py_DECREF(stats);
2466 return NULL;
2467}
2468
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002469static PyObject *
2470set_default_verify_paths(PySSLContext *self, PyObject *unused)
2471{
2472 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2473 _setSSLError(NULL, 0, __FILE__, __LINE__);
2474 return NULL;
2475 }
2476 Py_RETURN_NONE;
2477}
2478
Antoine Pitrou501da612011-12-21 09:27:41 +01002479#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002480static PyObject *
2481set_ecdh_curve(PySSLContext *self, PyObject *name)
2482{
2483 PyObject *name_bytes;
2484 int nid;
2485 EC_KEY *key;
2486
2487 if (!PyUnicode_FSConverter(name, &name_bytes))
2488 return NULL;
2489 assert(PyBytes_Check(name_bytes));
2490 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2491 Py_DECREF(name_bytes);
2492 if (nid == 0) {
2493 PyErr_Format(PyExc_ValueError,
2494 "unknown elliptic curve name %R", name);
2495 return NULL;
2496 }
2497 key = EC_KEY_new_by_curve_name(nid);
2498 if (key == NULL) {
2499 _setSSLError(NULL, 0, __FILE__, __LINE__);
2500 return NULL;
2501 }
2502 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2503 EC_KEY_free(key);
2504 Py_RETURN_NONE;
2505}
Antoine Pitrou501da612011-12-21 09:27:41 +01002506#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002507
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002508#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002509static int
2510_servername_callback(SSL *s, int *al, void *args)
2511{
2512 int ret;
2513 PySSLContext *ssl_ctx = (PySSLContext *) args;
2514 PySSLSocket *ssl;
2515 PyObject *servername_o;
2516 PyObject *servername_idna;
2517 PyObject *result;
2518 /* The high-level ssl.SSLSocket object */
2519 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002520 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01002521#ifdef WITH_THREAD
2522 PyGILState_STATE gstate = PyGILState_Ensure();
2523#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002524
2525 if (ssl_ctx->set_hostname == NULL) {
2526 /* remove race condition in this the call back while if removing the
2527 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01002528#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002529 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002530#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01002531 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002532 }
2533
2534 ssl = SSL_get_app_data(s);
2535 assert(PySSLSocket_Check(ssl));
2536 ssl_socket = PyWeakref_GetObject(ssl->Socket);
2537 Py_INCREF(ssl_socket);
2538 if (ssl_socket == Py_None) {
2539 goto error;
2540 }
Victor Stinner7e001512013-06-25 00:44:31 +02002541
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002542 if (servername == NULL) {
2543 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2544 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002545 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002546 else {
2547 servername_o = PyBytes_FromString(servername);
2548 if (servername_o == NULL) {
2549 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2550 goto error;
2551 }
2552 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2553 if (servername_idna == NULL) {
2554 PyErr_WriteUnraisable(servername_o);
2555 Py_DECREF(servername_o);
2556 goto error;
2557 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002558 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002559 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2560 servername_idna, ssl_ctx, NULL);
2561 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002562 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002563 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002564
2565 if (result == NULL) {
2566 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2567 *al = SSL_AD_HANDSHAKE_FAILURE;
2568 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2569 }
2570 else {
2571 if (result != Py_None) {
2572 *al = (int) PyLong_AsLong(result);
2573 if (PyErr_Occurred()) {
2574 PyErr_WriteUnraisable(result);
2575 *al = SSL_AD_INTERNAL_ERROR;
2576 }
2577 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2578 }
2579 else {
2580 ret = SSL_TLSEXT_ERR_OK;
2581 }
2582 Py_DECREF(result);
2583 }
2584
Stefan Krah20d60802013-01-17 17:07:17 +01002585#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002586 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002587#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002588 return ret;
2589
2590error:
2591 Py_DECREF(ssl_socket);
2592 *al = SSL_AD_INTERNAL_ERROR;
2593 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01002594#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002595 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002596#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002597 return ret;
2598}
Antoine Pitroua5963382013-03-30 16:39:00 +01002599#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002600
2601PyDoc_STRVAR(PySSL_set_servername_callback_doc,
2602"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002603\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002604This sets a callback that will be called when a server name is provided by\n\
2605the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002606\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002607If the argument is None then the callback is disabled. The method is called\n\
2608with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002609See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002610
2611static PyObject *
2612set_servername_callback(PySSLContext *self, PyObject *args)
2613{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002614#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002615 PyObject *cb;
2616
2617 if (!PyArg_ParseTuple(args, "O", &cb))
2618 return NULL;
2619
2620 Py_CLEAR(self->set_hostname);
2621 if (cb == Py_None) {
2622 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2623 }
2624 else {
2625 if (!PyCallable_Check(cb)) {
2626 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2627 PyErr_SetString(PyExc_TypeError,
2628 "not a callable object");
2629 return NULL;
2630 }
2631 Py_INCREF(cb);
2632 self->set_hostname = cb;
2633 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
2634 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
2635 }
2636 Py_RETURN_NONE;
2637#else
2638 PyErr_SetString(PyExc_NotImplementedError,
2639 "The TLS extension servername callback, "
2640 "SSL_CTX_set_tlsext_servername_callback, "
2641 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002642 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002643#endif
2644}
2645
Christian Heimes9a5395a2013-06-17 15:44:12 +02002646PyDoc_STRVAR(PySSL_get_stats_doc,
2647"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
2648\n\
2649Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
2650CA extension and certificate revocation lists inside the context's cert\n\
2651store.\n\
2652NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2653been used at least once.");
2654
2655static PyObject *
2656cert_store_stats(PySSLContext *self)
2657{
2658 X509_STORE *store;
2659 X509_OBJECT *obj;
2660 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
2661
2662 store = SSL_CTX_get_cert_store(self->ctx);
2663 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
2664 obj = sk_X509_OBJECT_value(store->objs, i);
2665 switch (obj->type) {
2666 case X509_LU_X509:
2667 x509++;
2668 if (X509_check_ca(obj->data.x509)) {
2669 ca++;
2670 }
2671 break;
2672 case X509_LU_CRL:
2673 crl++;
2674 break;
2675 case X509_LU_PKEY:
2676 pkey++;
2677 break;
2678 default:
2679 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
2680 * As far as I can tell they are internal states and never
2681 * stored in a cert store */
2682 break;
2683 }
2684 }
2685 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
2686 "x509_ca", ca);
2687}
2688
2689PyDoc_STRVAR(PySSL_get_ca_certs_doc,
2690"get_ca_certs([der=False]) -> list of loaded certificate\n\
2691\n\
2692Returns a list of dicts with information of loaded CA certs. If the\n\
2693optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
2694NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2695been used at least once.");
2696
2697static PyObject *
2698get_ca_certs(PySSLContext *self, PyObject *args)
2699{
2700 X509_STORE *store;
2701 PyObject *ci = NULL, *rlist = NULL;
2702 int i;
2703 int binary_mode = 0;
2704
2705 if (!PyArg_ParseTuple(args, "|p:get_ca_certs", &binary_mode)) {
2706 return NULL;
2707 }
2708
2709 if ((rlist = PyList_New(0)) == NULL) {
2710 return NULL;
2711 }
2712
2713 store = SSL_CTX_get_cert_store(self->ctx);
2714 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
2715 X509_OBJECT *obj;
2716 X509 *cert;
2717
2718 obj = sk_X509_OBJECT_value(store->objs, i);
2719 if (obj->type != X509_LU_X509) {
2720 /* not a x509 cert */
2721 continue;
2722 }
2723 /* CA for any purpose */
2724 cert = obj->data.x509;
2725 if (!X509_check_ca(cert)) {
2726 continue;
2727 }
2728 if (binary_mode) {
2729 ci = _certificate_to_der(cert);
2730 } else {
2731 ci = _decode_certificate(cert);
2732 }
2733 if (ci == NULL) {
2734 goto error;
2735 }
2736 if (PyList_Append(rlist, ci) == -1) {
2737 goto error;
2738 }
2739 Py_CLEAR(ci);
2740 }
2741 return rlist;
2742
2743 error:
2744 Py_XDECREF(ci);
2745 Py_XDECREF(rlist);
2746 return NULL;
2747}
2748
2749
Antoine Pitrou152efa22010-05-16 18:19:27 +00002750static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002751 {"options", (getter) get_options,
2752 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002753 {"verify_mode", (getter) get_verify_mode,
2754 (setter) set_verify_mode, NULL},
2755 {NULL}, /* sentinel */
2756};
2757
2758static struct PyMethodDef context_methods[] = {
2759 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2760 METH_VARARGS | METH_KEYWORDS, NULL},
2761 {"set_ciphers", (PyCFunction) set_ciphers,
2762 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002763 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2764 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002765 {"load_cert_chain", (PyCFunction) load_cert_chain,
2766 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002767 {"load_dh_params", (PyCFunction) load_dh_params,
2768 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002769 {"load_verify_locations", (PyCFunction) load_verify_locations,
2770 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002771 {"session_stats", (PyCFunction) session_stats,
2772 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002773 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2774 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002775#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002776 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2777 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002778#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002779 {"set_servername_callback", (PyCFunction) set_servername_callback,
2780 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02002781 {"cert_store_stats", (PyCFunction) cert_store_stats,
2782 METH_NOARGS, PySSL_get_stats_doc},
2783 {"get_ca_certs", (PyCFunction) get_ca_certs,
2784 METH_VARARGS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002785 {NULL, NULL} /* sentinel */
2786};
2787
2788static PyTypeObject PySSLContext_Type = {
2789 PyVarObject_HEAD_INIT(NULL, 0)
2790 "_ssl._SSLContext", /*tp_name*/
2791 sizeof(PySSLContext), /*tp_basicsize*/
2792 0, /*tp_itemsize*/
2793 (destructor)context_dealloc, /*tp_dealloc*/
2794 0, /*tp_print*/
2795 0, /*tp_getattr*/
2796 0, /*tp_setattr*/
2797 0, /*tp_reserved*/
2798 0, /*tp_repr*/
2799 0, /*tp_as_number*/
2800 0, /*tp_as_sequence*/
2801 0, /*tp_as_mapping*/
2802 0, /*tp_hash*/
2803 0, /*tp_call*/
2804 0, /*tp_str*/
2805 0, /*tp_getattro*/
2806 0, /*tp_setattro*/
2807 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002808 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002809 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002810 (traverseproc) context_traverse, /*tp_traverse*/
2811 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002812 0, /*tp_richcompare*/
2813 0, /*tp_weaklistoffset*/
2814 0, /*tp_iter*/
2815 0, /*tp_iternext*/
2816 context_methods, /*tp_methods*/
2817 0, /*tp_members*/
2818 context_getsetlist, /*tp_getset*/
2819 0, /*tp_base*/
2820 0, /*tp_dict*/
2821 0, /*tp_descr_get*/
2822 0, /*tp_descr_set*/
2823 0, /*tp_dictoffset*/
2824 0, /*tp_init*/
2825 0, /*tp_alloc*/
2826 context_new, /*tp_new*/
2827};
2828
2829
2830
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002831#ifdef HAVE_OPENSSL_RAND
2832
2833/* helper routines for seeding the SSL PRNG */
2834static PyObject *
2835PySSL_RAND_add(PyObject *self, PyObject *args)
2836{
2837 char *buf;
2838 int len;
2839 double entropy;
2840
2841 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002842 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002843 RAND_add(buf, len, entropy);
2844 Py_INCREF(Py_None);
2845 return Py_None;
2846}
2847
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002848PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002849"RAND_add(string, entropy)\n\
2850\n\
2851Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002852bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002853
2854static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002855PySSL_RAND(int len, int pseudo)
2856{
2857 int ok;
2858 PyObject *bytes;
2859 unsigned long err;
2860 const char *errstr;
2861 PyObject *v;
2862
2863 bytes = PyBytes_FromStringAndSize(NULL, len);
2864 if (bytes == NULL)
2865 return NULL;
2866 if (pseudo) {
2867 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2868 if (ok == 0 || ok == 1)
2869 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2870 }
2871 else {
2872 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2873 if (ok == 1)
2874 return bytes;
2875 }
2876 Py_DECREF(bytes);
2877
2878 err = ERR_get_error();
2879 errstr = ERR_reason_error_string(err);
2880 v = Py_BuildValue("(ks)", err, errstr);
2881 if (v != NULL) {
2882 PyErr_SetObject(PySSLErrorObject, v);
2883 Py_DECREF(v);
2884 }
2885 return NULL;
2886}
2887
2888static PyObject *
2889PySSL_RAND_bytes(PyObject *self, PyObject *args)
2890{
2891 int len;
2892 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2893 return NULL;
2894 return PySSL_RAND(len, 0);
2895}
2896
2897PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2898"RAND_bytes(n) -> bytes\n\
2899\n\
2900Generate n cryptographically strong pseudo-random bytes.");
2901
2902static PyObject *
2903PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2904{
2905 int len;
2906 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2907 return NULL;
2908 return PySSL_RAND(len, 1);
2909}
2910
2911PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2912"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2913\n\
2914Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2915generated are cryptographically strong.");
2916
2917static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002918PySSL_RAND_status(PyObject *self)
2919{
Christian Heimes217cfd12007-12-02 14:31:20 +00002920 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002921}
2922
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002923PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002924"RAND_status() -> 0 or 1\n\
2925\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002926Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2927It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2928using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002929
2930static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002931PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002932{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002933 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002934 int bytes;
2935
Jesus Ceac8754a12012-09-11 02:00:58 +02002936 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002937 PyUnicode_FSConverter, &path))
2938 return NULL;
2939
2940 bytes = RAND_egd(PyBytes_AsString(path));
2941 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002942 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002943 PyErr_SetString(PySSLErrorObject,
2944 "EGD connection failed or EGD did not return "
2945 "enough data to seed the PRNG");
2946 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002947 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002948 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002949}
2950
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002951PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002952"RAND_egd(path) -> bytes\n\
2953\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002954Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2955Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02002956fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002957
Christian Heimesf77b4b22013-08-21 13:26:05 +02002958#endif /* HAVE_OPENSSL_RAND */
2959
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002960
Christian Heimes6d7ad132013-06-09 18:02:55 +02002961PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
2962"get_default_verify_paths() -> tuple\n\
2963\n\
2964Return search paths and environment vars that are used by SSLContext's\n\
2965set_default_verify_paths() to load default CAs. The values are\n\
2966'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
2967
2968static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02002969PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02002970{
2971 PyObject *ofile_env = NULL;
2972 PyObject *ofile = NULL;
2973 PyObject *odir_env = NULL;
2974 PyObject *odir = NULL;
2975
2976#define convert(info, target) { \
2977 const char *tmp = (info); \
2978 target = NULL; \
2979 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
2980 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
2981 target = PyBytes_FromString(tmp); } \
2982 if (!target) goto error; \
2983 } while(0)
2984
2985 convert(X509_get_default_cert_file_env(), ofile_env);
2986 convert(X509_get_default_cert_file(), ofile);
2987 convert(X509_get_default_cert_dir_env(), odir_env);
2988 convert(X509_get_default_cert_dir(), odir);
2989#undef convert
2990
Christian Heimes200bb1b2013-06-14 15:14:29 +02002991 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02002992
2993 error:
2994 Py_XDECREF(ofile_env);
2995 Py_XDECREF(ofile);
2996 Py_XDECREF(odir_env);
2997 Py_XDECREF(odir);
2998 return NULL;
2999}
3000
Christian Heimes46bebee2013-06-09 19:03:31 +02003001#ifdef _MSC_VER
3002PyDoc_STRVAR(PySSL_enum_cert_store_doc,
3003"enum_cert_store(store_name, cert_type='certificate') -> []\n\
3004\n\
3005Retrieve certificates from Windows' cert store. store_name may be one of\n\
3006'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3007cert_type must be either 'certificate' or 'crl'.\n\
3008The function returns a list of (bytes, encoding_type) tuples. The\n\
3009encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3010PKCS_7_ASN_ENCODING.");
Bill Janssen40a0f662008-08-12 16:56:25 +00003011
Christian Heimes46bebee2013-06-09 19:03:31 +02003012static PyObject *
3013PySSL_enum_cert_store(PyObject *self, PyObject *args, PyObject *kwds)
3014{
3015 char *kwlist[] = {"store_name", "cert_type", NULL};
3016 char *store_name;
3017 char *cert_type = "certificate";
3018 HCERTSTORE hStore = NULL;
3019 PyObject *result = NULL;
3020 PyObject *tup = NULL, *cert = NULL, *enc = NULL;
3021 int ok = 1;
3022
3023 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_cert_store",
3024 kwlist, &store_name, &cert_type)) {
3025 return NULL;
3026 }
3027
3028 if ((strcmp(cert_type, "certificate") != 0) &&
3029 (strcmp(cert_type, "crl") != 0)) {
3030 return PyErr_Format(PyExc_ValueError,
3031 "cert_type must be 'certificate' or 'crl', "
3032 "not %.100s", cert_type);
3033 }
3034
3035 if ((result = PyList_New(0)) == NULL) {
3036 return NULL;
3037 }
3038
Richard Oudkerkcabbde92013-08-24 23:46:27 +01003039 if ((hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name)) == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003040 Py_DECREF(result);
3041 return PyErr_SetFromWindowsErr(GetLastError());
3042 }
3043
3044 if (strcmp(cert_type, "certificate") == 0) {
3045 PCCERT_CONTEXT pCertCtx = NULL;
3046 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3047 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3048 pCertCtx->cbCertEncoded);
3049 if (!cert) {
3050 ok = 0;
3051 break;
3052 }
3053 if ((enc = PyLong_FromLong(pCertCtx->dwCertEncodingType)) == NULL) {
3054 ok = 0;
3055 break;
3056 }
3057 if ((tup = PyTuple_New(2)) == NULL) {
3058 ok = 0;
3059 break;
3060 }
3061 PyTuple_SET_ITEM(tup, 0, cert); cert = NULL;
3062 PyTuple_SET_ITEM(tup, 1, enc); enc = NULL;
3063
3064 if (PyList_Append(result, tup) < 0) {
3065 ok = 0;
3066 break;
3067 }
3068 Py_CLEAR(tup);
3069 }
3070 if (pCertCtx) {
3071 /* loop ended with an error, need to clean up context manually */
3072 CertFreeCertificateContext(pCertCtx);
3073 }
3074 } else {
3075 PCCRL_CONTEXT pCrlCtx = NULL;
3076 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3077 cert = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3078 pCrlCtx->cbCrlEncoded);
3079 if (!cert) {
3080 ok = 0;
3081 break;
3082 }
3083 if ((enc = PyLong_FromLong(pCrlCtx->dwCertEncodingType)) == NULL) {
3084 ok = 0;
3085 break;
3086 }
3087 if ((tup = PyTuple_New(2)) == NULL) {
3088 ok = 0;
3089 break;
3090 }
3091 PyTuple_SET_ITEM(tup, 0, cert); cert = NULL;
3092 PyTuple_SET_ITEM(tup, 1, enc); enc = NULL;
3093
3094 if (PyList_Append(result, tup) < 0) {
3095 ok = 0;
3096 break;
3097 }
3098 Py_CLEAR(tup);
3099 }
3100 if (pCrlCtx) {
3101 /* loop ended with an error, need to clean up context manually */
3102 CertFreeCRLContext(pCrlCtx);
3103 }
3104 }
3105
3106 /* In error cases cert, enc and tup may not be NULL */
3107 Py_XDECREF(cert);
3108 Py_XDECREF(enc);
3109 Py_XDECREF(tup);
3110
3111 if (!CertCloseStore(hStore, 0)) {
3112 /* This error case might shadow another exception.*/
3113 Py_DECREF(result);
3114 return PyErr_SetFromWindowsErr(GetLastError());
3115 }
3116 if (ok) {
3117 return result;
3118 } else {
3119 Py_DECREF(result);
3120 return NULL;
3121 }
3122}
3123#endif
Bill Janssen40a0f662008-08-12 16:56:25 +00003124
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003125/* List of functions exported by this module. */
3126
3127static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003128 {"_test_decode_cert", PySSL_test_decode_certificate,
3129 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003130#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003131 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3132 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02003133 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
3134 PySSL_RAND_bytes_doc},
3135 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
3136 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003137 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003138 PySSL_RAND_egd_doc},
3139 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3140 PySSL_RAND_status_doc},
Christian Heimes142ec2c2013-06-09 18:29:54 +02003141#endif
Christian Heimes200bb1b2013-06-14 15:14:29 +02003142 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02003143 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003144#ifdef _MSC_VER
3145 {"enum_cert_store", (PyCFunction)PySSL_enum_cert_store,
3146 METH_VARARGS | METH_KEYWORDS, PySSL_enum_cert_store_doc},
3147#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003148 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003149};
3150
3151
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003152#ifdef WITH_THREAD
3153
3154/* an implementation of OpenSSL threading operations in terms
3155 of the Python C thread library */
3156
3157static PyThread_type_lock *_ssl_locks = NULL;
3158
Christian Heimes4d98ca92013-08-19 17:36:29 +02003159#if OPENSSL_VERSION_NUMBER >= 0x10000000
3160/* use new CRYPTO_THREADID API. */
3161static void
3162_ssl_threadid_callback(CRYPTO_THREADID *id)
3163{
3164 CRYPTO_THREADID_set_numeric(id,
3165 (unsigned long)PyThread_get_thread_ident());
3166}
3167#else
3168/* deprecated CRYPTO_set_id_callback() API. */
3169static unsigned long
3170_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003171 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003172}
Christian Heimes4d98ca92013-08-19 17:36:29 +02003173#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003174
Bill Janssen6e027db2007-11-15 22:23:56 +00003175static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003176 (int mode, int n, const char *file, int line) {
3177 /* this function is needed to perform locking on shared data
3178 structures. (Note that OpenSSL uses a number of global data
3179 structures that will be implicitly shared whenever multiple
3180 threads use OpenSSL.) Multi-threaded applications will
3181 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003182
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003183 locking_function() must be able to handle up to
3184 CRYPTO_num_locks() different mutex locks. It sets the n-th
3185 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003186
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003187 file and line are the file number of the function setting the
3188 lock. They can be useful for debugging.
3189 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003190
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003191 if ((_ssl_locks == NULL) ||
3192 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3193 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003194
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003195 if (mode & CRYPTO_LOCK) {
3196 PyThread_acquire_lock(_ssl_locks[n], 1);
3197 } else {
3198 PyThread_release_lock(_ssl_locks[n]);
3199 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003200}
3201
3202static int _setup_ssl_threads(void) {
3203
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003204 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003205
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003206 if (_ssl_locks == NULL) {
3207 _ssl_locks_count = CRYPTO_num_locks();
3208 _ssl_locks = (PyThread_type_lock *)
Victor Stinnerb6404912013-07-07 16:21:41 +02003209 PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003210 if (_ssl_locks == NULL)
3211 return 0;
3212 memset(_ssl_locks, 0,
3213 sizeof(PyThread_type_lock) * _ssl_locks_count);
3214 for (i = 0; i < _ssl_locks_count; i++) {
3215 _ssl_locks[i] = PyThread_allocate_lock();
3216 if (_ssl_locks[i] == NULL) {
3217 unsigned int j;
3218 for (j = 0; j < i; j++) {
3219 PyThread_free_lock(_ssl_locks[j]);
3220 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003221 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003222 return 0;
3223 }
3224 }
3225 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003226#if OPENSSL_VERSION_NUMBER >= 0x10000000
3227 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
3228#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003229 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003230#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003231 }
3232 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003233}
3234
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003235#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003236
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003237PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003238"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003239for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003240
Martin v. Löwis1a214512008-06-11 05:26:20 +00003241
3242static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003243 PyModuleDef_HEAD_INIT,
3244 "_ssl",
3245 module_doc,
3246 -1,
3247 PySSL_methods,
3248 NULL,
3249 NULL,
3250 NULL,
3251 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003252};
3253
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003254
3255static void
3256parse_openssl_version(unsigned long libver,
3257 unsigned int *major, unsigned int *minor,
3258 unsigned int *fix, unsigned int *patch,
3259 unsigned int *status)
3260{
3261 *status = libver & 0xF;
3262 libver >>= 4;
3263 *patch = libver & 0xFF;
3264 libver >>= 8;
3265 *fix = libver & 0xFF;
3266 libver >>= 8;
3267 *minor = libver & 0xFF;
3268 libver >>= 8;
3269 *major = libver & 0xFF;
3270}
3271
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003272PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003273PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003274{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003275 PyObject *m, *d, *r;
3276 unsigned long libver;
3277 unsigned int major, minor, fix, patch, status;
3278 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003279 struct py_ssl_error_code *errcode;
3280 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003281
Antoine Pitrou152efa22010-05-16 18:19:27 +00003282 if (PyType_Ready(&PySSLContext_Type) < 0)
3283 return NULL;
3284 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003285 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003286
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003287 m = PyModule_Create(&_sslmodule);
3288 if (m == NULL)
3289 return NULL;
3290 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003291
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003292 /* Load _socket module and its C API */
3293 socket_api = PySocketModule_ImportModuleAndAPI();
3294 if (!socket_api)
3295 return NULL;
3296 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003297
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003298 /* Init OpenSSL */
3299 SSL_load_error_strings();
3300 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003301#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003302 /* note that this will start threading if not already started */
3303 if (!_setup_ssl_threads()) {
3304 return NULL;
3305 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003306#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003307 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003308
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003309 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003310 sslerror_type_slots[0].pfunc = PyExc_OSError;
3311 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003312 if (PySSLErrorObject == NULL)
3313 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003314
Antoine Pitrou41032a62011-10-27 23:56:55 +02003315 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3316 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3317 PySSLErrorObject, NULL);
3318 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
3319 "ssl.SSLWantReadError", SSLWantReadError_doc,
3320 PySSLErrorObject, NULL);
3321 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
3322 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
3323 PySSLErrorObject, NULL);
3324 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
3325 "ssl.SSLSyscallError", SSLSyscallError_doc,
3326 PySSLErrorObject, NULL);
3327 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
3328 "ssl.SSLEOFError", SSLEOFError_doc,
3329 PySSLErrorObject, NULL);
3330 if (PySSLZeroReturnErrorObject == NULL
3331 || PySSLWantReadErrorObject == NULL
3332 || PySSLWantWriteErrorObject == NULL
3333 || PySSLSyscallErrorObject == NULL
3334 || PySSLEOFErrorObject == NULL)
3335 return NULL;
3336 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
3337 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
3338 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
3339 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
3340 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
3341 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003342 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003343 if (PyDict_SetItemString(d, "_SSLContext",
3344 (PyObject *)&PySSLContext_Type) != 0)
3345 return NULL;
3346 if (PyDict_SetItemString(d, "_SSLSocket",
3347 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003348 return NULL;
3349 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
3350 PY_SSL_ERROR_ZERO_RETURN);
3351 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
3352 PY_SSL_ERROR_WANT_READ);
3353 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
3354 PY_SSL_ERROR_WANT_WRITE);
3355 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
3356 PY_SSL_ERROR_WANT_X509_LOOKUP);
3357 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
3358 PY_SSL_ERROR_SYSCALL);
3359 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
3360 PY_SSL_ERROR_SSL);
3361 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
3362 PY_SSL_ERROR_WANT_CONNECT);
3363 /* non ssl.h errorcodes */
3364 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
3365 PY_SSL_ERROR_EOF);
3366 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
3367 PY_SSL_ERROR_INVALID_ERROR_CODE);
3368 /* cert requirements */
3369 PyModule_AddIntConstant(m, "CERT_NONE",
3370 PY_SSL_CERT_NONE);
3371 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
3372 PY_SSL_CERT_OPTIONAL);
3373 PyModule_AddIntConstant(m, "CERT_REQUIRED",
3374 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00003375
Christian Heimes46bebee2013-06-09 19:03:31 +02003376#ifdef _MSC_VER
3377 /* Windows dwCertEncodingType */
3378 PyModule_AddIntMacro(m, X509_ASN_ENCODING);
3379 PyModule_AddIntMacro(m, PKCS_7_ASN_ENCODING);
3380#endif
3381
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003382 /* Alert Descriptions from ssl.h */
3383 /* note RESERVED constants no longer intended for use have been removed */
3384 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
3385
3386#define ADD_AD_CONSTANT(s) \
3387 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
3388 SSL_AD_##s)
3389
3390 ADD_AD_CONSTANT(CLOSE_NOTIFY);
3391 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
3392 ADD_AD_CONSTANT(BAD_RECORD_MAC);
3393 ADD_AD_CONSTANT(RECORD_OVERFLOW);
3394 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
3395 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
3396 ADD_AD_CONSTANT(BAD_CERTIFICATE);
3397 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
3398 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
3399 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
3400 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
3401 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
3402 ADD_AD_CONSTANT(UNKNOWN_CA);
3403 ADD_AD_CONSTANT(ACCESS_DENIED);
3404 ADD_AD_CONSTANT(DECODE_ERROR);
3405 ADD_AD_CONSTANT(DECRYPT_ERROR);
3406 ADD_AD_CONSTANT(PROTOCOL_VERSION);
3407 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
3408 ADD_AD_CONSTANT(INTERNAL_ERROR);
3409 ADD_AD_CONSTANT(USER_CANCELLED);
3410 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003411 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003412#ifdef SSL_AD_UNSUPPORTED_EXTENSION
3413 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
3414#endif
3415#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
3416 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
3417#endif
3418#ifdef SSL_AD_UNRECOGNIZED_NAME
3419 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
3420#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003421#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
3422 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
3423#endif
3424#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
3425 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
3426#endif
3427#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
3428 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
3429#endif
3430
3431#undef ADD_AD_CONSTANT
3432
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003433 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02003434#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003435 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
3436 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02003437#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003438 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
3439 PY_SSL_VERSION_SSL3);
3440 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
3441 PY_SSL_VERSION_SSL23);
3442 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
3443 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003444#if HAVE_TLSv1_2
3445 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
3446 PY_SSL_VERSION_TLS1_1);
3447 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
3448 PY_SSL_VERSION_TLS1_2);
3449#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003450
Antoine Pitroub5218772010-05-21 09:56:06 +00003451 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01003452 PyModule_AddIntConstant(m, "OP_ALL",
3453 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00003454 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
3455 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
3456 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003457#if HAVE_TLSv1_2
3458 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
3459 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
3460#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01003461 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
3462 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003463 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003464#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003465 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003466#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01003467#ifdef SSL_OP_NO_COMPRESSION
3468 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
3469 SSL_OP_NO_COMPRESSION);
3470#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00003471
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003472#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00003473 r = Py_True;
3474#else
3475 r = Py_False;
3476#endif
3477 Py_INCREF(r);
3478 PyModule_AddObject(m, "HAS_SNI", r);
3479
Antoine Pitroud6494802011-07-21 01:11:30 +02003480#if HAVE_OPENSSL_FINISHED
3481 r = Py_True;
3482#else
3483 r = Py_False;
3484#endif
3485 Py_INCREF(r);
3486 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
3487
Antoine Pitrou501da612011-12-21 09:27:41 +01003488#ifdef OPENSSL_NO_ECDH
3489 r = Py_False;
3490#else
3491 r = Py_True;
3492#endif
3493 Py_INCREF(r);
3494 PyModule_AddObject(m, "HAS_ECDH", r);
3495
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003496#ifdef OPENSSL_NPN_NEGOTIATED
3497 r = Py_True;
3498#else
3499 r = Py_False;
3500#endif
3501 Py_INCREF(r);
3502 PyModule_AddObject(m, "HAS_NPN", r);
3503
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003504 /* Mappings for error codes */
3505 err_codes_to_names = PyDict_New();
3506 err_names_to_codes = PyDict_New();
3507 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
3508 return NULL;
3509 errcode = error_codes;
3510 while (errcode->mnemonic != NULL) {
3511 PyObject *mnemo, *key;
3512 mnemo = PyUnicode_FromString(errcode->mnemonic);
3513 key = Py_BuildValue("ii", errcode->library, errcode->reason);
3514 if (mnemo == NULL || key == NULL)
3515 return NULL;
3516 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
3517 return NULL;
3518 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
3519 return NULL;
3520 Py_DECREF(key);
3521 Py_DECREF(mnemo);
3522 errcode++;
3523 }
3524 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
3525 return NULL;
3526 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
3527 return NULL;
3528
3529 lib_codes_to_names = PyDict_New();
3530 if (lib_codes_to_names == NULL)
3531 return NULL;
3532 libcode = library_codes;
3533 while (libcode->library != NULL) {
3534 PyObject *mnemo, *key;
3535 key = PyLong_FromLong(libcode->code);
3536 mnemo = PyUnicode_FromString(libcode->library);
3537 if (key == NULL || mnemo == NULL)
3538 return NULL;
3539 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
3540 return NULL;
3541 Py_DECREF(key);
3542 Py_DECREF(mnemo);
3543 libcode++;
3544 }
3545 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
3546 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02003547
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003548 /* OpenSSL version */
3549 /* SSLeay() gives us the version of the library linked against,
3550 which could be different from the headers version.
3551 */
3552 libver = SSLeay();
3553 r = PyLong_FromUnsignedLong(libver);
3554 if (r == NULL)
3555 return NULL;
3556 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
3557 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003558 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003559 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3560 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
3561 return NULL;
3562 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
3563 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
3564 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003565
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003566 libver = OPENSSL_VERSION_NUMBER;
3567 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
3568 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3569 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
3570 return NULL;
3571
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003572 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003573}