blob: 374d930166f7cd302a805fecb1cdad2f0565346c [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;
1740 SSL_CTX *ctx = NULL;
1741
1742 if (!PyArg_ParseTupleAndKeywords(
1743 args, kwds, "i:_SSLContext", kwlist,
1744 &proto_version))
1745 return NULL;
1746
1747 PySSL_BEGIN_ALLOW_THREADS
1748 if (proto_version == PY_SSL_VERSION_TLS1)
1749 ctx = SSL_CTX_new(TLSv1_method());
1750 else if (proto_version == PY_SSL_VERSION_SSL3)
1751 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001752#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001753 else if (proto_version == PY_SSL_VERSION_SSL2)
1754 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001755#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001756 else if (proto_version == PY_SSL_VERSION_SSL23)
1757 ctx = SSL_CTX_new(SSLv23_method());
1758 else
1759 proto_version = -1;
1760 PySSL_END_ALLOW_THREADS
1761
1762 if (proto_version == -1) {
1763 PyErr_SetString(PyExc_ValueError,
1764 "invalid protocol version");
1765 return NULL;
1766 }
1767 if (ctx == NULL) {
1768 PyErr_SetString(PySSLErrorObject,
1769 "failed to allocate SSL context");
1770 return NULL;
1771 }
1772
1773 assert(type != NULL && type->tp_alloc != NULL);
1774 self = (PySSLContext *) type->tp_alloc(type, 0);
1775 if (self == NULL) {
1776 SSL_CTX_free(ctx);
1777 return NULL;
1778 }
1779 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02001780#ifdef OPENSSL_NPN_NEGOTIATED
1781 self->npn_protocols = NULL;
1782#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001783 /* Defaults */
1784 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001785 SSL_CTX_set_options(self->ctx,
1786 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001787
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001788#define SID_CTX "Python"
1789 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1790 sizeof(SID_CTX));
1791#undef SID_CTX
1792
Antoine Pitrou152efa22010-05-16 18:19:27 +00001793 return (PyObject *)self;
1794}
1795
1796static void
1797context_dealloc(PySSLContext *self)
1798{
1799 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001800#ifdef OPENSSL_NPN_NEGOTIATED
1801 PyMem_Free(self->npn_protocols);
1802#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001803 Py_TYPE(self)->tp_free(self);
1804}
1805
1806static PyObject *
1807set_ciphers(PySSLContext *self, PyObject *args)
1808{
1809 int ret;
1810 const char *cipherlist;
1811
1812 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1813 return NULL;
1814 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1815 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001816 /* Clearing the error queue is necessary on some OpenSSL versions,
1817 otherwise the error will be reported again when another SSL call
1818 is done. */
1819 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001820 PyErr_SetString(PySSLErrorObject,
1821 "No cipher can be selected.");
1822 return NULL;
1823 }
1824 Py_RETURN_NONE;
1825}
1826
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001827#ifdef OPENSSL_NPN_NEGOTIATED
1828/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
1829static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001830_advertiseNPN_cb(SSL *s,
1831 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001832 void *args)
1833{
1834 PySSLContext *ssl_ctx = (PySSLContext *) args;
1835
1836 if (ssl_ctx->npn_protocols == NULL) {
1837 *data = (unsigned char *) "";
1838 *len = 0;
1839 } else {
1840 *data = (unsigned char *) ssl_ctx->npn_protocols;
1841 *len = ssl_ctx->npn_protocols_len;
1842 }
1843
1844 return SSL_TLSEXT_ERR_OK;
1845}
1846/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
1847static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001848_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001849 unsigned char **out, unsigned char *outlen,
1850 const unsigned char *server, unsigned int server_len,
1851 void *args)
1852{
1853 PySSLContext *ssl_ctx = (PySSLContext *) args;
1854
1855 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
1856 int client_len;
1857
1858 if (client == NULL) {
1859 client = (unsigned char *) "";
1860 client_len = 0;
1861 } else {
1862 client_len = ssl_ctx->npn_protocols_len;
1863 }
1864
1865 SSL_select_next_proto(out, outlen,
1866 server, server_len,
1867 client, client_len);
1868
1869 return SSL_TLSEXT_ERR_OK;
1870}
1871#endif
1872
1873static PyObject *
1874_set_npn_protocols(PySSLContext *self, PyObject *args)
1875{
1876#ifdef OPENSSL_NPN_NEGOTIATED
1877 Py_buffer protos;
1878
1879 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
1880 return NULL;
1881
Christian Heimes5cb31c92012-09-20 12:42:54 +02001882 if (self->npn_protocols != NULL) {
1883 PyMem_Free(self->npn_protocols);
1884 }
1885
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001886 self->npn_protocols = PyMem_Malloc(protos.len);
1887 if (self->npn_protocols == NULL) {
1888 PyBuffer_Release(&protos);
1889 return PyErr_NoMemory();
1890 }
1891 memcpy(self->npn_protocols, protos.buf, protos.len);
1892 self->npn_protocols_len = (int) protos.len;
1893
1894 /* set both server and client callbacks, because the context can
1895 * be used to create both types of sockets */
1896 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
1897 _advertiseNPN_cb,
1898 self);
1899 SSL_CTX_set_next_proto_select_cb(self->ctx,
1900 _selectNPN_cb,
1901 self);
1902
1903 PyBuffer_Release(&protos);
1904 Py_RETURN_NONE;
1905#else
1906 PyErr_SetString(PyExc_NotImplementedError,
1907 "The NPN extension requires OpenSSL 1.0.1 or later.");
1908 return NULL;
1909#endif
1910}
1911
Antoine Pitrou152efa22010-05-16 18:19:27 +00001912static PyObject *
1913get_verify_mode(PySSLContext *self, void *c)
1914{
1915 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1916 case SSL_VERIFY_NONE:
1917 return PyLong_FromLong(PY_SSL_CERT_NONE);
1918 case SSL_VERIFY_PEER:
1919 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1920 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1921 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1922 }
1923 PyErr_SetString(PySSLErrorObject,
1924 "invalid return value from SSL_CTX_get_verify_mode");
1925 return NULL;
1926}
1927
1928static int
1929set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1930{
1931 int n, mode;
1932 if (!PyArg_Parse(arg, "i", &n))
1933 return -1;
1934 if (n == PY_SSL_CERT_NONE)
1935 mode = SSL_VERIFY_NONE;
1936 else if (n == PY_SSL_CERT_OPTIONAL)
1937 mode = SSL_VERIFY_PEER;
1938 else if (n == PY_SSL_CERT_REQUIRED)
1939 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1940 else {
1941 PyErr_SetString(PyExc_ValueError,
1942 "invalid value for verify_mode");
1943 return -1;
1944 }
1945 SSL_CTX_set_verify(self->ctx, mode, NULL);
1946 return 0;
1947}
1948
1949static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001950get_options(PySSLContext *self, void *c)
1951{
1952 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1953}
1954
1955static int
1956set_options(PySSLContext *self, PyObject *arg, void *c)
1957{
1958 long new_opts, opts, set, clear;
1959 if (!PyArg_Parse(arg, "l", &new_opts))
1960 return -1;
1961 opts = SSL_CTX_get_options(self->ctx);
1962 clear = opts & ~new_opts;
1963 set = ~opts & new_opts;
1964 if (clear) {
1965#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1966 SSL_CTX_clear_options(self->ctx, clear);
1967#else
1968 PyErr_SetString(PyExc_ValueError,
1969 "can't clear options before OpenSSL 0.9.8m");
1970 return -1;
1971#endif
1972 }
1973 if (set)
1974 SSL_CTX_set_options(self->ctx, set);
1975 return 0;
1976}
1977
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001978typedef struct {
1979 PyThreadState *thread_state;
1980 PyObject *callable;
1981 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02001982 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001983 int error;
1984} _PySSLPasswordInfo;
1985
1986static int
1987_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
1988 const char *bad_type_error)
1989{
1990 /* Set the password and size fields of a _PySSLPasswordInfo struct
1991 from a unicode, bytes, or byte array object.
1992 The password field will be dynamically allocated and must be freed
1993 by the caller */
1994 PyObject *password_bytes = NULL;
1995 const char *data = NULL;
1996 Py_ssize_t size;
1997
1998 if (PyUnicode_Check(password)) {
1999 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2000 if (!password_bytes) {
2001 goto error;
2002 }
2003 data = PyBytes_AS_STRING(password_bytes);
2004 size = PyBytes_GET_SIZE(password_bytes);
2005 } else if (PyBytes_Check(password)) {
2006 data = PyBytes_AS_STRING(password);
2007 size = PyBytes_GET_SIZE(password);
2008 } else if (PyByteArray_Check(password)) {
2009 data = PyByteArray_AS_STRING(password);
2010 size = PyByteArray_GET_SIZE(password);
2011 } else {
2012 PyErr_SetString(PyExc_TypeError, bad_type_error);
2013 goto error;
2014 }
2015
Victor Stinner9ee02032013-06-23 15:08:23 +02002016 if (size > (Py_ssize_t)INT_MAX) {
2017 PyErr_Format(PyExc_ValueError,
2018 "password cannot be longer than %d bytes", INT_MAX);
2019 goto error;
2020 }
2021
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002022 free(pw_info->password);
2023 pw_info->password = malloc(size);
2024 if (!pw_info->password) {
2025 PyErr_SetString(PyExc_MemoryError,
2026 "unable to allocate password buffer");
2027 goto error;
2028 }
2029 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002030 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002031
2032 Py_XDECREF(password_bytes);
2033 return 1;
2034
2035error:
2036 Py_XDECREF(password_bytes);
2037 return 0;
2038}
2039
2040static int
2041_password_callback(char *buf, int size, int rwflag, void *userdata)
2042{
2043 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2044 PyObject *fn_ret = NULL;
2045
2046 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2047
2048 if (pw_info->callable) {
2049 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2050 if (!fn_ret) {
2051 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2052 core python API, so we could use it to add a frame here */
2053 goto error;
2054 }
2055
2056 if (!_pwinfo_set(pw_info, fn_ret,
2057 "password callback must return a string")) {
2058 goto error;
2059 }
2060 Py_CLEAR(fn_ret);
2061 }
2062
2063 if (pw_info->size > size) {
2064 PyErr_Format(PyExc_ValueError,
2065 "password cannot be longer than %d bytes", size);
2066 goto error;
2067 }
2068
2069 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2070 memcpy(buf, pw_info->password, pw_info->size);
2071 return pw_info->size;
2072
2073error:
2074 Py_XDECREF(fn_ret);
2075 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2076 pw_info->error = 1;
2077 return -1;
2078}
2079
Antoine Pitroub5218772010-05-21 09:56:06 +00002080static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002081load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2082{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002083 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2084 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002085 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002086 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2087 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2088 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002089 int r;
2090
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002091 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002092 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002093 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002094 "O|OO:load_cert_chain", kwlist,
2095 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002096 return NULL;
2097 if (keyfile == Py_None)
2098 keyfile = NULL;
2099 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2100 PyErr_SetString(PyExc_TypeError,
2101 "certfile should be a valid filesystem path");
2102 return NULL;
2103 }
2104 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2105 PyErr_SetString(PyExc_TypeError,
2106 "keyfile should be a valid filesystem path");
2107 goto error;
2108 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002109 if (password && password != Py_None) {
2110 if (PyCallable_Check(password)) {
2111 pw_info.callable = password;
2112 } else if (!_pwinfo_set(&pw_info, password,
2113 "password should be a string or callable")) {
2114 goto error;
2115 }
2116 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2117 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2118 }
2119 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002120 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2121 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002122 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002123 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002124 if (pw_info.error) {
2125 ERR_clear_error();
2126 /* the password callback has already set the error information */
2127 }
2128 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002129 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002130 PyErr_SetFromErrno(PyExc_IOError);
2131 }
2132 else {
2133 _setSSLError(NULL, 0, __FILE__, __LINE__);
2134 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002135 goto error;
2136 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002137 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002138 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002139 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2140 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002141 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2142 Py_CLEAR(keyfile_bytes);
2143 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002144 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002145 if (pw_info.error) {
2146 ERR_clear_error();
2147 /* the password callback has already set the error information */
2148 }
2149 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002150 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002151 PyErr_SetFromErrno(PyExc_IOError);
2152 }
2153 else {
2154 _setSSLError(NULL, 0, __FILE__, __LINE__);
2155 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002156 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002157 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002158 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002159 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002160 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002161 if (r != 1) {
2162 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002163 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002164 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002165 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2166 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2167 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002168 Py_RETURN_NONE;
2169
2170error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002171 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2172 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2173 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002174 Py_XDECREF(keyfile_bytes);
2175 Py_XDECREF(certfile_bytes);
2176 return NULL;
2177}
2178
2179static PyObject *
2180load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2181{
2182 char *kwlist[] = {"cafile", "capath", NULL};
2183 PyObject *cafile = NULL, *capath = NULL;
2184 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2185 const char *cafile_buf = NULL, *capath_buf = NULL;
2186 int r;
2187
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002188 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002189 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2190 "|OO:load_verify_locations", kwlist,
2191 &cafile, &capath))
2192 return NULL;
2193 if (cafile == Py_None)
2194 cafile = NULL;
2195 if (capath == Py_None)
2196 capath = NULL;
2197 if (cafile == NULL && capath == NULL) {
2198 PyErr_SetString(PyExc_TypeError,
2199 "cafile and capath cannot be both omitted");
2200 return NULL;
2201 }
2202 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2203 PyErr_SetString(PyExc_TypeError,
2204 "cafile should be a valid filesystem path");
2205 return NULL;
2206 }
2207 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00002208 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002209 PyErr_SetString(PyExc_TypeError,
2210 "capath should be a valid filesystem path");
2211 return NULL;
2212 }
2213 if (cafile)
2214 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2215 if (capath)
2216 capath_buf = PyBytes_AS_STRING(capath_bytes);
2217 PySSL_BEGIN_ALLOW_THREADS
2218 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2219 PySSL_END_ALLOW_THREADS
2220 Py_XDECREF(cafile_bytes);
2221 Py_XDECREF(capath_bytes);
2222 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002223 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002224 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002225 PyErr_SetFromErrno(PyExc_IOError);
2226 }
2227 else {
2228 _setSSLError(NULL, 0, __FILE__, __LINE__);
2229 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002230 return NULL;
2231 }
2232 Py_RETURN_NONE;
2233}
2234
2235static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002236load_dh_params(PySSLContext *self, PyObject *filepath)
2237{
2238 FILE *f;
2239 DH *dh;
2240
2241 f = _Py_fopen(filepath, "rb");
2242 if (f == NULL) {
2243 if (!PyErr_Occurred())
2244 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2245 return NULL;
2246 }
2247 errno = 0;
2248 PySSL_BEGIN_ALLOW_THREADS
2249 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002250 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002251 PySSL_END_ALLOW_THREADS
2252 if (dh == NULL) {
2253 if (errno != 0) {
2254 ERR_clear_error();
2255 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2256 }
2257 else {
2258 _setSSLError(NULL, 0, __FILE__, __LINE__);
2259 }
2260 return NULL;
2261 }
2262 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2263 _setSSLError(NULL, 0, __FILE__, __LINE__);
2264 DH_free(dh);
2265 Py_RETURN_NONE;
2266}
2267
2268static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002269context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2270{
Antoine Pitroud5323212010-10-22 18:19:07 +00002271 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002272 PySocketSockObject *sock;
2273 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002274 char *hostname = NULL;
2275 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002276
Antoine Pitroud5323212010-10-22 18:19:07 +00002277 /* server_hostname is either None (or absent), or to be encoded
2278 using the idna encoding. */
2279 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002280 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002281 &sock, &server_side,
2282 Py_TYPE(Py_None), &hostname_obj)) {
2283 PyErr_Clear();
2284 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2285 PySocketModule.Sock_Type,
2286 &sock, &server_side,
2287 "idna", &hostname))
2288 return NULL;
2289#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
2290 PyMem_Free(hostname);
2291 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2292 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002293 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002294#endif
2295 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002296
Antoine Pitroud5323212010-10-22 18:19:07 +00002297 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
2298 hostname);
2299 if (hostname != NULL)
2300 PyMem_Free(hostname);
2301 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002302}
2303
Antoine Pitroub0182c82010-10-12 20:09:02 +00002304static PyObject *
2305session_stats(PySSLContext *self, PyObject *unused)
2306{
2307 int r;
2308 PyObject *value, *stats = PyDict_New();
2309 if (!stats)
2310 return NULL;
2311
2312#define ADD_STATS(SSL_NAME, KEY_NAME) \
2313 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2314 if (value == NULL) \
2315 goto error; \
2316 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2317 Py_DECREF(value); \
2318 if (r < 0) \
2319 goto error;
2320
2321 ADD_STATS(number, "number");
2322 ADD_STATS(connect, "connect");
2323 ADD_STATS(connect_good, "connect_good");
2324 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2325 ADD_STATS(accept, "accept");
2326 ADD_STATS(accept_good, "accept_good");
2327 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2328 ADD_STATS(accept, "accept");
2329 ADD_STATS(hits, "hits");
2330 ADD_STATS(misses, "misses");
2331 ADD_STATS(timeouts, "timeouts");
2332 ADD_STATS(cache_full, "cache_full");
2333
2334#undef ADD_STATS
2335
2336 return stats;
2337
2338error:
2339 Py_DECREF(stats);
2340 return NULL;
2341}
2342
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002343static PyObject *
2344set_default_verify_paths(PySSLContext *self, PyObject *unused)
2345{
2346 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2347 _setSSLError(NULL, 0, __FILE__, __LINE__);
2348 return NULL;
2349 }
2350 Py_RETURN_NONE;
2351}
2352
Antoine Pitrou501da612011-12-21 09:27:41 +01002353#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002354static PyObject *
2355set_ecdh_curve(PySSLContext *self, PyObject *name)
2356{
2357 PyObject *name_bytes;
2358 int nid;
2359 EC_KEY *key;
2360
2361 if (!PyUnicode_FSConverter(name, &name_bytes))
2362 return NULL;
2363 assert(PyBytes_Check(name_bytes));
2364 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2365 Py_DECREF(name_bytes);
2366 if (nid == 0) {
2367 PyErr_Format(PyExc_ValueError,
2368 "unknown elliptic curve name %R", name);
2369 return NULL;
2370 }
2371 key = EC_KEY_new_by_curve_name(nid);
2372 if (key == NULL) {
2373 _setSSLError(NULL, 0, __FILE__, __LINE__);
2374 return NULL;
2375 }
2376 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2377 EC_KEY_free(key);
2378 Py_RETURN_NONE;
2379}
Antoine Pitrou501da612011-12-21 09:27:41 +01002380#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002381
Antoine Pitrou152efa22010-05-16 18:19:27 +00002382static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002383 {"options", (getter) get_options,
2384 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002385 {"verify_mode", (getter) get_verify_mode,
2386 (setter) set_verify_mode, NULL},
2387 {NULL}, /* sentinel */
2388};
2389
2390static struct PyMethodDef context_methods[] = {
2391 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2392 METH_VARARGS | METH_KEYWORDS, NULL},
2393 {"set_ciphers", (PyCFunction) set_ciphers,
2394 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002395 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2396 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002397 {"load_cert_chain", (PyCFunction) load_cert_chain,
2398 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002399 {"load_dh_params", (PyCFunction) load_dh_params,
2400 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002401 {"load_verify_locations", (PyCFunction) load_verify_locations,
2402 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002403 {"session_stats", (PyCFunction) session_stats,
2404 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002405 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2406 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002407#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002408 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2409 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002410#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002411 {NULL, NULL} /* sentinel */
2412};
2413
2414static PyTypeObject PySSLContext_Type = {
2415 PyVarObject_HEAD_INIT(NULL, 0)
2416 "_ssl._SSLContext", /*tp_name*/
2417 sizeof(PySSLContext), /*tp_basicsize*/
2418 0, /*tp_itemsize*/
2419 (destructor)context_dealloc, /*tp_dealloc*/
2420 0, /*tp_print*/
2421 0, /*tp_getattr*/
2422 0, /*tp_setattr*/
2423 0, /*tp_reserved*/
2424 0, /*tp_repr*/
2425 0, /*tp_as_number*/
2426 0, /*tp_as_sequence*/
2427 0, /*tp_as_mapping*/
2428 0, /*tp_hash*/
2429 0, /*tp_call*/
2430 0, /*tp_str*/
2431 0, /*tp_getattro*/
2432 0, /*tp_setattro*/
2433 0, /*tp_as_buffer*/
2434 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
2435 0, /*tp_doc*/
2436 0, /*tp_traverse*/
2437 0, /*tp_clear*/
2438 0, /*tp_richcompare*/
2439 0, /*tp_weaklistoffset*/
2440 0, /*tp_iter*/
2441 0, /*tp_iternext*/
2442 context_methods, /*tp_methods*/
2443 0, /*tp_members*/
2444 context_getsetlist, /*tp_getset*/
2445 0, /*tp_base*/
2446 0, /*tp_dict*/
2447 0, /*tp_descr_get*/
2448 0, /*tp_descr_set*/
2449 0, /*tp_dictoffset*/
2450 0, /*tp_init*/
2451 0, /*tp_alloc*/
2452 context_new, /*tp_new*/
2453};
2454
2455
2456
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002457#ifdef HAVE_OPENSSL_RAND
2458
2459/* helper routines for seeding the SSL PRNG */
2460static PyObject *
2461PySSL_RAND_add(PyObject *self, PyObject *args)
2462{
2463 char *buf;
2464 int len;
2465 double entropy;
2466
2467 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002468 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002469 RAND_add(buf, len, entropy);
2470 Py_INCREF(Py_None);
2471 return Py_None;
2472}
2473
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002474PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002475"RAND_add(string, entropy)\n\
2476\n\
2477Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002478bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002479
2480static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002481PySSL_RAND(int len, int pseudo)
2482{
2483 int ok;
2484 PyObject *bytes;
2485 unsigned long err;
2486 const char *errstr;
2487 PyObject *v;
2488
2489 bytes = PyBytes_FromStringAndSize(NULL, len);
2490 if (bytes == NULL)
2491 return NULL;
2492 if (pseudo) {
2493 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2494 if (ok == 0 || ok == 1)
2495 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2496 }
2497 else {
2498 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2499 if (ok == 1)
2500 return bytes;
2501 }
2502 Py_DECREF(bytes);
2503
2504 err = ERR_get_error();
2505 errstr = ERR_reason_error_string(err);
2506 v = Py_BuildValue("(ks)", err, errstr);
2507 if (v != NULL) {
2508 PyErr_SetObject(PySSLErrorObject, v);
2509 Py_DECREF(v);
2510 }
2511 return NULL;
2512}
2513
2514static PyObject *
2515PySSL_RAND_bytes(PyObject *self, PyObject *args)
2516{
2517 int len;
2518 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2519 return NULL;
2520 return PySSL_RAND(len, 0);
2521}
2522
2523PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2524"RAND_bytes(n) -> bytes\n\
2525\n\
2526Generate n cryptographically strong pseudo-random bytes.");
2527
2528static PyObject *
2529PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2530{
2531 int len;
2532 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2533 return NULL;
2534 return PySSL_RAND(len, 1);
2535}
2536
2537PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2538"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2539\n\
2540Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2541generated are cryptographically strong.");
2542
2543static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002544PySSL_RAND_status(PyObject *self)
2545{
Christian Heimes217cfd12007-12-02 14:31:20 +00002546 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002547}
2548
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002549PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002550"RAND_status() -> 0 or 1\n\
2551\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002552Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2553It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2554using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002555
2556static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002557PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002558{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002559 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002560 int bytes;
2561
Jesus Ceac8754a12012-09-11 02:00:58 +02002562 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002563 PyUnicode_FSConverter, &path))
2564 return NULL;
2565
2566 bytes = RAND_egd(PyBytes_AsString(path));
2567 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002568 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002569 PyErr_SetString(PySSLErrorObject,
2570 "EGD connection failed or EGD did not return "
2571 "enough data to seed the PRNG");
2572 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002573 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002574 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002575}
2576
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002577PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002578"RAND_egd(path) -> bytes\n\
2579\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002580Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2581Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02002582fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002583
Christian Heimesf77b4b22013-08-21 13:26:05 +02002584#endif /* HAVE_OPENSSL_RAND */
2585
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002586
Bill Janssen40a0f662008-08-12 16:56:25 +00002587
2588
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002589/* List of functions exported by this module. */
2590
2591static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002592 {"_test_decode_cert", PySSL_test_decode_certificate,
2593 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002594#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002595 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
2596 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02002597 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
2598 PySSL_RAND_bytes_doc},
2599 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
2600 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002601 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002602 PySSL_RAND_egd_doc},
2603 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
2604 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002605#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002606 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002607};
2608
2609
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002610#ifdef WITH_THREAD
2611
2612/* an implementation of OpenSSL threading operations in terms
2613 of the Python C thread library */
2614
2615static PyThread_type_lock *_ssl_locks = NULL;
2616
Christian Heimes4d98ca92013-08-19 17:36:29 +02002617#if OPENSSL_VERSION_NUMBER >= 0x10000000
2618/* use new CRYPTO_THREADID API. */
2619static void
2620_ssl_threadid_callback(CRYPTO_THREADID *id)
2621{
2622 CRYPTO_THREADID_set_numeric(id,
2623 (unsigned long)PyThread_get_thread_ident());
2624}
2625#else
2626/* deprecated CRYPTO_set_id_callback() API. */
2627static unsigned long
2628_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002629 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002630}
Christian Heimes4d98ca92013-08-19 17:36:29 +02002631#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002632
Bill Janssen6e027db2007-11-15 22:23:56 +00002633static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002634 (int mode, int n, const char *file, int line) {
2635 /* this function is needed to perform locking on shared data
2636 structures. (Note that OpenSSL uses a number of global data
2637 structures that will be implicitly shared whenever multiple
2638 threads use OpenSSL.) Multi-threaded applications will
2639 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002640
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002641 locking_function() must be able to handle up to
2642 CRYPTO_num_locks() different mutex locks. It sets the n-th
2643 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002644
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002645 file and line are the file number of the function setting the
2646 lock. They can be useful for debugging.
2647 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002648
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002649 if ((_ssl_locks == NULL) ||
2650 (n < 0) || ((unsigned)n >= _ssl_locks_count))
2651 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002652
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002653 if (mode & CRYPTO_LOCK) {
2654 PyThread_acquire_lock(_ssl_locks[n], 1);
2655 } else {
2656 PyThread_release_lock(_ssl_locks[n]);
2657 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002658}
2659
2660static int _setup_ssl_threads(void) {
2661
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002662 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002663
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002664 if (_ssl_locks == NULL) {
2665 _ssl_locks_count = CRYPTO_num_locks();
2666 _ssl_locks = (PyThread_type_lock *)
2667 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2668 if (_ssl_locks == NULL)
2669 return 0;
2670 memset(_ssl_locks, 0,
2671 sizeof(PyThread_type_lock) * _ssl_locks_count);
2672 for (i = 0; i < _ssl_locks_count; i++) {
2673 _ssl_locks[i] = PyThread_allocate_lock();
2674 if (_ssl_locks[i] == NULL) {
2675 unsigned int j;
2676 for (j = 0; j < i; j++) {
2677 PyThread_free_lock(_ssl_locks[j]);
2678 }
2679 free(_ssl_locks);
2680 return 0;
2681 }
2682 }
2683 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02002684#if OPENSSL_VERSION_NUMBER >= 0x10000000
2685 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
2686#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002687 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02002688#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002689 }
2690 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002691}
2692
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002693#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002694
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002695PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002696"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002697for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002698
Martin v. Löwis1a214512008-06-11 05:26:20 +00002699
2700static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002701 PyModuleDef_HEAD_INIT,
2702 "_ssl",
2703 module_doc,
2704 -1,
2705 PySSL_methods,
2706 NULL,
2707 NULL,
2708 NULL,
2709 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002710};
2711
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002712
2713static void
2714parse_openssl_version(unsigned long libver,
2715 unsigned int *major, unsigned int *minor,
2716 unsigned int *fix, unsigned int *patch,
2717 unsigned int *status)
2718{
2719 *status = libver & 0xF;
2720 libver >>= 4;
2721 *patch = libver & 0xFF;
2722 libver >>= 8;
2723 *fix = libver & 0xFF;
2724 libver >>= 8;
2725 *minor = libver & 0xFF;
2726 libver >>= 8;
2727 *major = libver & 0xFF;
2728}
2729
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002730PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002731PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002732{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002733 PyObject *m, *d, *r;
2734 unsigned long libver;
2735 unsigned int major, minor, fix, patch, status;
2736 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002737 struct py_ssl_error_code *errcode;
2738 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002739
Antoine Pitrou152efa22010-05-16 18:19:27 +00002740 if (PyType_Ready(&PySSLContext_Type) < 0)
2741 return NULL;
2742 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002743 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002744
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002745 m = PyModule_Create(&_sslmodule);
2746 if (m == NULL)
2747 return NULL;
2748 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002749
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002750 /* Load _socket module and its C API */
2751 socket_api = PySocketModule_ImportModuleAndAPI();
2752 if (!socket_api)
2753 return NULL;
2754 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002755
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002756 /* Init OpenSSL */
2757 SSL_load_error_strings();
2758 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002759#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002760 /* note that this will start threading if not already started */
2761 if (!_setup_ssl_threads()) {
2762 return NULL;
2763 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002764#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002765 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002766
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002767 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002768 sslerror_type_slots[0].pfunc = PyExc_OSError;
2769 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002770 if (PySSLErrorObject == NULL)
2771 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002772
Antoine Pitrou41032a62011-10-27 23:56:55 +02002773 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
2774 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
2775 PySSLErrorObject, NULL);
2776 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
2777 "ssl.SSLWantReadError", SSLWantReadError_doc,
2778 PySSLErrorObject, NULL);
2779 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
2780 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
2781 PySSLErrorObject, NULL);
2782 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
2783 "ssl.SSLSyscallError", SSLSyscallError_doc,
2784 PySSLErrorObject, NULL);
2785 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
2786 "ssl.SSLEOFError", SSLEOFError_doc,
2787 PySSLErrorObject, NULL);
2788 if (PySSLZeroReturnErrorObject == NULL
2789 || PySSLWantReadErrorObject == NULL
2790 || PySSLWantWriteErrorObject == NULL
2791 || PySSLSyscallErrorObject == NULL
2792 || PySSLEOFErrorObject == NULL)
2793 return NULL;
2794 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
2795 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
2796 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
2797 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
2798 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
2799 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002800 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002801 if (PyDict_SetItemString(d, "_SSLContext",
2802 (PyObject *)&PySSLContext_Type) != 0)
2803 return NULL;
2804 if (PyDict_SetItemString(d, "_SSLSocket",
2805 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002806 return NULL;
2807 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2808 PY_SSL_ERROR_ZERO_RETURN);
2809 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2810 PY_SSL_ERROR_WANT_READ);
2811 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2812 PY_SSL_ERROR_WANT_WRITE);
2813 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2814 PY_SSL_ERROR_WANT_X509_LOOKUP);
2815 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2816 PY_SSL_ERROR_SYSCALL);
2817 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2818 PY_SSL_ERROR_SSL);
2819 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2820 PY_SSL_ERROR_WANT_CONNECT);
2821 /* non ssl.h errorcodes */
2822 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2823 PY_SSL_ERROR_EOF);
2824 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2825 PY_SSL_ERROR_INVALID_ERROR_CODE);
2826 /* cert requirements */
2827 PyModule_AddIntConstant(m, "CERT_NONE",
2828 PY_SSL_CERT_NONE);
2829 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2830 PY_SSL_CERT_OPTIONAL);
2831 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2832 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002833
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002834 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02002835#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002836 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2837 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02002838#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002839 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2840 PY_SSL_VERSION_SSL3);
2841 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2842 PY_SSL_VERSION_SSL23);
2843 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2844 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002845
Antoine Pitroub5218772010-05-21 09:56:06 +00002846 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01002847 PyModule_AddIntConstant(m, "OP_ALL",
2848 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00002849 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2850 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2851 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou6db49442011-12-19 13:27:11 +01002852 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
2853 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002854 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002855#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002856 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002857#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002858#ifdef SSL_OP_NO_COMPRESSION
2859 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
2860 SSL_OP_NO_COMPRESSION);
2861#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00002862
Antoine Pitroud5323212010-10-22 18:19:07 +00002863#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2864 r = Py_True;
2865#else
2866 r = Py_False;
2867#endif
2868 Py_INCREF(r);
2869 PyModule_AddObject(m, "HAS_SNI", r);
2870
Antoine Pitroud6494802011-07-21 01:11:30 +02002871#if HAVE_OPENSSL_FINISHED
2872 r = Py_True;
2873#else
2874 r = Py_False;
2875#endif
2876 Py_INCREF(r);
2877 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
2878
Antoine Pitrou501da612011-12-21 09:27:41 +01002879#ifdef OPENSSL_NO_ECDH
2880 r = Py_False;
2881#else
2882 r = Py_True;
2883#endif
2884 Py_INCREF(r);
2885 PyModule_AddObject(m, "HAS_ECDH", r);
2886
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002887#ifdef OPENSSL_NPN_NEGOTIATED
2888 r = Py_True;
2889#else
2890 r = Py_False;
2891#endif
2892 Py_INCREF(r);
2893 PyModule_AddObject(m, "HAS_NPN", r);
2894
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002895 /* Mappings for error codes */
2896 err_codes_to_names = PyDict_New();
2897 err_names_to_codes = PyDict_New();
2898 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
2899 return NULL;
2900 errcode = error_codes;
2901 while (errcode->mnemonic != NULL) {
2902 PyObject *mnemo, *key;
2903 mnemo = PyUnicode_FromString(errcode->mnemonic);
2904 key = Py_BuildValue("ii", errcode->library, errcode->reason);
2905 if (mnemo == NULL || key == NULL)
2906 return NULL;
2907 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
2908 return NULL;
2909 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
2910 return NULL;
2911 Py_DECREF(key);
2912 Py_DECREF(mnemo);
2913 errcode++;
2914 }
2915 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
2916 return NULL;
2917 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
2918 return NULL;
2919
2920 lib_codes_to_names = PyDict_New();
2921 if (lib_codes_to_names == NULL)
2922 return NULL;
2923 libcode = library_codes;
2924 while (libcode->library != NULL) {
2925 PyObject *mnemo, *key;
2926 key = PyLong_FromLong(libcode->code);
2927 mnemo = PyUnicode_FromString(libcode->library);
2928 if (key == NULL || mnemo == NULL)
2929 return NULL;
2930 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
2931 return NULL;
2932 Py_DECREF(key);
2933 Py_DECREF(mnemo);
2934 libcode++;
2935 }
2936 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
2937 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02002938
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002939 /* OpenSSL version */
2940 /* SSLeay() gives us the version of the library linked against,
2941 which could be different from the headers version.
2942 */
2943 libver = SSLeay();
2944 r = PyLong_FromUnsignedLong(libver);
2945 if (r == NULL)
2946 return NULL;
2947 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2948 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002949 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002950 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2951 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2952 return NULL;
2953 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2954 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2955 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002956
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002957 libver = OPENSSL_VERSION_NUMBER;
2958 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
2959 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2960 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
2961 return NULL;
2962
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002963 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002964}