blob: 8789d00fe0a8dc2d2f96d27ca34c37813b4f9695 [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
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000045enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000046 /* these mirror ssl.h */
47 PY_SSL_ERROR_NONE,
48 PY_SSL_ERROR_SSL,
49 PY_SSL_ERROR_WANT_READ,
50 PY_SSL_ERROR_WANT_WRITE,
51 PY_SSL_ERROR_WANT_X509_LOOKUP,
52 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
53 PY_SSL_ERROR_ZERO_RETURN,
54 PY_SSL_ERROR_WANT_CONNECT,
55 /* start of non ssl.h errorcodes */
56 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
57 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
58 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000059};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000060
Thomas Woutersed03b412007-08-28 21:37:11 +000061enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000062 PY_SSL_CLIENT,
63 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +000064};
65
66enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000067 PY_SSL_CERT_NONE,
68 PY_SSL_CERT_OPTIONAL,
69 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +000070};
71
72enum py_ssl_version {
Victor Stinner3de49192011-05-09 00:42:58 +020073#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000074 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +020075#endif
76 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000077 PY_SSL_VERSION_SSL23,
78 PY_SSL_VERSION_TLS1
Thomas Woutersed03b412007-08-28 21:37:11 +000079};
80
Antoine Pitrou3b36fb12012-06-22 21:11:52 +020081struct py_ssl_error_code {
82 const char *mnemonic;
83 int library, reason;
84};
85
86struct py_ssl_library_code {
87 const char *library;
88 int code;
89};
90
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000091/* Include symbols from _socket module */
92#include "socketmodule.h"
93
Benjamin Petersonb173f782009-05-05 22:31:58 +000094static PySocketModule_APIObject PySocketModule;
95
Thomas Woutersed03b412007-08-28 21:37:11 +000096#if defined(HAVE_POLL_H)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000097#include <poll.h>
98#elif defined(HAVE_SYS_POLL_H)
99#include <sys/poll.h>
100#endif
101
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000102/* Include OpenSSL header files */
103#include "openssl/rsa.h"
104#include "openssl/crypto.h"
105#include "openssl/x509.h"
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000106#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000107#include "openssl/pem.h"
108#include "openssl/ssl.h"
109#include "openssl/err.h"
110#include "openssl/rand.h"
111
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200112/* Include generated data (error codes) */
113#include "_ssl_data.h"
114
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000115/* SSL error object */
116static PyObject *PySSLErrorObject;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200117static PyObject *PySSLZeroReturnErrorObject;
118static PyObject *PySSLWantReadErrorObject;
119static PyObject *PySSLWantWriteErrorObject;
120static PyObject *PySSLSyscallErrorObject;
121static PyObject *PySSLEOFErrorObject;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000122
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200123/* Error mappings */
124static PyObject *err_codes_to_names;
125static PyObject *err_names_to_codes;
126static PyObject *lib_codes_to_names;
127
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000128#ifdef WITH_THREAD
129
130/* serves as a flag to see whether we've initialized the SSL thread support. */
131/* 0 means no, greater than 0 means yes */
132
133static unsigned int _ssl_locks_count = 0;
134
135#endif /* def WITH_THREAD */
136
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000137/* SSL socket object */
138
139#define X509_NAME_MAXLEN 256
140
141/* RAND_* APIs got added to OpenSSL in 0.9.5 */
142#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
143# define HAVE_OPENSSL_RAND 1
144#else
145# undef HAVE_OPENSSL_RAND
146#endif
147
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000148/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
149 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
150 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
151#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000152# define HAVE_SSL_CTX_CLEAR_OPTIONS
153#else
154# undef HAVE_SSL_CTX_CLEAR_OPTIONS
155#endif
156
Antoine Pitroud6494802011-07-21 01:11:30 +0200157/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
158 * older SSL, but let's be safe */
159#define PySSL_CB_MAXLEN 128
160
161/* SSL_get_finished got added to OpenSSL in 0.9.5 */
162#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
163# define HAVE_OPENSSL_FINISHED 1
164#else
165# define HAVE_OPENSSL_FINISHED 0
166#endif
167
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100168/* ECDH support got added to OpenSSL in 0.9.8 */
169#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
170# define OPENSSL_NO_ECDH
171#endif
172
Antoine Pitrouc135fa42012-02-19 21:22:39 +0100173/* compression support got added to OpenSSL in 0.9.8 */
174#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
175# define OPENSSL_NO_COMP
176#endif
177
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100178
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000179typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000180 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000181 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100182#ifdef OPENSSL_NPN_NEGOTIATED
183 char *npn_protocols;
184 int npn_protocols_len;
185#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000186} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000187
Antoine Pitrou152efa22010-05-16 18:19:27 +0000188typedef struct {
189 PyObject_HEAD
190 PyObject *Socket; /* weakref to socket on which we're layered */
191 SSL *ssl;
192 X509 *peer_cert;
193 int shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200194 enum py_ssl_server_or_client socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000195} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000196
Antoine Pitrou152efa22010-05-16 18:19:27 +0000197static PyTypeObject PySSLContext_Type;
198static PyTypeObject PySSLSocket_Type;
199
200static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
201static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000202static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000203 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000204static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
205static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000206
Antoine Pitrou152efa22010-05-16 18:19:27 +0000207#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
208#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000209
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000210typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000211 SOCKET_IS_NONBLOCKING,
212 SOCKET_IS_BLOCKING,
213 SOCKET_HAS_TIMED_OUT,
214 SOCKET_HAS_BEEN_CLOSED,
215 SOCKET_TOO_LARGE_FOR_SELECT,
216 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000217} timeout_state;
218
Thomas Woutersed03b412007-08-28 21:37:11 +0000219/* Wrap error strings with filename and line # */
220#define STRINGIFY1(x) #x
221#define STRINGIFY2(x) STRINGIFY1(x)
222#define ERRSTR1(x,y,z) (x ":" y ": " z)
223#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
224
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200225
226/*
227 * SSL errors.
228 */
229
230PyDoc_STRVAR(SSLError_doc,
231"An error occurred in the SSL implementation.");
232
233PyDoc_STRVAR(SSLZeroReturnError_doc,
234"SSL/TLS session closed cleanly.");
235
236PyDoc_STRVAR(SSLWantReadError_doc,
237"Non-blocking SSL socket needs to read more data\n"
238"before the requested operation can be completed.");
239
240PyDoc_STRVAR(SSLWantWriteError_doc,
241"Non-blocking SSL socket needs to write more data\n"
242"before the requested operation can be completed.");
243
244PyDoc_STRVAR(SSLSyscallError_doc,
245"System error when attempting SSL operation.");
246
247PyDoc_STRVAR(SSLEOFError_doc,
248"SSL/TLS connection terminated abruptly.");
249
250static PyObject *
251SSLError_str(PyOSErrorObject *self)
252{
253 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
254 Py_INCREF(self->strerror);
255 return self->strerror;
256 }
257 else
258 return PyObject_Str(self->args);
259}
260
261static PyType_Slot sslerror_type_slots[] = {
262 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
263 {Py_tp_doc, SSLError_doc},
264 {Py_tp_str, SSLError_str},
265 {0, 0},
266};
267
268static PyType_Spec sslerror_type_spec = {
269 "ssl.SSLError",
270 sizeof(PyOSErrorObject),
271 0,
272 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
273 sslerror_type_slots
274};
275
276static void
277fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
278 int lineno, unsigned long errcode)
279{
280 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
281 PyObject *init_value, *msg, *key;
282 _Py_IDENTIFIER(reason);
283 _Py_IDENTIFIER(library);
284
285 if (errcode != 0) {
286 int lib, reason;
287
288 lib = ERR_GET_LIB(errcode);
289 reason = ERR_GET_REASON(errcode);
290 key = Py_BuildValue("ii", lib, reason);
291 if (key == NULL)
292 goto fail;
293 reason_obj = PyDict_GetItem(err_codes_to_names, key);
294 Py_DECREF(key);
295 if (reason_obj == NULL) {
296 /* XXX if reason < 100, it might reflect a library number (!!) */
297 PyErr_Clear();
298 }
299 key = PyLong_FromLong(lib);
300 if (key == NULL)
301 goto fail;
302 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
303 Py_DECREF(key);
304 if (lib_obj == NULL) {
305 PyErr_Clear();
306 }
307 if (errstr == NULL)
308 errstr = ERR_reason_error_string(errcode);
309 }
310 if (errstr == NULL)
311 errstr = "unknown error";
312
313 if (reason_obj && lib_obj)
314 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
315 lib_obj, reason_obj, errstr, lineno);
316 else if (lib_obj)
317 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
318 lib_obj, errstr, lineno);
319 else
320 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
321
322 if (msg == NULL)
323 goto fail;
324 init_value = Py_BuildValue("iN", ssl_errno, msg);
325 err_value = PyObject_CallObject(type, init_value);
326 Py_DECREF(init_value);
327 if (err_value == NULL)
328 goto fail;
329 if (reason_obj == NULL)
330 reason_obj = Py_None;
331 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
332 goto fail;
333 if (lib_obj == NULL)
334 lib_obj = Py_None;
335 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
336 goto fail;
337 PyErr_SetObject(type, err_value);
338fail:
339 Py_XDECREF(err_value);
340}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000341
342static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000343PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000344{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200345 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200346 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000347 int err;
348 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200349 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000350
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000351 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200352 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000353
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000354 if (obj->ssl != NULL) {
355 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000356
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000357 switch (err) {
358 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200359 errstr = "TLS/SSL connection has been closed (EOF)";
360 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000361 p = PY_SSL_ERROR_ZERO_RETURN;
362 break;
363 case SSL_ERROR_WANT_READ:
364 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200365 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000366 p = PY_SSL_ERROR_WANT_READ;
367 break;
368 case SSL_ERROR_WANT_WRITE:
369 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200370 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000371 errstr = "The operation did not complete (write)";
372 break;
373 case SSL_ERROR_WANT_X509_LOOKUP:
374 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000375 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000376 break;
377 case SSL_ERROR_WANT_CONNECT:
378 p = PY_SSL_ERROR_WANT_CONNECT;
379 errstr = "The operation did not complete (connect)";
380 break;
381 case SSL_ERROR_SYSCALL:
382 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000383 if (e == 0) {
384 PySocketSockObject *s
385 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
386 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000387 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200388 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000389 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000390 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000391 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000392 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000393 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200394 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000395 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200396 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000397 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000398 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200399 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000400 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000401 }
402 } else {
403 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000404 }
405 break;
406 }
407 case SSL_ERROR_SSL:
408 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000409 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200410 if (e == 0)
411 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000412 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000413 break;
414 }
415 default:
416 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
417 errstr = "Invalid error code";
418 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000419 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200420 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000421 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000422 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000423}
424
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000425static PyObject *
426_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
427
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200428 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000429 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200430 else
431 errcode = 0;
432 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000433 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000434 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000435}
436
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200437/*
438 * SSL objects
439 */
440
Antoine Pitrou152efa22010-05-16 18:19:27 +0000441static PySSLSocket *
442newPySSLSocket(SSL_CTX *ctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000443 enum py_ssl_server_or_client socket_type,
444 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000445{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000446 PySSLSocket *self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000447
Antoine Pitrou152efa22010-05-16 18:19:27 +0000448 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000449 if (self == NULL)
450 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000451
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000452 self->peer_cert = NULL;
453 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000454 self->Socket = NULL;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200455 self->shutdown_seen_zero = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000456
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000457 /* Make sure the SSL error state is initialized */
458 (void) ERR_get_state();
459 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000460
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000461 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000462 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000463 PySSL_END_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000464 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000465#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000466 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000467#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000468
Antoine Pitroud5323212010-10-22 18:19:07 +0000469#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
470 if (server_hostname != NULL)
471 SSL_set_tlsext_host_name(self->ssl, server_hostname);
472#endif
473
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000474 /* If the socket is in non-blocking mode or timeout mode, set the BIO
475 * to non-blocking mode (blocking is the default)
476 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000477 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000478 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
479 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
480 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000481
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000482 PySSL_BEGIN_ALLOW_THREADS
483 if (socket_type == PY_SSL_CLIENT)
484 SSL_set_connect_state(self->ssl);
485 else
486 SSL_set_accept_state(self->ssl);
487 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000488
Antoine Pitroud6494802011-07-21 01:11:30 +0200489 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000490 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000491 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000492}
493
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000494/* SSL object methods */
495
Antoine Pitrou152efa22010-05-16 18:19:27 +0000496static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000497{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000498 int ret;
499 int err;
500 int sockstate, nonblocking;
501 PySocketSockObject *sock
502 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000503
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000504 if (((PyObject*)sock) == Py_None) {
505 _setSSLError("Underlying socket connection gone",
506 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
507 return NULL;
508 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000509 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000510
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000511 /* just in case the blocking state of the socket has been changed */
512 nonblocking = (sock->sock_timeout >= 0.0);
513 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
514 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000515
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000516 /* Actually negotiate SSL connection */
517 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000518 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000519 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000520 ret = SSL_do_handshake(self->ssl);
521 err = SSL_get_error(self->ssl, ret);
522 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000523 if (PyErr_CheckSignals())
524 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000525 if (err == SSL_ERROR_WANT_READ) {
526 sockstate = check_socket_and_wait_for_timeout(sock, 0);
527 } else if (err == SSL_ERROR_WANT_WRITE) {
528 sockstate = check_socket_and_wait_for_timeout(sock, 1);
529 } else {
530 sockstate = SOCKET_OPERATION_OK;
531 }
532 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000533 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000534 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000535 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000536 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
537 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000538 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000539 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000540 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
541 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000542 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000543 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000544 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
545 break;
546 }
547 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000548 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000549 if (ret < 1)
550 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000551
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000552 if (self->peer_cert)
553 X509_free (self->peer_cert);
554 PySSL_BEGIN_ALLOW_THREADS
555 self->peer_cert = SSL_get_peer_certificate(self->ssl);
556 PySSL_END_ALLOW_THREADS
557
558 Py_INCREF(Py_None);
559 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000560
561error:
562 Py_DECREF(sock);
563 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000564}
565
Thomas Woutersed03b412007-08-28 21:37:11 +0000566static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000567_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000568
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000569 char namebuf[X509_NAME_MAXLEN];
570 int buflen;
571 PyObject *name_obj;
572 PyObject *value_obj;
573 PyObject *attr;
574 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000575
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000576 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
577 if (buflen < 0) {
578 _setSSLError(NULL, 0, __FILE__, __LINE__);
579 goto fail;
580 }
581 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
582 if (name_obj == NULL)
583 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000584
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000585 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
586 if (buflen < 0) {
587 _setSSLError(NULL, 0, __FILE__, __LINE__);
588 Py_DECREF(name_obj);
589 goto fail;
590 }
591 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000592 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000593 OPENSSL_free(valuebuf);
594 if (value_obj == NULL) {
595 Py_DECREF(name_obj);
596 goto fail;
597 }
598 attr = PyTuple_New(2);
599 if (attr == NULL) {
600 Py_DECREF(name_obj);
601 Py_DECREF(value_obj);
602 goto fail;
603 }
604 PyTuple_SET_ITEM(attr, 0, name_obj);
605 PyTuple_SET_ITEM(attr, 1, value_obj);
606 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000607
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000608 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000609 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000610}
611
612static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000613_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000614{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000615 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
616 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
617 PyObject *rdnt;
618 PyObject *attr = NULL; /* tuple to hold an attribute */
619 int entry_count = X509_NAME_entry_count(xname);
620 X509_NAME_ENTRY *entry;
621 ASN1_OBJECT *name;
622 ASN1_STRING *value;
623 int index_counter;
624 int rdn_level = -1;
625 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000626
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000627 dn = PyList_New(0);
628 if (dn == NULL)
629 return NULL;
630 /* now create another tuple to hold the top-level RDN */
631 rdn = PyList_New(0);
632 if (rdn == NULL)
633 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000634
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000635 for (index_counter = 0;
636 index_counter < entry_count;
637 index_counter++)
638 {
639 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000640
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000641 /* check to see if we've gotten to a new RDN */
642 if (rdn_level >= 0) {
643 if (rdn_level != entry->set) {
644 /* yes, new RDN */
645 /* add old RDN to DN */
646 rdnt = PyList_AsTuple(rdn);
647 Py_DECREF(rdn);
648 if (rdnt == NULL)
649 goto fail0;
650 retcode = PyList_Append(dn, rdnt);
651 Py_DECREF(rdnt);
652 if (retcode < 0)
653 goto fail0;
654 /* create new RDN */
655 rdn = PyList_New(0);
656 if (rdn == NULL)
657 goto fail0;
658 }
659 }
660 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000661
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000662 /* now add this attribute to the current RDN */
663 name = X509_NAME_ENTRY_get_object(entry);
664 value = X509_NAME_ENTRY_get_data(entry);
665 attr = _create_tuple_for_attribute(name, value);
666 /*
667 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
668 entry->set,
669 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
670 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
671 */
672 if (attr == NULL)
673 goto fail1;
674 retcode = PyList_Append(rdn, attr);
675 Py_DECREF(attr);
676 if (retcode < 0)
677 goto fail1;
678 }
679 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100680 if (rdn != NULL) {
681 if (PyList_GET_SIZE(rdn) > 0) {
682 rdnt = PyList_AsTuple(rdn);
683 Py_DECREF(rdn);
684 if (rdnt == NULL)
685 goto fail0;
686 retcode = PyList_Append(dn, rdnt);
687 Py_DECREF(rdnt);
688 if (retcode < 0)
689 goto fail0;
690 }
691 else {
692 Py_DECREF(rdn);
693 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000694 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000695
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000696 /* convert list to tuple */
697 rdnt = PyList_AsTuple(dn);
698 Py_DECREF(dn);
699 if (rdnt == NULL)
700 return NULL;
701 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000702
703 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000704 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000705
706 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000707 Py_XDECREF(dn);
708 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000709}
710
711static PyObject *
712_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000713
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000714 /* this code follows the procedure outlined in
715 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
716 function to extract the STACK_OF(GENERAL_NAME),
717 then iterates through the stack to add the
718 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000719
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000720 int i, j;
721 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200722 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000723 X509_EXTENSION *ext = NULL;
724 GENERAL_NAMES *names = NULL;
725 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000726 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000727 BIO *biobuf = NULL;
728 char buf[2048];
729 char *vptr;
730 int len;
731 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000732#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000733 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000734#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000735 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000736#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000737
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000738 if (certificate == NULL)
739 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000740
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000741 /* get a memory buffer */
742 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000743
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200744 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000745 while ((i = X509_get_ext_by_NID(
746 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000747
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000748 if (peer_alt_names == Py_None) {
749 peer_alt_names = PyList_New(0);
750 if (peer_alt_names == NULL)
751 goto fail;
752 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000753
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000754 /* now decode the altName */
755 ext = X509_get_ext(certificate, i);
756 if(!(method = X509V3_EXT_get(ext))) {
757 PyErr_SetString
758 (PySSLErrorObject,
759 ERRSTR("No method for internalizing subjectAltName!"));
760 goto fail;
761 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000762
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000763 p = ext->value->data;
764 if (method->it)
765 names = (GENERAL_NAMES*)
766 (ASN1_item_d2i(NULL,
767 &p,
768 ext->value->length,
769 ASN1_ITEM_ptr(method->it)));
770 else
771 names = (GENERAL_NAMES*)
772 (method->d2i(NULL,
773 &p,
774 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000775
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000776 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000777 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200778 int gntype;
779 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000780
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000781 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200782 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200783 switch (gntype) {
784 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000785 /* we special-case DirName as a tuple of
786 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000787
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000788 t = PyTuple_New(2);
789 if (t == NULL) {
790 goto fail;
791 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000792
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000793 v = PyUnicode_FromString("DirName");
794 if (v == NULL) {
795 Py_DECREF(t);
796 goto fail;
797 }
798 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000799
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000800 v = _create_tuple_for_X509_NAME (name->d.dirn);
801 if (v == NULL) {
802 Py_DECREF(t);
803 goto fail;
804 }
805 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200806 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000807
Christian Heimes824f7f32013-08-17 00:54:47 +0200808 case GEN_EMAIL:
809 case GEN_DNS:
810 case GEN_URI:
811 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
812 correctly, CVE-2013-4238 */
813 t = PyTuple_New(2);
814 if (t == NULL)
815 goto fail;
816 switch (gntype) {
817 case GEN_EMAIL:
818 v = PyUnicode_FromString("email");
819 as = name->d.rfc822Name;
820 break;
821 case GEN_DNS:
822 v = PyUnicode_FromString("DNS");
823 as = name->d.dNSName;
824 break;
825 case GEN_URI:
826 v = PyUnicode_FromString("URI");
827 as = name->d.uniformResourceIdentifier;
828 break;
829 }
830 if (v == NULL) {
831 Py_DECREF(t);
832 goto fail;
833 }
834 PyTuple_SET_ITEM(t, 0, v);
835 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
836 ASN1_STRING_length(as));
837 if (v == NULL) {
838 Py_DECREF(t);
839 goto fail;
840 }
841 PyTuple_SET_ITEM(t, 1, v);
842 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000843
Christian Heimes824f7f32013-08-17 00:54:47 +0200844 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000845 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200846 switch (gntype) {
847 /* check for new general name type */
848 case GEN_OTHERNAME:
849 case GEN_X400:
850 case GEN_EDIPARTY:
851 case GEN_IPADD:
852 case GEN_RID:
853 break;
854 default:
855 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
856 "Unknown general name type %d",
857 gntype) == -1) {
858 goto fail;
859 }
860 break;
861 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000862 (void) BIO_reset(biobuf);
863 GENERAL_NAME_print(biobuf, name);
864 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
865 if (len < 0) {
866 _setSSLError(NULL, 0, __FILE__, __LINE__);
867 goto fail;
868 }
869 vptr = strchr(buf, ':');
870 if (vptr == NULL)
871 goto fail;
872 t = PyTuple_New(2);
873 if (t == NULL)
874 goto fail;
875 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
876 if (v == NULL) {
877 Py_DECREF(t);
878 goto fail;
879 }
880 PyTuple_SET_ITEM(t, 0, v);
881 v = PyUnicode_FromStringAndSize((vptr + 1),
882 (len - (vptr - buf + 1)));
883 if (v == NULL) {
884 Py_DECREF(t);
885 goto fail;
886 }
887 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200888 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000889 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000890
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000891 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000892
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000893 if (PyList_Append(peer_alt_names, t) < 0) {
894 Py_DECREF(t);
895 goto fail;
896 }
897 Py_DECREF(t);
898 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100899 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000900 }
901 BIO_free(biobuf);
902 if (peer_alt_names != Py_None) {
903 v = PyList_AsTuple(peer_alt_names);
904 Py_DECREF(peer_alt_names);
905 return v;
906 } else {
907 return peer_alt_names;
908 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000909
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000910
911 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000912 if (biobuf != NULL)
913 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000914
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000915 if (peer_alt_names != Py_None) {
916 Py_XDECREF(peer_alt_names);
917 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000918
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000919 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000920}
921
922static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000923_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000924
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000925 PyObject *retval = NULL;
926 BIO *biobuf = NULL;
927 PyObject *peer;
928 PyObject *peer_alt_names = NULL;
929 PyObject *issuer;
930 PyObject *version;
931 PyObject *sn_obj;
932 ASN1_INTEGER *serialNumber;
933 char buf[2048];
934 int len;
935 ASN1_TIME *notBefore, *notAfter;
936 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000937
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 retval = PyDict_New();
939 if (retval == NULL)
940 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000941
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 peer = _create_tuple_for_X509_NAME(
943 X509_get_subject_name(certificate));
944 if (peer == NULL)
945 goto fail0;
946 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
947 Py_DECREF(peer);
948 goto fail0;
949 }
950 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000951
Antoine Pitroufb046912010-11-09 20:21:19 +0000952 issuer = _create_tuple_for_X509_NAME(
953 X509_get_issuer_name(certificate));
954 if (issuer == NULL)
955 goto fail0;
956 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000957 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000958 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000959 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000960 Py_DECREF(issuer);
961
962 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +0200963 if (version == NULL)
964 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +0000965 if (PyDict_SetItemString(retval, "version", version) < 0) {
966 Py_DECREF(version);
967 goto fail0;
968 }
969 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000970
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000971 /* get a memory buffer */
972 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000973
Antoine Pitroufb046912010-11-09 20:21:19 +0000974 (void) BIO_reset(biobuf);
975 serialNumber = X509_get_serialNumber(certificate);
976 /* should not exceed 20 octets, 160 bits, so buf is big enough */
977 i2a_ASN1_INTEGER(biobuf, serialNumber);
978 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
979 if (len < 0) {
980 _setSSLError(NULL, 0, __FILE__, __LINE__);
981 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000982 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000983 sn_obj = PyUnicode_FromStringAndSize(buf, len);
984 if (sn_obj == NULL)
985 goto fail1;
986 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
987 Py_DECREF(sn_obj);
988 goto fail1;
989 }
990 Py_DECREF(sn_obj);
991
992 (void) BIO_reset(biobuf);
993 notBefore = X509_get_notBefore(certificate);
994 ASN1_TIME_print(biobuf, notBefore);
995 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
996 if (len < 0) {
997 _setSSLError(NULL, 0, __FILE__, __LINE__);
998 goto fail1;
999 }
1000 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1001 if (pnotBefore == NULL)
1002 goto fail1;
1003 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1004 Py_DECREF(pnotBefore);
1005 goto fail1;
1006 }
1007 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001008
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001009 (void) BIO_reset(biobuf);
1010 notAfter = X509_get_notAfter(certificate);
1011 ASN1_TIME_print(biobuf, notAfter);
1012 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1013 if (len < 0) {
1014 _setSSLError(NULL, 0, __FILE__, __LINE__);
1015 goto fail1;
1016 }
1017 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1018 if (pnotAfter == NULL)
1019 goto fail1;
1020 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1021 Py_DECREF(pnotAfter);
1022 goto fail1;
1023 }
1024 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001025
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001026 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001027
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001028 peer_alt_names = _get_peer_alt_names(certificate);
1029 if (peer_alt_names == NULL)
1030 goto fail1;
1031 else if (peer_alt_names != Py_None) {
1032 if (PyDict_SetItemString(retval, "subjectAltName",
1033 peer_alt_names) < 0) {
1034 Py_DECREF(peer_alt_names);
1035 goto fail1;
1036 }
1037 Py_DECREF(peer_alt_names);
1038 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001039
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001040 BIO_free(biobuf);
1041 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001042
1043 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001044 if (biobuf != NULL)
1045 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001046 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001047 Py_XDECREF(retval);
1048 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001049}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001050
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001051
1052static PyObject *
1053PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1054
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001055 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001056 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 X509 *x=NULL;
1058 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001059
Antoine Pitroufb046912010-11-09 20:21:19 +00001060 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1061 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001062 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001063
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001064 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1065 PyErr_SetString(PySSLErrorObject,
1066 "Can't malloc memory to read file");
1067 goto fail0;
1068 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001069
Victor Stinner3800e1e2010-05-16 21:23:48 +00001070 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001071 PyErr_SetString(PySSLErrorObject,
1072 "Can't open file");
1073 goto fail0;
1074 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001075
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001076 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1077 if (x == NULL) {
1078 PyErr_SetString(PySSLErrorObject,
1079 "Error decoding PEM-encoded file");
1080 goto fail0;
1081 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001082
Antoine Pitroufb046912010-11-09 20:21:19 +00001083 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001084 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001085
1086 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001087 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001088 if (cert != NULL) BIO_free(cert);
1089 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001090}
1091
1092
1093static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001094PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001095{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001096 PyObject *retval = NULL;
1097 int len;
1098 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001099 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001100
Antoine Pitrou721738f2012-08-15 23:20:39 +02001101 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001102 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001103
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001104 if (!self->peer_cert)
1105 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001106
Antoine Pitrou721738f2012-08-15 23:20:39 +02001107 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001108 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001109
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001110 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001111
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001112 bytes_buf = NULL;
1113 len = i2d_X509(self->peer_cert, &bytes_buf);
1114 if (len < 0) {
1115 PySSL_SetError(self, len, __FILE__, __LINE__);
1116 return NULL;
1117 }
1118 /* this is actually an immutable bytes sequence */
1119 retval = PyBytes_FromStringAndSize
1120 ((const char *) bytes_buf, len);
1121 OPENSSL_free(bytes_buf);
1122 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001123
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001124 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001125 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001126 if ((verification & SSL_VERIFY_PEER) == 0)
1127 return PyDict_New();
1128 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001129 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001130 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001131}
1132
1133PyDoc_STRVAR(PySSL_peercert_doc,
1134"peer_certificate([der=False]) -> certificate\n\
1135\n\
1136Returns the certificate for the peer. If no certificate was provided,\n\
1137returns None. If a certificate was provided, but not validated, returns\n\
1138an empty dictionary. Otherwise returns a dict containing information\n\
1139about the peer certificate.\n\
1140\n\
1141If the optional argument is True, returns a DER-encoded copy of the\n\
1142peer certificate, or None if no certificate was provided. This will\n\
1143return the certificate even if it wasn't validated.");
1144
Antoine Pitrou152efa22010-05-16 18:19:27 +00001145static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001146
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001147 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001148 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001149 char *cipher_name;
1150 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001151
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001152 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001153 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001154 current = SSL_get_current_cipher(self->ssl);
1155 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001156 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001157
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001158 retval = PyTuple_New(3);
1159 if (retval == NULL)
1160 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001161
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001162 cipher_name = (char *) SSL_CIPHER_get_name(current);
1163 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001164 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001165 PyTuple_SET_ITEM(retval, 0, Py_None);
1166 } else {
1167 v = PyUnicode_FromString(cipher_name);
1168 if (v == NULL)
1169 goto fail0;
1170 PyTuple_SET_ITEM(retval, 0, v);
1171 }
1172 cipher_protocol = SSL_CIPHER_get_version(current);
1173 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001174 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001175 PyTuple_SET_ITEM(retval, 1, Py_None);
1176 } else {
1177 v = PyUnicode_FromString(cipher_protocol);
1178 if (v == NULL)
1179 goto fail0;
1180 PyTuple_SET_ITEM(retval, 1, v);
1181 }
1182 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1183 if (v == NULL)
1184 goto fail0;
1185 PyTuple_SET_ITEM(retval, 2, v);
1186 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001187
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001188 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001189 Py_DECREF(retval);
1190 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001191}
1192
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001193#ifdef OPENSSL_NPN_NEGOTIATED
1194static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1195 const unsigned char *out;
1196 unsigned int outlen;
1197
Victor Stinner4569cd52013-06-23 14:58:43 +02001198 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001199 &out, &outlen);
1200
1201 if (out == NULL)
1202 Py_RETURN_NONE;
1203 return PyUnicode_FromStringAndSize((char *) out, outlen);
1204}
1205#endif
1206
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001207static PyObject *PySSL_compression(PySSLSocket *self) {
1208#ifdef OPENSSL_NO_COMP
1209 Py_RETURN_NONE;
1210#else
1211 const COMP_METHOD *comp_method;
1212 const char *short_name;
1213
1214 if (self->ssl == NULL)
1215 Py_RETURN_NONE;
1216 comp_method = SSL_get_current_compression(self->ssl);
1217 if (comp_method == NULL || comp_method->type == NID_undef)
1218 Py_RETURN_NONE;
1219 short_name = OBJ_nid2sn(comp_method->type);
1220 if (short_name == NULL)
1221 Py_RETURN_NONE;
1222 return PyUnicode_DecodeFSDefault(short_name);
1223#endif
1224}
1225
Antoine Pitrou152efa22010-05-16 18:19:27 +00001226static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001227{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001228 if (self->peer_cert) /* Possible not to have one? */
1229 X509_free (self->peer_cert);
1230 if (self->ssl)
1231 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001232 Py_XDECREF(self->Socket);
1233 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001234}
1235
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001236/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001237 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001238 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001239 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001240
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001241static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001242check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001243{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001244 fd_set fds;
1245 struct timeval tv;
1246 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001247
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001248 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1249 if (s->sock_timeout < 0.0)
1250 return SOCKET_IS_BLOCKING;
1251 else if (s->sock_timeout == 0.0)
1252 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001253
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001254 /* Guard against closed socket */
1255 if (s->sock_fd < 0)
1256 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001257
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001258 /* Prefer poll, if available, since you can poll() any fd
1259 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001260#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001261 {
1262 struct pollfd pollfd;
1263 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001264
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001265 pollfd.fd = s->sock_fd;
1266 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001267
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001268 /* s->sock_timeout is in seconds, timeout in ms */
1269 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1270 PySSL_BEGIN_ALLOW_THREADS
1271 rc = poll(&pollfd, 1, timeout);
1272 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001273
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001274 goto normal_return;
1275 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001276#endif
1277
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001278 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001279 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001280 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001281
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001282 /* Construct the arguments to select */
1283 tv.tv_sec = (int)s->sock_timeout;
1284 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1285 FD_ZERO(&fds);
1286 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001287
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001288 /* See if the socket is ready */
1289 PySSL_BEGIN_ALLOW_THREADS
1290 if (writing)
1291 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1292 else
1293 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1294 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001295
Bill Janssen6e027db2007-11-15 22:23:56 +00001296#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001297normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001298#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001299 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1300 (when we are able to write or when there's something to read) */
1301 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001302}
1303
Antoine Pitrou152efa22010-05-16 18:19:27 +00001304static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001305{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001306 Py_buffer buf;
1307 int len;
1308 int sockstate;
1309 int err;
1310 int nonblocking;
1311 PySocketSockObject *sock
1312 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001313
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001314 if (((PyObject*)sock) == Py_None) {
1315 _setSSLError("Underlying socket connection gone",
1316 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1317 return NULL;
1318 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001319 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001320
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001321 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1322 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001323 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001324 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001325
Victor Stinner6efa9652013-06-25 00:42:31 +02001326 if (buf.len > INT_MAX) {
1327 PyErr_Format(PyExc_OverflowError,
1328 "string longer than %d bytes", INT_MAX);
1329 goto error;
1330 }
1331
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001332 /* just in case the blocking state of the socket has been changed */
1333 nonblocking = (sock->sock_timeout >= 0.0);
1334 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1335 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1336
1337 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1338 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001339 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340 "The write operation timed out");
1341 goto error;
1342 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1343 PyErr_SetString(PySSLErrorObject,
1344 "Underlying socket has been closed.");
1345 goto error;
1346 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1347 PyErr_SetString(PySSLErrorObject,
1348 "Underlying socket too large for select().");
1349 goto error;
1350 }
1351 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001352 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001353 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001354 err = SSL_get_error(self->ssl, len);
1355 PySSL_END_ALLOW_THREADS
1356 if (PyErr_CheckSignals()) {
1357 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001358 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001359 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001360 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001361 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001362 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001363 } else {
1364 sockstate = SOCKET_OPERATION_OK;
1365 }
1366 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001367 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001368 "The write operation timed out");
1369 goto error;
1370 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1371 PyErr_SetString(PySSLErrorObject,
1372 "Underlying socket has been closed.");
1373 goto error;
1374 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1375 break;
1376 }
1377 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001378
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001379 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001380 PyBuffer_Release(&buf);
1381 if (len > 0)
1382 return PyLong_FromLong(len);
1383 else
1384 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001385
1386error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001387 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001388 PyBuffer_Release(&buf);
1389 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001390}
1391
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001392PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001393"write(s) -> len\n\
1394\n\
1395Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001396of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001397
Antoine Pitrou152efa22010-05-16 18:19:27 +00001398static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001399{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001400 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001401
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001402 PySSL_BEGIN_ALLOW_THREADS
1403 count = SSL_pending(self->ssl);
1404 PySSL_END_ALLOW_THREADS
1405 if (count < 0)
1406 return PySSL_SetError(self, count, __FILE__, __LINE__);
1407 else
1408 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001409}
1410
1411PyDoc_STRVAR(PySSL_SSLpending_doc,
1412"pending() -> count\n\
1413\n\
1414Returns the number of already decrypted bytes available for read,\n\
1415pending on the connection.\n");
1416
Antoine Pitrou152efa22010-05-16 18:19:27 +00001417static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001418{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001419 PyObject *dest = NULL;
1420 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001421 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001422 int len, count;
1423 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001424 int sockstate;
1425 int err;
1426 int nonblocking;
1427 PySocketSockObject *sock
1428 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001429
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001430 if (((PyObject*)sock) == Py_None) {
1431 _setSSLError("Underlying socket connection gone",
1432 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1433 return NULL;
1434 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001435 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001436
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001437 buf.obj = NULL;
1438 buf.buf = NULL;
1439 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001440 goto error;
1441
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001442 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1443 dest = PyBytes_FromStringAndSize(NULL, len);
1444 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001445 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001446 mem = PyBytes_AS_STRING(dest);
1447 }
1448 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001449 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001450 mem = buf.buf;
1451 if (len <= 0 || len > buf.len) {
1452 len = (int) buf.len;
1453 if (buf.len != len) {
1454 PyErr_SetString(PyExc_OverflowError,
1455 "maximum length can't fit in a C 'int'");
1456 goto error;
1457 }
1458 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001459 }
1460
1461 /* just in case the blocking state of the socket has been changed */
1462 nonblocking = (sock->sock_timeout >= 0.0);
1463 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1464 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1465
1466 /* first check if there are bytes ready to be read */
1467 PySSL_BEGIN_ALLOW_THREADS
1468 count = SSL_pending(self->ssl);
1469 PySSL_END_ALLOW_THREADS
1470
1471 if (!count) {
1472 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1473 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001474 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001475 "The read operation timed out");
1476 goto error;
1477 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1478 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001479 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001480 goto error;
1481 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1482 count = 0;
1483 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001484 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001485 }
1486 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001487 PySSL_BEGIN_ALLOW_THREADS
1488 count = SSL_read(self->ssl, mem, len);
1489 err = SSL_get_error(self->ssl, count);
1490 PySSL_END_ALLOW_THREADS
1491 if (PyErr_CheckSignals())
1492 goto error;
1493 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001494 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001495 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001496 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001497 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1498 (SSL_get_shutdown(self->ssl) ==
1499 SSL_RECEIVED_SHUTDOWN))
1500 {
1501 count = 0;
1502 goto done;
1503 } else {
1504 sockstate = SOCKET_OPERATION_OK;
1505 }
1506 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001507 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001508 "The read operation timed out");
1509 goto error;
1510 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1511 break;
1512 }
1513 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1514 if (count <= 0) {
1515 PySSL_SetError(self, count, __FILE__, __LINE__);
1516 goto error;
1517 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001518
1519done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001520 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001521 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001522 _PyBytes_Resize(&dest, count);
1523 return dest;
1524 }
1525 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001526 PyBuffer_Release(&buf);
1527 return PyLong_FromLong(count);
1528 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001529
1530error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001531 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001532 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001533 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001534 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001535 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001536 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001537}
1538
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001539PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001540"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001541\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001542Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001543
Antoine Pitrou152efa22010-05-16 18:19:27 +00001544static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001545{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001546 int err, ssl_err, sockstate, nonblocking;
1547 int zeros = 0;
1548 PySocketSockObject *sock
1549 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001550
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001551 /* Guard against closed socket */
1552 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1553 _setSSLError("Underlying socket connection gone",
1554 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1555 return NULL;
1556 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001557 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001558
1559 /* Just in case the blocking state of the socket has been changed */
1560 nonblocking = (sock->sock_timeout >= 0.0);
1561 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1562 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1563
1564 while (1) {
1565 PySSL_BEGIN_ALLOW_THREADS
1566 /* Disable read-ahead so that unwrap can work correctly.
1567 * Otherwise OpenSSL might read in too much data,
1568 * eating clear text data that happens to be
1569 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001570 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001571 * function is used and the shutdown_seen_zero != 0
1572 * condition is met.
1573 */
1574 if (self->shutdown_seen_zero)
1575 SSL_set_read_ahead(self->ssl, 0);
1576 err = SSL_shutdown(self->ssl);
1577 PySSL_END_ALLOW_THREADS
1578 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1579 if (err > 0)
1580 break;
1581 if (err == 0) {
1582 /* Don't loop endlessly; instead preserve legacy
1583 behaviour of trying SSL_shutdown() only twice.
1584 This looks necessary for OpenSSL < 0.9.8m */
1585 if (++zeros > 1)
1586 break;
1587 /* Shutdown was sent, now try receiving */
1588 self->shutdown_seen_zero = 1;
1589 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001590 }
1591
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001592 /* Possibly retry shutdown until timeout or failure */
1593 ssl_err = SSL_get_error(self->ssl, err);
1594 if (ssl_err == SSL_ERROR_WANT_READ)
1595 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1596 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1597 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1598 else
1599 break;
1600 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1601 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001602 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001603 "The read operation timed out");
1604 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001605 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001606 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001607 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001608 }
1609 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1610 PyErr_SetString(PySSLErrorObject,
1611 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001612 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001613 }
1614 else if (sockstate != SOCKET_OPERATION_OK)
1615 /* Retain the SSL error code */
1616 break;
1617 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001618
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001619 if (err < 0) {
1620 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001621 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001622 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001623 else
1624 /* It's already INCREF'ed */
1625 return (PyObject *) sock;
1626
1627error:
1628 Py_DECREF(sock);
1629 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001630}
1631
1632PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1633"shutdown(s) -> socket\n\
1634\n\
1635Does the SSL shutdown handshake with the remote end, and returns\n\
1636the underlying socket object.");
1637
Antoine Pitroud6494802011-07-21 01:11:30 +02001638#if HAVE_OPENSSL_FINISHED
1639static PyObject *
1640PySSL_tls_unique_cb(PySSLSocket *self)
1641{
1642 PyObject *retval = NULL;
1643 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001644 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001645
1646 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1647 /* if session is resumed XOR we are the client */
1648 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1649 }
1650 else {
1651 /* if a new session XOR we are the server */
1652 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1653 }
1654
1655 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001656 if (len == 0)
1657 Py_RETURN_NONE;
1658
1659 retval = PyBytes_FromStringAndSize(buf, len);
1660
1661 return retval;
1662}
1663
1664PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1665"tls_unique_cb() -> bytes\n\
1666\n\
1667Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1668\n\
1669If the TLS handshake is not yet complete, None is returned");
1670
1671#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001672
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001673static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001674 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1675 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1676 PySSL_SSLwrite_doc},
1677 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1678 PySSL_SSLread_doc},
1679 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1680 PySSL_SSLpending_doc},
1681 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1682 PySSL_peercert_doc},
1683 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001684#ifdef OPENSSL_NPN_NEGOTIATED
1685 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1686#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001687 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001688 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1689 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001690#if HAVE_OPENSSL_FINISHED
1691 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1692 PySSL_tls_unique_cb_doc},
1693#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001694 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001695};
1696
Antoine Pitrou152efa22010-05-16 18:19:27 +00001697static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001698 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001699 "_ssl._SSLSocket", /*tp_name*/
1700 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001701 0, /*tp_itemsize*/
1702 /* methods */
1703 (destructor)PySSL_dealloc, /*tp_dealloc*/
1704 0, /*tp_print*/
1705 0, /*tp_getattr*/
1706 0, /*tp_setattr*/
1707 0, /*tp_reserved*/
1708 0, /*tp_repr*/
1709 0, /*tp_as_number*/
1710 0, /*tp_as_sequence*/
1711 0, /*tp_as_mapping*/
1712 0, /*tp_hash*/
1713 0, /*tp_call*/
1714 0, /*tp_str*/
1715 0, /*tp_getattro*/
1716 0, /*tp_setattro*/
1717 0, /*tp_as_buffer*/
1718 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1719 0, /*tp_doc*/
1720 0, /*tp_traverse*/
1721 0, /*tp_clear*/
1722 0, /*tp_richcompare*/
1723 0, /*tp_weaklistoffset*/
1724 0, /*tp_iter*/
1725 0, /*tp_iternext*/
1726 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001727};
1728
Antoine Pitrou152efa22010-05-16 18:19:27 +00001729
1730/*
1731 * _SSLContext objects
1732 */
1733
1734static PyObject *
1735context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1736{
1737 char *kwlist[] = {"protocol", NULL};
1738 PySSLContext *self;
1739 int proto_version = PY_SSL_VERSION_SSL23;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01001740 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001741 SSL_CTX *ctx = NULL;
1742
1743 if (!PyArg_ParseTupleAndKeywords(
1744 args, kwds, "i:_SSLContext", kwlist,
1745 &proto_version))
1746 return NULL;
1747
1748 PySSL_BEGIN_ALLOW_THREADS
1749 if (proto_version == PY_SSL_VERSION_TLS1)
1750 ctx = SSL_CTX_new(TLSv1_method());
1751 else if (proto_version == PY_SSL_VERSION_SSL3)
1752 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001753#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001754 else if (proto_version == PY_SSL_VERSION_SSL2)
1755 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001756#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001757 else if (proto_version == PY_SSL_VERSION_SSL23)
1758 ctx = SSL_CTX_new(SSLv23_method());
1759 else
1760 proto_version = -1;
1761 PySSL_END_ALLOW_THREADS
1762
1763 if (proto_version == -1) {
1764 PyErr_SetString(PyExc_ValueError,
1765 "invalid protocol version");
1766 return NULL;
1767 }
1768 if (ctx == NULL) {
1769 PyErr_SetString(PySSLErrorObject,
1770 "failed to allocate SSL context");
1771 return NULL;
1772 }
1773
1774 assert(type != NULL && type->tp_alloc != NULL);
1775 self = (PySSLContext *) type->tp_alloc(type, 0);
1776 if (self == NULL) {
1777 SSL_CTX_free(ctx);
1778 return NULL;
1779 }
1780 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02001781#ifdef OPENSSL_NPN_NEGOTIATED
1782 self->npn_protocols = NULL;
1783#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001784 /* Defaults */
1785 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01001786 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
1787 if (proto_version != PY_SSL_VERSION_SSL2)
1788 options |= SSL_OP_NO_SSLv2;
1789 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001790
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001791#define SID_CTX "Python"
1792 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1793 sizeof(SID_CTX));
1794#undef SID_CTX
1795
Antoine Pitrou152efa22010-05-16 18:19:27 +00001796 return (PyObject *)self;
1797}
1798
1799static void
1800context_dealloc(PySSLContext *self)
1801{
1802 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001803#ifdef OPENSSL_NPN_NEGOTIATED
1804 PyMem_Free(self->npn_protocols);
1805#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001806 Py_TYPE(self)->tp_free(self);
1807}
1808
1809static PyObject *
1810set_ciphers(PySSLContext *self, PyObject *args)
1811{
1812 int ret;
1813 const char *cipherlist;
1814
1815 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1816 return NULL;
1817 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1818 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001819 /* Clearing the error queue is necessary on some OpenSSL versions,
1820 otherwise the error will be reported again when another SSL call
1821 is done. */
1822 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001823 PyErr_SetString(PySSLErrorObject,
1824 "No cipher can be selected.");
1825 return NULL;
1826 }
1827 Py_RETURN_NONE;
1828}
1829
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001830#ifdef OPENSSL_NPN_NEGOTIATED
1831/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
1832static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001833_advertiseNPN_cb(SSL *s,
1834 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001835 void *args)
1836{
1837 PySSLContext *ssl_ctx = (PySSLContext *) args;
1838
1839 if (ssl_ctx->npn_protocols == NULL) {
1840 *data = (unsigned char *) "";
1841 *len = 0;
1842 } else {
1843 *data = (unsigned char *) ssl_ctx->npn_protocols;
1844 *len = ssl_ctx->npn_protocols_len;
1845 }
1846
1847 return SSL_TLSEXT_ERR_OK;
1848}
1849/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
1850static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001851_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001852 unsigned char **out, unsigned char *outlen,
1853 const unsigned char *server, unsigned int server_len,
1854 void *args)
1855{
1856 PySSLContext *ssl_ctx = (PySSLContext *) args;
1857
1858 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
1859 int client_len;
1860
1861 if (client == NULL) {
1862 client = (unsigned char *) "";
1863 client_len = 0;
1864 } else {
1865 client_len = ssl_ctx->npn_protocols_len;
1866 }
1867
1868 SSL_select_next_proto(out, outlen,
1869 server, server_len,
1870 client, client_len);
1871
1872 return SSL_TLSEXT_ERR_OK;
1873}
1874#endif
1875
1876static PyObject *
1877_set_npn_protocols(PySSLContext *self, PyObject *args)
1878{
1879#ifdef OPENSSL_NPN_NEGOTIATED
1880 Py_buffer protos;
1881
1882 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
1883 return NULL;
1884
Christian Heimes5cb31c92012-09-20 12:42:54 +02001885 if (self->npn_protocols != NULL) {
1886 PyMem_Free(self->npn_protocols);
1887 }
1888
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001889 self->npn_protocols = PyMem_Malloc(protos.len);
1890 if (self->npn_protocols == NULL) {
1891 PyBuffer_Release(&protos);
1892 return PyErr_NoMemory();
1893 }
1894 memcpy(self->npn_protocols, protos.buf, protos.len);
1895 self->npn_protocols_len = (int) protos.len;
1896
1897 /* set both server and client callbacks, because the context can
1898 * be used to create both types of sockets */
1899 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
1900 _advertiseNPN_cb,
1901 self);
1902 SSL_CTX_set_next_proto_select_cb(self->ctx,
1903 _selectNPN_cb,
1904 self);
1905
1906 PyBuffer_Release(&protos);
1907 Py_RETURN_NONE;
1908#else
1909 PyErr_SetString(PyExc_NotImplementedError,
1910 "The NPN extension requires OpenSSL 1.0.1 or later.");
1911 return NULL;
1912#endif
1913}
1914
Antoine Pitrou152efa22010-05-16 18:19:27 +00001915static PyObject *
1916get_verify_mode(PySSLContext *self, void *c)
1917{
1918 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1919 case SSL_VERIFY_NONE:
1920 return PyLong_FromLong(PY_SSL_CERT_NONE);
1921 case SSL_VERIFY_PEER:
1922 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1923 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1924 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1925 }
1926 PyErr_SetString(PySSLErrorObject,
1927 "invalid return value from SSL_CTX_get_verify_mode");
1928 return NULL;
1929}
1930
1931static int
1932set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1933{
1934 int n, mode;
1935 if (!PyArg_Parse(arg, "i", &n))
1936 return -1;
1937 if (n == PY_SSL_CERT_NONE)
1938 mode = SSL_VERIFY_NONE;
1939 else if (n == PY_SSL_CERT_OPTIONAL)
1940 mode = SSL_VERIFY_PEER;
1941 else if (n == PY_SSL_CERT_REQUIRED)
1942 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1943 else {
1944 PyErr_SetString(PyExc_ValueError,
1945 "invalid value for verify_mode");
1946 return -1;
1947 }
1948 SSL_CTX_set_verify(self->ctx, mode, NULL);
1949 return 0;
1950}
1951
1952static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001953get_options(PySSLContext *self, void *c)
1954{
1955 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1956}
1957
1958static int
1959set_options(PySSLContext *self, PyObject *arg, void *c)
1960{
1961 long new_opts, opts, set, clear;
1962 if (!PyArg_Parse(arg, "l", &new_opts))
1963 return -1;
1964 opts = SSL_CTX_get_options(self->ctx);
1965 clear = opts & ~new_opts;
1966 set = ~opts & new_opts;
1967 if (clear) {
1968#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1969 SSL_CTX_clear_options(self->ctx, clear);
1970#else
1971 PyErr_SetString(PyExc_ValueError,
1972 "can't clear options before OpenSSL 0.9.8m");
1973 return -1;
1974#endif
1975 }
1976 if (set)
1977 SSL_CTX_set_options(self->ctx, set);
1978 return 0;
1979}
1980
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001981typedef struct {
1982 PyThreadState *thread_state;
1983 PyObject *callable;
1984 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02001985 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001986 int error;
1987} _PySSLPasswordInfo;
1988
1989static int
1990_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
1991 const char *bad_type_error)
1992{
1993 /* Set the password and size fields of a _PySSLPasswordInfo struct
1994 from a unicode, bytes, or byte array object.
1995 The password field will be dynamically allocated and must be freed
1996 by the caller */
1997 PyObject *password_bytes = NULL;
1998 const char *data = NULL;
1999 Py_ssize_t size;
2000
2001 if (PyUnicode_Check(password)) {
2002 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2003 if (!password_bytes) {
2004 goto error;
2005 }
2006 data = PyBytes_AS_STRING(password_bytes);
2007 size = PyBytes_GET_SIZE(password_bytes);
2008 } else if (PyBytes_Check(password)) {
2009 data = PyBytes_AS_STRING(password);
2010 size = PyBytes_GET_SIZE(password);
2011 } else if (PyByteArray_Check(password)) {
2012 data = PyByteArray_AS_STRING(password);
2013 size = PyByteArray_GET_SIZE(password);
2014 } else {
2015 PyErr_SetString(PyExc_TypeError, bad_type_error);
2016 goto error;
2017 }
2018
Victor Stinner9ee02032013-06-23 15:08:23 +02002019 if (size > (Py_ssize_t)INT_MAX) {
2020 PyErr_Format(PyExc_ValueError,
2021 "password cannot be longer than %d bytes", INT_MAX);
2022 goto error;
2023 }
2024
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002025 free(pw_info->password);
2026 pw_info->password = malloc(size);
2027 if (!pw_info->password) {
2028 PyErr_SetString(PyExc_MemoryError,
2029 "unable to allocate password buffer");
2030 goto error;
2031 }
2032 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002033 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002034
2035 Py_XDECREF(password_bytes);
2036 return 1;
2037
2038error:
2039 Py_XDECREF(password_bytes);
2040 return 0;
2041}
2042
2043static int
2044_password_callback(char *buf, int size, int rwflag, void *userdata)
2045{
2046 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2047 PyObject *fn_ret = NULL;
2048
2049 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2050
2051 if (pw_info->callable) {
2052 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2053 if (!fn_ret) {
2054 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2055 core python API, so we could use it to add a frame here */
2056 goto error;
2057 }
2058
2059 if (!_pwinfo_set(pw_info, fn_ret,
2060 "password callback must return a string")) {
2061 goto error;
2062 }
2063 Py_CLEAR(fn_ret);
2064 }
2065
2066 if (pw_info->size > size) {
2067 PyErr_Format(PyExc_ValueError,
2068 "password cannot be longer than %d bytes", size);
2069 goto error;
2070 }
2071
2072 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2073 memcpy(buf, pw_info->password, pw_info->size);
2074 return pw_info->size;
2075
2076error:
2077 Py_XDECREF(fn_ret);
2078 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2079 pw_info->error = 1;
2080 return -1;
2081}
2082
Antoine Pitroub5218772010-05-21 09:56:06 +00002083static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002084load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2085{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002086 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2087 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002088 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002089 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2090 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2091 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002092 int r;
2093
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002094 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002095 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002096 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002097 "O|OO:load_cert_chain", kwlist,
2098 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002099 return NULL;
2100 if (keyfile == Py_None)
2101 keyfile = NULL;
2102 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2103 PyErr_SetString(PyExc_TypeError,
2104 "certfile should be a valid filesystem path");
2105 return NULL;
2106 }
2107 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2108 PyErr_SetString(PyExc_TypeError,
2109 "keyfile should be a valid filesystem path");
2110 goto error;
2111 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002112 if (password && password != Py_None) {
2113 if (PyCallable_Check(password)) {
2114 pw_info.callable = password;
2115 } else if (!_pwinfo_set(&pw_info, password,
2116 "password should be a string or callable")) {
2117 goto error;
2118 }
2119 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2120 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2121 }
2122 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002123 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2124 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002125 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002126 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002127 if (pw_info.error) {
2128 ERR_clear_error();
2129 /* the password callback has already set the error information */
2130 }
2131 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002132 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002133 PyErr_SetFromErrno(PyExc_IOError);
2134 }
2135 else {
2136 _setSSLError(NULL, 0, __FILE__, __LINE__);
2137 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002138 goto error;
2139 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002140 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002141 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002142 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2143 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002144 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2145 Py_CLEAR(keyfile_bytes);
2146 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002147 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002148 if (pw_info.error) {
2149 ERR_clear_error();
2150 /* the password callback has already set the error information */
2151 }
2152 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002153 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002154 PyErr_SetFromErrno(PyExc_IOError);
2155 }
2156 else {
2157 _setSSLError(NULL, 0, __FILE__, __LINE__);
2158 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002159 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002160 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002161 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002162 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002163 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002164 if (r != 1) {
2165 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002166 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002167 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002168 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2169 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2170 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002171 Py_RETURN_NONE;
2172
2173error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002174 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2175 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2176 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002177 Py_XDECREF(keyfile_bytes);
2178 Py_XDECREF(certfile_bytes);
2179 return NULL;
2180}
2181
2182static PyObject *
2183load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2184{
2185 char *kwlist[] = {"cafile", "capath", NULL};
2186 PyObject *cafile = NULL, *capath = NULL;
2187 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2188 const char *cafile_buf = NULL, *capath_buf = NULL;
2189 int r;
2190
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002191 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002192 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2193 "|OO:load_verify_locations", kwlist,
2194 &cafile, &capath))
2195 return NULL;
2196 if (cafile == Py_None)
2197 cafile = NULL;
2198 if (capath == Py_None)
2199 capath = NULL;
2200 if (cafile == NULL && capath == NULL) {
2201 PyErr_SetString(PyExc_TypeError,
2202 "cafile and capath cannot be both omitted");
2203 return NULL;
2204 }
2205 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2206 PyErr_SetString(PyExc_TypeError,
2207 "cafile should be a valid filesystem path");
2208 return NULL;
2209 }
2210 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00002211 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002212 PyErr_SetString(PyExc_TypeError,
2213 "capath should be a valid filesystem path");
2214 return NULL;
2215 }
2216 if (cafile)
2217 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2218 if (capath)
2219 capath_buf = PyBytes_AS_STRING(capath_bytes);
2220 PySSL_BEGIN_ALLOW_THREADS
2221 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2222 PySSL_END_ALLOW_THREADS
2223 Py_XDECREF(cafile_bytes);
2224 Py_XDECREF(capath_bytes);
2225 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002226 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002227 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002228 PyErr_SetFromErrno(PyExc_IOError);
2229 }
2230 else {
2231 _setSSLError(NULL, 0, __FILE__, __LINE__);
2232 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002233 return NULL;
2234 }
2235 Py_RETURN_NONE;
2236}
2237
2238static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002239load_dh_params(PySSLContext *self, PyObject *filepath)
2240{
2241 FILE *f;
2242 DH *dh;
2243
2244 f = _Py_fopen(filepath, "rb");
2245 if (f == NULL) {
2246 if (!PyErr_Occurred())
2247 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2248 return NULL;
2249 }
2250 errno = 0;
2251 PySSL_BEGIN_ALLOW_THREADS
2252 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002253 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002254 PySSL_END_ALLOW_THREADS
2255 if (dh == NULL) {
2256 if (errno != 0) {
2257 ERR_clear_error();
2258 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2259 }
2260 else {
2261 _setSSLError(NULL, 0, __FILE__, __LINE__);
2262 }
2263 return NULL;
2264 }
2265 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2266 _setSSLError(NULL, 0, __FILE__, __LINE__);
2267 DH_free(dh);
2268 Py_RETURN_NONE;
2269}
2270
2271static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002272context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2273{
Antoine Pitroud5323212010-10-22 18:19:07 +00002274 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002275 PySocketSockObject *sock;
2276 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002277 char *hostname = NULL;
2278 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002279
Antoine Pitroud5323212010-10-22 18:19:07 +00002280 /* server_hostname is either None (or absent), or to be encoded
2281 using the idna encoding. */
2282 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002283 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002284 &sock, &server_side,
2285 Py_TYPE(Py_None), &hostname_obj)) {
2286 PyErr_Clear();
2287 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2288 PySocketModule.Sock_Type,
2289 &sock, &server_side,
2290 "idna", &hostname))
2291 return NULL;
2292#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
2293 PyMem_Free(hostname);
2294 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2295 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002296 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002297#endif
2298 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002299
Antoine Pitroud5323212010-10-22 18:19:07 +00002300 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
2301 hostname);
2302 if (hostname != NULL)
2303 PyMem_Free(hostname);
2304 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002305}
2306
Antoine Pitroub0182c82010-10-12 20:09:02 +00002307static PyObject *
2308session_stats(PySSLContext *self, PyObject *unused)
2309{
2310 int r;
2311 PyObject *value, *stats = PyDict_New();
2312 if (!stats)
2313 return NULL;
2314
2315#define ADD_STATS(SSL_NAME, KEY_NAME) \
2316 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2317 if (value == NULL) \
2318 goto error; \
2319 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2320 Py_DECREF(value); \
2321 if (r < 0) \
2322 goto error;
2323
2324 ADD_STATS(number, "number");
2325 ADD_STATS(connect, "connect");
2326 ADD_STATS(connect_good, "connect_good");
2327 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2328 ADD_STATS(accept, "accept");
2329 ADD_STATS(accept_good, "accept_good");
2330 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2331 ADD_STATS(accept, "accept");
2332 ADD_STATS(hits, "hits");
2333 ADD_STATS(misses, "misses");
2334 ADD_STATS(timeouts, "timeouts");
2335 ADD_STATS(cache_full, "cache_full");
2336
2337#undef ADD_STATS
2338
2339 return stats;
2340
2341error:
2342 Py_DECREF(stats);
2343 return NULL;
2344}
2345
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002346static PyObject *
2347set_default_verify_paths(PySSLContext *self, PyObject *unused)
2348{
2349 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2350 _setSSLError(NULL, 0, __FILE__, __LINE__);
2351 return NULL;
2352 }
2353 Py_RETURN_NONE;
2354}
2355
Antoine Pitrou501da612011-12-21 09:27:41 +01002356#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002357static PyObject *
2358set_ecdh_curve(PySSLContext *self, PyObject *name)
2359{
2360 PyObject *name_bytes;
2361 int nid;
2362 EC_KEY *key;
2363
2364 if (!PyUnicode_FSConverter(name, &name_bytes))
2365 return NULL;
2366 assert(PyBytes_Check(name_bytes));
2367 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2368 Py_DECREF(name_bytes);
2369 if (nid == 0) {
2370 PyErr_Format(PyExc_ValueError,
2371 "unknown elliptic curve name %R", name);
2372 return NULL;
2373 }
2374 key = EC_KEY_new_by_curve_name(nid);
2375 if (key == NULL) {
2376 _setSSLError(NULL, 0, __FILE__, __LINE__);
2377 return NULL;
2378 }
2379 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2380 EC_KEY_free(key);
2381 Py_RETURN_NONE;
2382}
Antoine Pitrou501da612011-12-21 09:27:41 +01002383#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002384
Antoine Pitrou152efa22010-05-16 18:19:27 +00002385static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002386 {"options", (getter) get_options,
2387 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002388 {"verify_mode", (getter) get_verify_mode,
2389 (setter) set_verify_mode, NULL},
2390 {NULL}, /* sentinel */
2391};
2392
2393static struct PyMethodDef context_methods[] = {
2394 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2395 METH_VARARGS | METH_KEYWORDS, NULL},
2396 {"set_ciphers", (PyCFunction) set_ciphers,
2397 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002398 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2399 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002400 {"load_cert_chain", (PyCFunction) load_cert_chain,
2401 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002402 {"load_dh_params", (PyCFunction) load_dh_params,
2403 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002404 {"load_verify_locations", (PyCFunction) load_verify_locations,
2405 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002406 {"session_stats", (PyCFunction) session_stats,
2407 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002408 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2409 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002410#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002411 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2412 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002413#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002414 {NULL, NULL} /* sentinel */
2415};
2416
2417static PyTypeObject PySSLContext_Type = {
2418 PyVarObject_HEAD_INIT(NULL, 0)
2419 "_ssl._SSLContext", /*tp_name*/
2420 sizeof(PySSLContext), /*tp_basicsize*/
2421 0, /*tp_itemsize*/
2422 (destructor)context_dealloc, /*tp_dealloc*/
2423 0, /*tp_print*/
2424 0, /*tp_getattr*/
2425 0, /*tp_setattr*/
2426 0, /*tp_reserved*/
2427 0, /*tp_repr*/
2428 0, /*tp_as_number*/
2429 0, /*tp_as_sequence*/
2430 0, /*tp_as_mapping*/
2431 0, /*tp_hash*/
2432 0, /*tp_call*/
2433 0, /*tp_str*/
2434 0, /*tp_getattro*/
2435 0, /*tp_setattro*/
2436 0, /*tp_as_buffer*/
2437 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
2438 0, /*tp_doc*/
2439 0, /*tp_traverse*/
2440 0, /*tp_clear*/
2441 0, /*tp_richcompare*/
2442 0, /*tp_weaklistoffset*/
2443 0, /*tp_iter*/
2444 0, /*tp_iternext*/
2445 context_methods, /*tp_methods*/
2446 0, /*tp_members*/
2447 context_getsetlist, /*tp_getset*/
2448 0, /*tp_base*/
2449 0, /*tp_dict*/
2450 0, /*tp_descr_get*/
2451 0, /*tp_descr_set*/
2452 0, /*tp_dictoffset*/
2453 0, /*tp_init*/
2454 0, /*tp_alloc*/
2455 context_new, /*tp_new*/
2456};
2457
2458
2459
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002460#ifdef HAVE_OPENSSL_RAND
2461
2462/* helper routines for seeding the SSL PRNG */
2463static PyObject *
2464PySSL_RAND_add(PyObject *self, PyObject *args)
2465{
2466 char *buf;
2467 int len;
2468 double entropy;
2469
2470 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002471 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002472 RAND_add(buf, len, entropy);
2473 Py_INCREF(Py_None);
2474 return Py_None;
2475}
2476
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002477PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002478"RAND_add(string, entropy)\n\
2479\n\
2480Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002481bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002482
2483static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002484PySSL_RAND(int len, int pseudo)
2485{
2486 int ok;
2487 PyObject *bytes;
2488 unsigned long err;
2489 const char *errstr;
2490 PyObject *v;
2491
Victor Stinner1e81a392013-12-19 16:47:04 +01002492 if (len < 0) {
2493 PyErr_SetString(PyExc_ValueError, "num must be positive");
2494 return NULL;
2495 }
2496
Victor Stinner99c8b162011-05-24 12:05:19 +02002497 bytes = PyBytes_FromStringAndSize(NULL, len);
2498 if (bytes == NULL)
2499 return NULL;
2500 if (pseudo) {
2501 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2502 if (ok == 0 || ok == 1)
2503 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2504 }
2505 else {
2506 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2507 if (ok == 1)
2508 return bytes;
2509 }
2510 Py_DECREF(bytes);
2511
2512 err = ERR_get_error();
2513 errstr = ERR_reason_error_string(err);
2514 v = Py_BuildValue("(ks)", err, errstr);
2515 if (v != NULL) {
2516 PyErr_SetObject(PySSLErrorObject, v);
2517 Py_DECREF(v);
2518 }
2519 return NULL;
2520}
2521
2522static PyObject *
2523PySSL_RAND_bytes(PyObject *self, PyObject *args)
2524{
2525 int len;
2526 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2527 return NULL;
2528 return PySSL_RAND(len, 0);
2529}
2530
2531PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2532"RAND_bytes(n) -> bytes\n\
2533\n\
2534Generate n cryptographically strong pseudo-random bytes.");
2535
2536static PyObject *
2537PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2538{
2539 int len;
2540 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2541 return NULL;
2542 return PySSL_RAND(len, 1);
2543}
2544
2545PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2546"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2547\n\
2548Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2549generated are cryptographically strong.");
2550
2551static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002552PySSL_RAND_status(PyObject *self)
2553{
Christian Heimes217cfd12007-12-02 14:31:20 +00002554 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002555}
2556
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002557PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002558"RAND_status() -> 0 or 1\n\
2559\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002560Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2561It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2562using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002563
2564static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002565PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002566{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002567 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002568 int bytes;
2569
Jesus Ceac8754a12012-09-11 02:00:58 +02002570 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002571 PyUnicode_FSConverter, &path))
2572 return NULL;
2573
2574 bytes = RAND_egd(PyBytes_AsString(path));
2575 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002576 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002577 PyErr_SetString(PySSLErrorObject,
2578 "EGD connection failed or EGD did not return "
2579 "enough data to seed the PRNG");
2580 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002581 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002582 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002583}
2584
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002585PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002586"RAND_egd(path) -> bytes\n\
2587\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002588Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2589Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02002590fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002591
Christian Heimesf77b4b22013-08-21 13:26:05 +02002592#endif /* HAVE_OPENSSL_RAND */
2593
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002594
Bill Janssen40a0f662008-08-12 16:56:25 +00002595
2596
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002597/* List of functions exported by this module. */
2598
2599static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002600 {"_test_decode_cert", PySSL_test_decode_certificate,
2601 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002602#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002603 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
2604 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02002605 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
2606 PySSL_RAND_bytes_doc},
2607 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
2608 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002609 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002610 PySSL_RAND_egd_doc},
2611 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
2612 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002613#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002614 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002615};
2616
2617
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002618#ifdef WITH_THREAD
2619
2620/* an implementation of OpenSSL threading operations in terms
2621 of the Python C thread library */
2622
2623static PyThread_type_lock *_ssl_locks = NULL;
2624
Christian Heimes4d98ca92013-08-19 17:36:29 +02002625#if OPENSSL_VERSION_NUMBER >= 0x10000000
2626/* use new CRYPTO_THREADID API. */
2627static void
2628_ssl_threadid_callback(CRYPTO_THREADID *id)
2629{
2630 CRYPTO_THREADID_set_numeric(id,
2631 (unsigned long)PyThread_get_thread_ident());
2632}
2633#else
2634/* deprecated CRYPTO_set_id_callback() API. */
2635static unsigned long
2636_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002637 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002638}
Christian Heimes4d98ca92013-08-19 17:36:29 +02002639#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002640
Bill Janssen6e027db2007-11-15 22:23:56 +00002641static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002642 (int mode, int n, const char *file, int line) {
2643 /* this function is needed to perform locking on shared data
2644 structures. (Note that OpenSSL uses a number of global data
2645 structures that will be implicitly shared whenever multiple
2646 threads use OpenSSL.) Multi-threaded applications will
2647 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002648
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002649 locking_function() must be able to handle up to
2650 CRYPTO_num_locks() different mutex locks. It sets the n-th
2651 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002652
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002653 file and line are the file number of the function setting the
2654 lock. They can be useful for debugging.
2655 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002656
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002657 if ((_ssl_locks == NULL) ||
2658 (n < 0) || ((unsigned)n >= _ssl_locks_count))
2659 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002660
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002661 if (mode & CRYPTO_LOCK) {
2662 PyThread_acquire_lock(_ssl_locks[n], 1);
2663 } else {
2664 PyThread_release_lock(_ssl_locks[n]);
2665 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002666}
2667
2668static int _setup_ssl_threads(void) {
2669
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002670 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002671
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002672 if (_ssl_locks == NULL) {
2673 _ssl_locks_count = CRYPTO_num_locks();
2674 _ssl_locks = (PyThread_type_lock *)
2675 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2676 if (_ssl_locks == NULL)
2677 return 0;
2678 memset(_ssl_locks, 0,
2679 sizeof(PyThread_type_lock) * _ssl_locks_count);
2680 for (i = 0; i < _ssl_locks_count; i++) {
2681 _ssl_locks[i] = PyThread_allocate_lock();
2682 if (_ssl_locks[i] == NULL) {
2683 unsigned int j;
2684 for (j = 0; j < i; j++) {
2685 PyThread_free_lock(_ssl_locks[j]);
2686 }
2687 free(_ssl_locks);
2688 return 0;
2689 }
2690 }
2691 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02002692#if OPENSSL_VERSION_NUMBER >= 0x10000000
2693 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
2694#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002695 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02002696#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002697 }
2698 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002699}
2700
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002701#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002702
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002703PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002704"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002705for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002706
Martin v. Löwis1a214512008-06-11 05:26:20 +00002707
2708static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002709 PyModuleDef_HEAD_INIT,
2710 "_ssl",
2711 module_doc,
2712 -1,
2713 PySSL_methods,
2714 NULL,
2715 NULL,
2716 NULL,
2717 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002718};
2719
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002720
2721static void
2722parse_openssl_version(unsigned long libver,
2723 unsigned int *major, unsigned int *minor,
2724 unsigned int *fix, unsigned int *patch,
2725 unsigned int *status)
2726{
2727 *status = libver & 0xF;
2728 libver >>= 4;
2729 *patch = libver & 0xFF;
2730 libver >>= 8;
2731 *fix = libver & 0xFF;
2732 libver >>= 8;
2733 *minor = libver & 0xFF;
2734 libver >>= 8;
2735 *major = libver & 0xFF;
2736}
2737
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002738PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002739PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002740{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002741 PyObject *m, *d, *r;
2742 unsigned long libver;
2743 unsigned int major, minor, fix, patch, status;
2744 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002745 struct py_ssl_error_code *errcode;
2746 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002747
Antoine Pitrou152efa22010-05-16 18:19:27 +00002748 if (PyType_Ready(&PySSLContext_Type) < 0)
2749 return NULL;
2750 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002751 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002752
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002753 m = PyModule_Create(&_sslmodule);
2754 if (m == NULL)
2755 return NULL;
2756 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002757
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002758 /* Load _socket module and its C API */
2759 socket_api = PySocketModule_ImportModuleAndAPI();
2760 if (!socket_api)
2761 return NULL;
2762 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002763
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002764 /* Init OpenSSL */
2765 SSL_load_error_strings();
2766 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002767#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002768 /* note that this will start threading if not already started */
2769 if (!_setup_ssl_threads()) {
2770 return NULL;
2771 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002772#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002773 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002774
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002775 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002776 sslerror_type_slots[0].pfunc = PyExc_OSError;
2777 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002778 if (PySSLErrorObject == NULL)
2779 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002780
Antoine Pitrou41032a62011-10-27 23:56:55 +02002781 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
2782 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
2783 PySSLErrorObject, NULL);
2784 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
2785 "ssl.SSLWantReadError", SSLWantReadError_doc,
2786 PySSLErrorObject, NULL);
2787 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
2788 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
2789 PySSLErrorObject, NULL);
2790 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
2791 "ssl.SSLSyscallError", SSLSyscallError_doc,
2792 PySSLErrorObject, NULL);
2793 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
2794 "ssl.SSLEOFError", SSLEOFError_doc,
2795 PySSLErrorObject, NULL);
2796 if (PySSLZeroReturnErrorObject == NULL
2797 || PySSLWantReadErrorObject == NULL
2798 || PySSLWantWriteErrorObject == NULL
2799 || PySSLSyscallErrorObject == NULL
2800 || PySSLEOFErrorObject == NULL)
2801 return NULL;
2802 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
2803 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
2804 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
2805 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
2806 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
2807 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002808 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002809 if (PyDict_SetItemString(d, "_SSLContext",
2810 (PyObject *)&PySSLContext_Type) != 0)
2811 return NULL;
2812 if (PyDict_SetItemString(d, "_SSLSocket",
2813 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002814 return NULL;
2815 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2816 PY_SSL_ERROR_ZERO_RETURN);
2817 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2818 PY_SSL_ERROR_WANT_READ);
2819 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2820 PY_SSL_ERROR_WANT_WRITE);
2821 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2822 PY_SSL_ERROR_WANT_X509_LOOKUP);
2823 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2824 PY_SSL_ERROR_SYSCALL);
2825 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2826 PY_SSL_ERROR_SSL);
2827 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2828 PY_SSL_ERROR_WANT_CONNECT);
2829 /* non ssl.h errorcodes */
2830 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2831 PY_SSL_ERROR_EOF);
2832 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2833 PY_SSL_ERROR_INVALID_ERROR_CODE);
2834 /* cert requirements */
2835 PyModule_AddIntConstant(m, "CERT_NONE",
2836 PY_SSL_CERT_NONE);
2837 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2838 PY_SSL_CERT_OPTIONAL);
2839 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2840 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002841
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002842 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02002843#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002844 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2845 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02002846#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002847 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2848 PY_SSL_VERSION_SSL3);
2849 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2850 PY_SSL_VERSION_SSL23);
2851 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2852 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002853
Antoine Pitroub5218772010-05-21 09:56:06 +00002854 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01002855 PyModule_AddIntConstant(m, "OP_ALL",
2856 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00002857 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2858 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2859 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou6db49442011-12-19 13:27:11 +01002860 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
2861 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002862 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002863#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002864 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002865#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002866#ifdef SSL_OP_NO_COMPRESSION
2867 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
2868 SSL_OP_NO_COMPRESSION);
2869#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00002870
Antoine Pitroud5323212010-10-22 18:19:07 +00002871#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2872 r = Py_True;
2873#else
2874 r = Py_False;
2875#endif
2876 Py_INCREF(r);
2877 PyModule_AddObject(m, "HAS_SNI", r);
2878
Antoine Pitroud6494802011-07-21 01:11:30 +02002879#if HAVE_OPENSSL_FINISHED
2880 r = Py_True;
2881#else
2882 r = Py_False;
2883#endif
2884 Py_INCREF(r);
2885 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
2886
Antoine Pitrou501da612011-12-21 09:27:41 +01002887#ifdef OPENSSL_NO_ECDH
2888 r = Py_False;
2889#else
2890 r = Py_True;
2891#endif
2892 Py_INCREF(r);
2893 PyModule_AddObject(m, "HAS_ECDH", r);
2894
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002895#ifdef OPENSSL_NPN_NEGOTIATED
2896 r = Py_True;
2897#else
2898 r = Py_False;
2899#endif
2900 Py_INCREF(r);
2901 PyModule_AddObject(m, "HAS_NPN", r);
2902
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002903 /* Mappings for error codes */
2904 err_codes_to_names = PyDict_New();
2905 err_names_to_codes = PyDict_New();
2906 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
2907 return NULL;
2908 errcode = error_codes;
2909 while (errcode->mnemonic != NULL) {
2910 PyObject *mnemo, *key;
2911 mnemo = PyUnicode_FromString(errcode->mnemonic);
2912 key = Py_BuildValue("ii", errcode->library, errcode->reason);
2913 if (mnemo == NULL || key == NULL)
2914 return NULL;
2915 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
2916 return NULL;
2917 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
2918 return NULL;
2919 Py_DECREF(key);
2920 Py_DECREF(mnemo);
2921 errcode++;
2922 }
2923 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
2924 return NULL;
2925 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
2926 return NULL;
2927
2928 lib_codes_to_names = PyDict_New();
2929 if (lib_codes_to_names == NULL)
2930 return NULL;
2931 libcode = library_codes;
2932 while (libcode->library != NULL) {
2933 PyObject *mnemo, *key;
2934 key = PyLong_FromLong(libcode->code);
2935 mnemo = PyUnicode_FromString(libcode->library);
2936 if (key == NULL || mnemo == NULL)
2937 return NULL;
2938 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
2939 return NULL;
2940 Py_DECREF(key);
2941 Py_DECREF(mnemo);
2942 libcode++;
2943 }
2944 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
2945 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02002946
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002947 /* OpenSSL version */
2948 /* SSLeay() gives us the version of the library linked against,
2949 which could be different from the headers version.
2950 */
2951 libver = SSLeay();
2952 r = PyLong_FromUnsignedLong(libver);
2953 if (r == NULL)
2954 return NULL;
2955 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2956 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002957 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002958 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2959 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2960 return NULL;
2961 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2962 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2963 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002964
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002965 libver = OPENSSL_VERSION_NUMBER;
2966 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
2967 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2968 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
2969 return NULL;
2970
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002971 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002972}