blob: d7554110203567bebf96b06dba7628f1c2956dee [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"
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020021#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
22 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
23#define PySSL_END_ALLOW_THREADS_S(save) \
24 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000025#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000026 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020027 PySSL_BEGIN_ALLOW_THREADS_S(_save);
28#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
29#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
30#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000031
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000032#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000033
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020034#define PySSL_BEGIN_ALLOW_THREADS_S(save)
35#define PySSL_END_ALLOW_THREADS_S(save)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000036#define PySSL_BEGIN_ALLOW_THREADS
37#define PySSL_BLOCK_THREADS
38#define PySSL_UNBLOCK_THREADS
39#define PySSL_END_ALLOW_THREADS
40
41#endif
42
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000043enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000044 /* these mirror ssl.h */
45 PY_SSL_ERROR_NONE,
46 PY_SSL_ERROR_SSL,
47 PY_SSL_ERROR_WANT_READ,
48 PY_SSL_ERROR_WANT_WRITE,
49 PY_SSL_ERROR_WANT_X509_LOOKUP,
50 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
51 PY_SSL_ERROR_ZERO_RETURN,
52 PY_SSL_ERROR_WANT_CONNECT,
53 /* start of non ssl.h errorcodes */
54 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
55 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
56 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000057};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000058
Thomas Woutersed03b412007-08-28 21:37:11 +000059enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000060 PY_SSL_CLIENT,
61 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +000062};
63
64enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000065 PY_SSL_CERT_NONE,
66 PY_SSL_CERT_OPTIONAL,
67 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +000068};
69
70enum py_ssl_version {
Victor Stinner3de49192011-05-09 00:42:58 +020071#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000072 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +020073#endif
74 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000075 PY_SSL_VERSION_SSL23,
76 PY_SSL_VERSION_TLS1
Thomas Woutersed03b412007-08-28 21:37:11 +000077};
78
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000079/* Include symbols from _socket module */
80#include "socketmodule.h"
81
Benjamin Petersonb173f782009-05-05 22:31:58 +000082static PySocketModule_APIObject PySocketModule;
83
Thomas Woutersed03b412007-08-28 21:37:11 +000084#if defined(HAVE_POLL_H)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000085#include <poll.h>
86#elif defined(HAVE_SYS_POLL_H)
87#include <sys/poll.h>
88#endif
89
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000090/* Include OpenSSL header files */
91#include "openssl/rsa.h"
92#include "openssl/crypto.h"
93#include "openssl/x509.h"
Thomas Wouters1b7f8912007-09-19 03:06:30 +000094#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000095#include "openssl/pem.h"
96#include "openssl/ssl.h"
97#include "openssl/err.h"
98#include "openssl/rand.h"
99
100/* SSL error object */
101static PyObject *PySSLErrorObject;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200102static PyObject *PySSLZeroReturnErrorObject;
103static PyObject *PySSLWantReadErrorObject;
104static PyObject *PySSLWantWriteErrorObject;
105static PyObject *PySSLSyscallErrorObject;
106static PyObject *PySSLEOFErrorObject;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000107
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000108#ifdef WITH_THREAD
109
110/* serves as a flag to see whether we've initialized the SSL thread support. */
111/* 0 means no, greater than 0 means yes */
112
113static unsigned int _ssl_locks_count = 0;
114
115#endif /* def WITH_THREAD */
116
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000117/* SSL socket object */
118
119#define X509_NAME_MAXLEN 256
120
121/* RAND_* APIs got added to OpenSSL in 0.9.5 */
122#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
123# define HAVE_OPENSSL_RAND 1
124#else
125# undef HAVE_OPENSSL_RAND
126#endif
127
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000128/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
129 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
130 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
131#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000132# define HAVE_SSL_CTX_CLEAR_OPTIONS
133#else
134# undef HAVE_SSL_CTX_CLEAR_OPTIONS
135#endif
136
Antoine Pitroud6494802011-07-21 01:11:30 +0200137/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
138 * older SSL, but let's be safe */
139#define PySSL_CB_MAXLEN 128
140
141/* SSL_get_finished got added to OpenSSL in 0.9.5 */
142#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
143# define HAVE_OPENSSL_FINISHED 1
144#else
145# define HAVE_OPENSSL_FINISHED 0
146#endif
147
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100148/* ECDH support got added to OpenSSL in 0.9.8 */
149#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
150# define OPENSSL_NO_ECDH
151#endif
152
Antoine Pitrouc135fa42012-02-19 21:22:39 +0100153/* compression support got added to OpenSSL in 0.9.8 */
154#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
155# define OPENSSL_NO_COMP
156#endif
157
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100158
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000159typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000160 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000161 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100162#ifdef OPENSSL_NPN_NEGOTIATED
163 char *npn_protocols;
164 int npn_protocols_len;
165#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000166} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000167
Antoine Pitrou152efa22010-05-16 18:19:27 +0000168typedef struct {
169 PyObject_HEAD
170 PyObject *Socket; /* weakref to socket on which we're layered */
171 SSL *ssl;
172 X509 *peer_cert;
173 int shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200174 enum py_ssl_server_or_client socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000175} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000176
Antoine Pitrou152efa22010-05-16 18:19:27 +0000177static PyTypeObject PySSLContext_Type;
178static PyTypeObject PySSLSocket_Type;
179
180static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
181static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000182static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000183 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000184static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
185static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000186
Antoine Pitrou152efa22010-05-16 18:19:27 +0000187#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
188#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000189
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000190typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000191 SOCKET_IS_NONBLOCKING,
192 SOCKET_IS_BLOCKING,
193 SOCKET_HAS_TIMED_OUT,
194 SOCKET_HAS_BEEN_CLOSED,
195 SOCKET_TOO_LARGE_FOR_SELECT,
196 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000197} timeout_state;
198
Thomas Woutersed03b412007-08-28 21:37:11 +0000199/* Wrap error strings with filename and line # */
200#define STRINGIFY1(x) #x
201#define STRINGIFY2(x) STRINGIFY1(x)
202#define ERRSTR1(x,y,z) (x ":" y ": " z)
203#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
204
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000205/* XXX It might be helpful to augment the error message generated
206 below with the name of the SSL function that generated the error.
207 I expect it's obvious most of the time.
208*/
209
210static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000211PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000212{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000213 PyObject *v;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200214 PyObject *type = PySSLErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000215 char buf[2048];
216 char *errstr;
217 int err;
218 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000219
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000220 assert(ret <= 0);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000221
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000222 if (obj->ssl != NULL) {
223 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000224
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000225 switch (err) {
226 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200227 errstr = "TLS/SSL connection has been closed (EOF)";
228 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000229 p = PY_SSL_ERROR_ZERO_RETURN;
230 break;
231 case SSL_ERROR_WANT_READ:
232 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200233 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000234 p = PY_SSL_ERROR_WANT_READ;
235 break;
236 case SSL_ERROR_WANT_WRITE:
237 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200238 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000239 errstr = "The operation did not complete (write)";
240 break;
241 case SSL_ERROR_WANT_X509_LOOKUP:
242 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000243 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000244 break;
245 case SSL_ERROR_WANT_CONNECT:
246 p = PY_SSL_ERROR_WANT_CONNECT;
247 errstr = "The operation did not complete (connect)";
248 break;
249 case SSL_ERROR_SYSCALL:
250 {
251 unsigned long e = ERR_get_error();
252 if (e == 0) {
253 PySocketSockObject *s
254 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
255 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000256 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200257 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000258 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000259 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000260 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000261 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000262 ERR_clear_error();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000263 v = s->errorhandler();
264 Py_DECREF(s);
265 return v;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000266 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000267 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200268 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000269 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000270 }
271 } else {
272 p = PY_SSL_ERROR_SYSCALL;
273 /* XXX Protected by global interpreter lock */
274 errstr = ERR_error_string(e, NULL);
275 }
276 break;
277 }
278 case SSL_ERROR_SSL:
279 {
280 unsigned long e = ERR_get_error();
281 p = PY_SSL_ERROR_SSL;
282 if (e != 0)
283 /* XXX Protected by global interpreter lock */
284 errstr = ERR_error_string(e, NULL);
285 else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000286 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000287 }
288 break;
289 }
290 default:
291 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
292 errstr = "Invalid error code";
293 }
294 } else {
295 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
296 }
297 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000298 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000299 v = Py_BuildValue("(is)", p, buf);
300 if (v != NULL) {
Antoine Pitrou41032a62011-10-27 23:56:55 +0200301 PyErr_SetObject(type, v);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000302 Py_DECREF(v);
303 }
304 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000305}
306
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000307static PyObject *
308_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
309
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000310 char buf[2048];
311 PyObject *v;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000312
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000313 if (errstr == NULL) {
314 errcode = ERR_peek_last_error();
315 errstr = ERR_error_string(errcode, NULL);
316 }
317 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000318 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000319 v = Py_BuildValue("(is)", errcode, buf);
320 if (v != NULL) {
321 PyErr_SetObject(PySSLErrorObject, v);
322 Py_DECREF(v);
323 }
324 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000325}
326
Antoine Pitrou152efa22010-05-16 18:19:27 +0000327static PySSLSocket *
328newPySSLSocket(SSL_CTX *ctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000329 enum py_ssl_server_or_client socket_type,
330 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000331{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000332 PySSLSocket *self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000333
Antoine Pitrou152efa22010-05-16 18:19:27 +0000334 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000335 if (self == NULL)
336 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000337
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000338 self->peer_cert = NULL;
339 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000340 self->Socket = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000341
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000342 /* Make sure the SSL error state is initialized */
343 (void) ERR_get_state();
344 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000345
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000346 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000347 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000348 PySSL_END_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000349 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000350#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000351 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000352#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000353
Antoine Pitroud5323212010-10-22 18:19:07 +0000354#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
355 if (server_hostname != NULL)
356 SSL_set_tlsext_host_name(self->ssl, server_hostname);
357#endif
358
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000359 /* If the socket is in non-blocking mode or timeout mode, set the BIO
360 * to non-blocking mode (blocking is the default)
361 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000362 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000363 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
364 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
365 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000366
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000367 PySSL_BEGIN_ALLOW_THREADS
368 if (socket_type == PY_SSL_CLIENT)
369 SSL_set_connect_state(self->ssl);
370 else
371 SSL_set_accept_state(self->ssl);
372 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000373
Antoine Pitroud6494802011-07-21 01:11:30 +0200374 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000375 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000376 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000377}
378
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000379/* SSL object methods */
380
Antoine Pitrou152efa22010-05-16 18:19:27 +0000381static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000382{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000383 int ret;
384 int err;
385 int sockstate, nonblocking;
386 PySocketSockObject *sock
387 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000388
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000389 if (((PyObject*)sock) == Py_None) {
390 _setSSLError("Underlying socket connection gone",
391 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
392 return NULL;
393 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000394 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000395
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000396 /* just in case the blocking state of the socket has been changed */
397 nonblocking = (sock->sock_timeout >= 0.0);
398 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
399 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000400
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000401 /* Actually negotiate SSL connection */
402 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000403 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000404 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000405 ret = SSL_do_handshake(self->ssl);
406 err = SSL_get_error(self->ssl, ret);
407 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000408 if (PyErr_CheckSignals())
409 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000410 if (err == SSL_ERROR_WANT_READ) {
411 sockstate = check_socket_and_wait_for_timeout(sock, 0);
412 } else if (err == SSL_ERROR_WANT_WRITE) {
413 sockstate = check_socket_and_wait_for_timeout(sock, 1);
414 } else {
415 sockstate = SOCKET_OPERATION_OK;
416 }
417 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000418 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000419 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000420 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000421 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
422 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000423 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000424 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000425 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
426 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000427 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000428 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000429 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
430 break;
431 }
432 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000433 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000434 if (ret < 1)
435 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000436
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000437 if (self->peer_cert)
438 X509_free (self->peer_cert);
439 PySSL_BEGIN_ALLOW_THREADS
440 self->peer_cert = SSL_get_peer_certificate(self->ssl);
441 PySSL_END_ALLOW_THREADS
442
443 Py_INCREF(Py_None);
444 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000445
446error:
447 Py_DECREF(sock);
448 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000449}
450
Thomas Woutersed03b412007-08-28 21:37:11 +0000451static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000452_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000453
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000454 char namebuf[X509_NAME_MAXLEN];
455 int buflen;
456 PyObject *name_obj;
457 PyObject *value_obj;
458 PyObject *attr;
459 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000460
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000461 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
462 if (buflen < 0) {
463 _setSSLError(NULL, 0, __FILE__, __LINE__);
464 goto fail;
465 }
466 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
467 if (name_obj == NULL)
468 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000469
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000470 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
471 if (buflen < 0) {
472 _setSSLError(NULL, 0, __FILE__, __LINE__);
473 Py_DECREF(name_obj);
474 goto fail;
475 }
476 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000477 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000478 OPENSSL_free(valuebuf);
479 if (value_obj == NULL) {
480 Py_DECREF(name_obj);
481 goto fail;
482 }
483 attr = PyTuple_New(2);
484 if (attr == NULL) {
485 Py_DECREF(name_obj);
486 Py_DECREF(value_obj);
487 goto fail;
488 }
489 PyTuple_SET_ITEM(attr, 0, name_obj);
490 PyTuple_SET_ITEM(attr, 1, value_obj);
491 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000492
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000493 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000494 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000495}
496
497static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000498_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000499{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000500 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
501 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
502 PyObject *rdnt;
503 PyObject *attr = NULL; /* tuple to hold an attribute */
504 int entry_count = X509_NAME_entry_count(xname);
505 X509_NAME_ENTRY *entry;
506 ASN1_OBJECT *name;
507 ASN1_STRING *value;
508 int index_counter;
509 int rdn_level = -1;
510 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000511
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000512 dn = PyList_New(0);
513 if (dn == NULL)
514 return NULL;
515 /* now create another tuple to hold the top-level RDN */
516 rdn = PyList_New(0);
517 if (rdn == NULL)
518 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000519
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000520 for (index_counter = 0;
521 index_counter < entry_count;
522 index_counter++)
523 {
524 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000525
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000526 /* check to see if we've gotten to a new RDN */
527 if (rdn_level >= 0) {
528 if (rdn_level != entry->set) {
529 /* yes, new RDN */
530 /* add old RDN to DN */
531 rdnt = PyList_AsTuple(rdn);
532 Py_DECREF(rdn);
533 if (rdnt == NULL)
534 goto fail0;
535 retcode = PyList_Append(dn, rdnt);
536 Py_DECREF(rdnt);
537 if (retcode < 0)
538 goto fail0;
539 /* create new RDN */
540 rdn = PyList_New(0);
541 if (rdn == NULL)
542 goto fail0;
543 }
544 }
545 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000546
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000547 /* now add this attribute to the current RDN */
548 name = X509_NAME_ENTRY_get_object(entry);
549 value = X509_NAME_ENTRY_get_data(entry);
550 attr = _create_tuple_for_attribute(name, value);
551 /*
552 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
553 entry->set,
554 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
555 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
556 */
557 if (attr == NULL)
558 goto fail1;
559 retcode = PyList_Append(rdn, attr);
560 Py_DECREF(attr);
561 if (retcode < 0)
562 goto fail1;
563 }
564 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100565 if (rdn != NULL) {
566 if (PyList_GET_SIZE(rdn) > 0) {
567 rdnt = PyList_AsTuple(rdn);
568 Py_DECREF(rdn);
569 if (rdnt == NULL)
570 goto fail0;
571 retcode = PyList_Append(dn, rdnt);
572 Py_DECREF(rdnt);
573 if (retcode < 0)
574 goto fail0;
575 }
576 else {
577 Py_DECREF(rdn);
578 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000579 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000580
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000581 /* convert list to tuple */
582 rdnt = PyList_AsTuple(dn);
583 Py_DECREF(dn);
584 if (rdnt == NULL)
585 return NULL;
586 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000587
588 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000589 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000590
591 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000592 Py_XDECREF(dn);
593 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000594}
595
596static PyObject *
597_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000598
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000599 /* this code follows the procedure outlined in
600 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
601 function to extract the STACK_OF(GENERAL_NAME),
602 then iterates through the stack to add the
603 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000604
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000605 int i, j;
606 PyObject *peer_alt_names = Py_None;
607 PyObject *v, *t;
608 X509_EXTENSION *ext = NULL;
609 GENERAL_NAMES *names = NULL;
610 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000611 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000612 BIO *biobuf = NULL;
613 char buf[2048];
614 char *vptr;
615 int len;
616 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000617#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000618 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000619#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000620 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000621#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000622
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000623 if (certificate == NULL)
624 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000625
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000626 /* get a memory buffer */
627 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000628
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200629 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000630 while ((i = X509_get_ext_by_NID(
631 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000632
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000633 if (peer_alt_names == Py_None) {
634 peer_alt_names = PyList_New(0);
635 if (peer_alt_names == NULL)
636 goto fail;
637 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000638
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000639 /* now decode the altName */
640 ext = X509_get_ext(certificate, i);
641 if(!(method = X509V3_EXT_get(ext))) {
642 PyErr_SetString
643 (PySSLErrorObject,
644 ERRSTR("No method for internalizing subjectAltName!"));
645 goto fail;
646 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000647
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000648 p = ext->value->data;
649 if (method->it)
650 names = (GENERAL_NAMES*)
651 (ASN1_item_d2i(NULL,
652 &p,
653 ext->value->length,
654 ASN1_ITEM_ptr(method->it)));
655 else
656 names = (GENERAL_NAMES*)
657 (method->d2i(NULL,
658 &p,
659 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000660
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000661 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000662
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000663 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000664
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000665 name = sk_GENERAL_NAME_value(names, j);
666 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000667
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000668 /* we special-case DirName as a tuple of
669 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000670
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000671 t = PyTuple_New(2);
672 if (t == NULL) {
673 goto fail;
674 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000675
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000676 v = PyUnicode_FromString("DirName");
677 if (v == NULL) {
678 Py_DECREF(t);
679 goto fail;
680 }
681 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000682
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000683 v = _create_tuple_for_X509_NAME (name->d.dirn);
684 if (v == NULL) {
685 Py_DECREF(t);
686 goto fail;
687 }
688 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000689
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000690 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000691
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000692 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000693
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000694 (void) BIO_reset(biobuf);
695 GENERAL_NAME_print(biobuf, name);
696 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
697 if (len < 0) {
698 _setSSLError(NULL, 0, __FILE__, __LINE__);
699 goto fail;
700 }
701 vptr = strchr(buf, ':');
702 if (vptr == NULL)
703 goto fail;
704 t = PyTuple_New(2);
705 if (t == NULL)
706 goto fail;
707 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
708 if (v == NULL) {
709 Py_DECREF(t);
710 goto fail;
711 }
712 PyTuple_SET_ITEM(t, 0, v);
713 v = PyUnicode_FromStringAndSize((vptr + 1),
714 (len - (vptr - buf + 1)));
715 if (v == NULL) {
716 Py_DECREF(t);
717 goto fail;
718 }
719 PyTuple_SET_ITEM(t, 1, v);
720 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000721
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000722 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000723
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000724 if (PyList_Append(peer_alt_names, t) < 0) {
725 Py_DECREF(t);
726 goto fail;
727 }
728 Py_DECREF(t);
729 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100730 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000731 }
732 BIO_free(biobuf);
733 if (peer_alt_names != Py_None) {
734 v = PyList_AsTuple(peer_alt_names);
735 Py_DECREF(peer_alt_names);
736 return v;
737 } else {
738 return peer_alt_names;
739 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000740
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000741
742 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000743 if (biobuf != NULL)
744 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000745
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000746 if (peer_alt_names != Py_None) {
747 Py_XDECREF(peer_alt_names);
748 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000749
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000750 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000751}
752
753static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000754_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000755
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000756 PyObject *retval = NULL;
757 BIO *biobuf = NULL;
758 PyObject *peer;
759 PyObject *peer_alt_names = NULL;
760 PyObject *issuer;
761 PyObject *version;
762 PyObject *sn_obj;
763 ASN1_INTEGER *serialNumber;
764 char buf[2048];
765 int len;
766 ASN1_TIME *notBefore, *notAfter;
767 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000768
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000769 retval = PyDict_New();
770 if (retval == NULL)
771 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000772
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000773 peer = _create_tuple_for_X509_NAME(
774 X509_get_subject_name(certificate));
775 if (peer == NULL)
776 goto fail0;
777 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
778 Py_DECREF(peer);
779 goto fail0;
780 }
781 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000782
Antoine Pitroufb046912010-11-09 20:21:19 +0000783 issuer = _create_tuple_for_X509_NAME(
784 X509_get_issuer_name(certificate));
785 if (issuer == NULL)
786 goto fail0;
787 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000788 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000789 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000790 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000791 Py_DECREF(issuer);
792
793 version = PyLong_FromLong(X509_get_version(certificate) + 1);
794 if (PyDict_SetItemString(retval, "version", version) < 0) {
795 Py_DECREF(version);
796 goto fail0;
797 }
798 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000799
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000800 /* get a memory buffer */
801 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000802
Antoine Pitroufb046912010-11-09 20:21:19 +0000803 (void) BIO_reset(biobuf);
804 serialNumber = X509_get_serialNumber(certificate);
805 /* should not exceed 20 octets, 160 bits, so buf is big enough */
806 i2a_ASN1_INTEGER(biobuf, serialNumber);
807 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
808 if (len < 0) {
809 _setSSLError(NULL, 0, __FILE__, __LINE__);
810 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000811 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000812 sn_obj = PyUnicode_FromStringAndSize(buf, len);
813 if (sn_obj == NULL)
814 goto fail1;
815 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
816 Py_DECREF(sn_obj);
817 goto fail1;
818 }
819 Py_DECREF(sn_obj);
820
821 (void) BIO_reset(biobuf);
822 notBefore = X509_get_notBefore(certificate);
823 ASN1_TIME_print(biobuf, notBefore);
824 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
825 if (len < 0) {
826 _setSSLError(NULL, 0, __FILE__, __LINE__);
827 goto fail1;
828 }
829 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
830 if (pnotBefore == NULL)
831 goto fail1;
832 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
833 Py_DECREF(pnotBefore);
834 goto fail1;
835 }
836 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000837
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000838 (void) BIO_reset(biobuf);
839 notAfter = X509_get_notAfter(certificate);
840 ASN1_TIME_print(biobuf, notAfter);
841 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
842 if (len < 0) {
843 _setSSLError(NULL, 0, __FILE__, __LINE__);
844 goto fail1;
845 }
846 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
847 if (pnotAfter == NULL)
848 goto fail1;
849 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
850 Py_DECREF(pnotAfter);
851 goto fail1;
852 }
853 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000854
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000855 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000856
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000857 peer_alt_names = _get_peer_alt_names(certificate);
858 if (peer_alt_names == NULL)
859 goto fail1;
860 else if (peer_alt_names != Py_None) {
861 if (PyDict_SetItemString(retval, "subjectAltName",
862 peer_alt_names) < 0) {
863 Py_DECREF(peer_alt_names);
864 goto fail1;
865 }
866 Py_DECREF(peer_alt_names);
867 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000868
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000869 BIO_free(biobuf);
870 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000871
872 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000873 if (biobuf != NULL)
874 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000875 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000876 Py_XDECREF(retval);
877 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000878}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000879
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000880
881static PyObject *
882PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
883
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000884 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +0000885 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000886 X509 *x=NULL;
887 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000888
Antoine Pitroufb046912010-11-09 20:21:19 +0000889 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
890 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000891 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000892
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000893 if ((cert=BIO_new(BIO_s_file())) == NULL) {
894 PyErr_SetString(PySSLErrorObject,
895 "Can't malloc memory to read file");
896 goto fail0;
897 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000898
Victor Stinner3800e1e2010-05-16 21:23:48 +0000899 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000900 PyErr_SetString(PySSLErrorObject,
901 "Can't open file");
902 goto fail0;
903 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000904
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000905 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
906 if (x == NULL) {
907 PyErr_SetString(PySSLErrorObject,
908 "Error decoding PEM-encoded file");
909 goto fail0;
910 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000911
Antoine Pitroufb046912010-11-09 20:21:19 +0000912 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +0000913 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000914
915 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +0000916 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000917 if (cert != NULL) BIO_free(cert);
918 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000919}
920
921
922static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000923PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000924{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000925 PyObject *retval = NULL;
926 int len;
927 int verification;
928 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000929
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000930 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
931 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000932
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000933 if (!self->peer_cert)
934 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000935
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000936 if (PyObject_IsTrue(binary_mode)) {
937 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000938
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000939 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000940
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000941 bytes_buf = NULL;
942 len = i2d_X509(self->peer_cert, &bytes_buf);
943 if (len < 0) {
944 PySSL_SetError(self, len, __FILE__, __LINE__);
945 return NULL;
946 }
947 /* this is actually an immutable bytes sequence */
948 retval = PyBytes_FromStringAndSize
949 ((const char *) bytes_buf, len);
950 OPENSSL_free(bytes_buf);
951 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000952
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000953 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000954 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000955 if ((verification & SSL_VERIFY_PEER) == 0)
956 return PyDict_New();
957 else
Antoine Pitroufb046912010-11-09 20:21:19 +0000958 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000959 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000960}
961
962PyDoc_STRVAR(PySSL_peercert_doc,
963"peer_certificate([der=False]) -> certificate\n\
964\n\
965Returns the certificate for the peer. If no certificate was provided,\n\
966returns None. If a certificate was provided, but not validated, returns\n\
967an empty dictionary. Otherwise returns a dict containing information\n\
968about the peer certificate.\n\
969\n\
970If the optional argument is True, returns a DER-encoded copy of the\n\
971peer certificate, or None if no certificate was provided. This will\n\
972return the certificate even if it wasn't validated.");
973
Antoine Pitrou152efa22010-05-16 18:19:27 +0000974static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000975
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000976 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000977 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000978 char *cipher_name;
979 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000980
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000981 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000982 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000983 current = SSL_get_current_cipher(self->ssl);
984 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000985 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000986
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000987 retval = PyTuple_New(3);
988 if (retval == NULL)
989 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000990
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000991 cipher_name = (char *) SSL_CIPHER_get_name(current);
992 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000993 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000994 PyTuple_SET_ITEM(retval, 0, Py_None);
995 } else {
996 v = PyUnicode_FromString(cipher_name);
997 if (v == NULL)
998 goto fail0;
999 PyTuple_SET_ITEM(retval, 0, v);
1000 }
1001 cipher_protocol = SSL_CIPHER_get_version(current);
1002 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001003 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001004 PyTuple_SET_ITEM(retval, 1, Py_None);
1005 } else {
1006 v = PyUnicode_FromString(cipher_protocol);
1007 if (v == NULL)
1008 goto fail0;
1009 PyTuple_SET_ITEM(retval, 1, v);
1010 }
1011 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1012 if (v == NULL)
1013 goto fail0;
1014 PyTuple_SET_ITEM(retval, 2, v);
1015 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001016
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001017 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001018 Py_DECREF(retval);
1019 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001020}
1021
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001022#ifdef OPENSSL_NPN_NEGOTIATED
1023static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1024 const unsigned char *out;
1025 unsigned int outlen;
1026
1027 SSL_get0_next_proto_negotiated(self->ssl,
1028 &out, &outlen);
1029
1030 if (out == NULL)
1031 Py_RETURN_NONE;
1032 return PyUnicode_FromStringAndSize((char *) out, outlen);
1033}
1034#endif
1035
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001036static PyObject *PySSL_compression(PySSLSocket *self) {
1037#ifdef OPENSSL_NO_COMP
1038 Py_RETURN_NONE;
1039#else
1040 const COMP_METHOD *comp_method;
1041 const char *short_name;
1042
1043 if (self->ssl == NULL)
1044 Py_RETURN_NONE;
1045 comp_method = SSL_get_current_compression(self->ssl);
1046 if (comp_method == NULL || comp_method->type == NID_undef)
1047 Py_RETURN_NONE;
1048 short_name = OBJ_nid2sn(comp_method->type);
1049 if (short_name == NULL)
1050 Py_RETURN_NONE;
1051 return PyUnicode_DecodeFSDefault(short_name);
1052#endif
1053}
1054
Antoine Pitrou152efa22010-05-16 18:19:27 +00001055static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001056{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 if (self->peer_cert) /* Possible not to have one? */
1058 X509_free (self->peer_cert);
1059 if (self->ssl)
1060 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001061 Py_XDECREF(self->Socket);
1062 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001063}
1064
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001065/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001066 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001067 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001068 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001069
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001070static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001071check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001072{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001073 fd_set fds;
1074 struct timeval tv;
1075 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001076
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001077 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1078 if (s->sock_timeout < 0.0)
1079 return SOCKET_IS_BLOCKING;
1080 else if (s->sock_timeout == 0.0)
1081 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001082
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001083 /* Guard against closed socket */
1084 if (s->sock_fd < 0)
1085 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001086
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001087 /* Prefer poll, if available, since you can poll() any fd
1088 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001089#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001090 {
1091 struct pollfd pollfd;
1092 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001093
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001094 pollfd.fd = s->sock_fd;
1095 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001096
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001097 /* s->sock_timeout is in seconds, timeout in ms */
1098 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1099 PySSL_BEGIN_ALLOW_THREADS
1100 rc = poll(&pollfd, 1, timeout);
1101 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001102
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001103 goto normal_return;
1104 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001105#endif
1106
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001107 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001108 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001109 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001110
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 /* Construct the arguments to select */
1112 tv.tv_sec = (int)s->sock_timeout;
1113 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1114 FD_ZERO(&fds);
1115 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001116
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001117 /* See if the socket is ready */
1118 PySSL_BEGIN_ALLOW_THREADS
1119 if (writing)
1120 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1121 else
1122 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1123 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001124
Bill Janssen6e027db2007-11-15 22:23:56 +00001125#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001126normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001127#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001128 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1129 (when we are able to write or when there's something to read) */
1130 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001131}
1132
Antoine Pitrou152efa22010-05-16 18:19:27 +00001133static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001134{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001135 Py_buffer buf;
1136 int len;
1137 int sockstate;
1138 int err;
1139 int nonblocking;
1140 PySocketSockObject *sock
1141 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001142
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001143 if (((PyObject*)sock) == Py_None) {
1144 _setSSLError("Underlying socket connection gone",
1145 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1146 return NULL;
1147 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001148 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001149
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001150 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1151 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001152 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001153 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001154
1155 /* just in case the blocking state of the socket has been changed */
1156 nonblocking = (sock->sock_timeout >= 0.0);
1157 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1158 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1159
1160 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1161 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001162 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001163 "The write operation timed out");
1164 goto error;
1165 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1166 PyErr_SetString(PySSLErrorObject,
1167 "Underlying socket has been closed.");
1168 goto error;
1169 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1170 PyErr_SetString(PySSLErrorObject,
1171 "Underlying socket too large for select().");
1172 goto error;
1173 }
1174 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001175 PySSL_BEGIN_ALLOW_THREADS
1176 len = SSL_write(self->ssl, buf.buf, buf.len);
1177 err = SSL_get_error(self->ssl, len);
1178 PySSL_END_ALLOW_THREADS
1179 if (PyErr_CheckSignals()) {
1180 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001181 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001182 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001183 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001184 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001185 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001186 } else {
1187 sockstate = SOCKET_OPERATION_OK;
1188 }
1189 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001190 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001191 "The write operation timed out");
1192 goto error;
1193 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1194 PyErr_SetString(PySSLErrorObject,
1195 "Underlying socket has been closed.");
1196 goto error;
1197 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1198 break;
1199 }
1200 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001201
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001202 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001203 PyBuffer_Release(&buf);
1204 if (len > 0)
1205 return PyLong_FromLong(len);
1206 else
1207 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001208
1209error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001210 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001211 PyBuffer_Release(&buf);
1212 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001213}
1214
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001215PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001216"write(s) -> len\n\
1217\n\
1218Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001219of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001220
Antoine Pitrou152efa22010-05-16 18:19:27 +00001221static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001222{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001223 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001224
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001225 PySSL_BEGIN_ALLOW_THREADS
1226 count = SSL_pending(self->ssl);
1227 PySSL_END_ALLOW_THREADS
1228 if (count < 0)
1229 return PySSL_SetError(self, count, __FILE__, __LINE__);
1230 else
1231 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001232}
1233
1234PyDoc_STRVAR(PySSL_SSLpending_doc,
1235"pending() -> count\n\
1236\n\
1237Returns the number of already decrypted bytes available for read,\n\
1238pending on the connection.\n");
1239
Antoine Pitrou152efa22010-05-16 18:19:27 +00001240static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001241{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001242 PyObject *dest = NULL;
1243 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001244 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001245 int len, count;
1246 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001247 int sockstate;
1248 int err;
1249 int nonblocking;
1250 PySocketSockObject *sock
1251 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001252
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001253 if (((PyObject*)sock) == Py_None) {
1254 _setSSLError("Underlying socket connection gone",
1255 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1256 return NULL;
1257 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001258 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001259
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001260 buf.obj = NULL;
1261 buf.buf = NULL;
1262 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001263 goto error;
1264
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001265 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1266 dest = PyBytes_FromStringAndSize(NULL, len);
1267 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001268 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001269 mem = PyBytes_AS_STRING(dest);
1270 }
1271 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001272 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001273 mem = buf.buf;
1274 if (len <= 0 || len > buf.len) {
1275 len = (int) buf.len;
1276 if (buf.len != len) {
1277 PyErr_SetString(PyExc_OverflowError,
1278 "maximum length can't fit in a C 'int'");
1279 goto error;
1280 }
1281 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001282 }
1283
1284 /* just in case the blocking state of the socket has been changed */
1285 nonblocking = (sock->sock_timeout >= 0.0);
1286 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1287 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1288
1289 /* first check if there are bytes ready to be read */
1290 PySSL_BEGIN_ALLOW_THREADS
1291 count = SSL_pending(self->ssl);
1292 PySSL_END_ALLOW_THREADS
1293
1294 if (!count) {
1295 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1296 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001297 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001298 "The read operation timed out");
1299 goto error;
1300 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1301 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001302 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001303 goto error;
1304 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1305 count = 0;
1306 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001307 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001308 }
1309 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001310 PySSL_BEGIN_ALLOW_THREADS
1311 count = SSL_read(self->ssl, mem, len);
1312 err = SSL_get_error(self->ssl, count);
1313 PySSL_END_ALLOW_THREADS
1314 if (PyErr_CheckSignals())
1315 goto error;
1316 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001317 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001318 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001319 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001320 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1321 (SSL_get_shutdown(self->ssl) ==
1322 SSL_RECEIVED_SHUTDOWN))
1323 {
1324 count = 0;
1325 goto done;
1326 } else {
1327 sockstate = SOCKET_OPERATION_OK;
1328 }
1329 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001330 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001331 "The read operation timed out");
1332 goto error;
1333 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1334 break;
1335 }
1336 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1337 if (count <= 0) {
1338 PySSL_SetError(self, count, __FILE__, __LINE__);
1339 goto error;
1340 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001341
1342done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001343 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001344 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001345 _PyBytes_Resize(&dest, count);
1346 return dest;
1347 }
1348 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001349 PyBuffer_Release(&buf);
1350 return PyLong_FromLong(count);
1351 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001352
1353error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001354 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001355 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001356 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001357 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001358 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001359 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001360}
1361
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001362PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001363"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001364\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001365Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001366
Antoine Pitrou152efa22010-05-16 18:19:27 +00001367static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001368{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001369 int err, ssl_err, sockstate, nonblocking;
1370 int zeros = 0;
1371 PySocketSockObject *sock
1372 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001373
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001374 /* Guard against closed socket */
1375 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1376 _setSSLError("Underlying socket connection gone",
1377 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1378 return NULL;
1379 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001380 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001381
1382 /* Just in case the blocking state of the socket has been changed */
1383 nonblocking = (sock->sock_timeout >= 0.0);
1384 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1385 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1386
1387 while (1) {
1388 PySSL_BEGIN_ALLOW_THREADS
1389 /* Disable read-ahead so that unwrap can work correctly.
1390 * Otherwise OpenSSL might read in too much data,
1391 * eating clear text data that happens to be
1392 * transmitted after the SSL shutdown.
1393 * Should be safe to call repeatedly everytime this
1394 * function is used and the shutdown_seen_zero != 0
1395 * condition is met.
1396 */
1397 if (self->shutdown_seen_zero)
1398 SSL_set_read_ahead(self->ssl, 0);
1399 err = SSL_shutdown(self->ssl);
1400 PySSL_END_ALLOW_THREADS
1401 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1402 if (err > 0)
1403 break;
1404 if (err == 0) {
1405 /* Don't loop endlessly; instead preserve legacy
1406 behaviour of trying SSL_shutdown() only twice.
1407 This looks necessary for OpenSSL < 0.9.8m */
1408 if (++zeros > 1)
1409 break;
1410 /* Shutdown was sent, now try receiving */
1411 self->shutdown_seen_zero = 1;
1412 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001413 }
1414
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001415 /* Possibly retry shutdown until timeout or failure */
1416 ssl_err = SSL_get_error(self->ssl, err);
1417 if (ssl_err == SSL_ERROR_WANT_READ)
1418 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1419 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1420 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1421 else
1422 break;
1423 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1424 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001425 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001426 "The read operation timed out");
1427 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001428 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001429 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001430 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001431 }
1432 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1433 PyErr_SetString(PySSLErrorObject,
1434 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001435 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001436 }
1437 else if (sockstate != SOCKET_OPERATION_OK)
1438 /* Retain the SSL error code */
1439 break;
1440 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001441
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001442 if (err < 0) {
1443 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001444 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001445 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001446 else
1447 /* It's already INCREF'ed */
1448 return (PyObject *) sock;
1449
1450error:
1451 Py_DECREF(sock);
1452 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001453}
1454
1455PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1456"shutdown(s) -> socket\n\
1457\n\
1458Does the SSL shutdown handshake with the remote end, and returns\n\
1459the underlying socket object.");
1460
Antoine Pitroud6494802011-07-21 01:11:30 +02001461#if HAVE_OPENSSL_FINISHED
1462static PyObject *
1463PySSL_tls_unique_cb(PySSLSocket *self)
1464{
1465 PyObject *retval = NULL;
1466 char buf[PySSL_CB_MAXLEN];
1467 int len;
1468
1469 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1470 /* if session is resumed XOR we are the client */
1471 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1472 }
1473 else {
1474 /* if a new session XOR we are the server */
1475 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1476 }
1477
1478 /* It cannot be negative in current OpenSSL version as of July 2011 */
1479 assert(len >= 0);
1480 if (len == 0)
1481 Py_RETURN_NONE;
1482
1483 retval = PyBytes_FromStringAndSize(buf, len);
1484
1485 return retval;
1486}
1487
1488PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1489"tls_unique_cb() -> bytes\n\
1490\n\
1491Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1492\n\
1493If the TLS handshake is not yet complete, None is returned");
1494
1495#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001496
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001497static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001498 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1499 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1500 PySSL_SSLwrite_doc},
1501 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1502 PySSL_SSLread_doc},
1503 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1504 PySSL_SSLpending_doc},
1505 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1506 PySSL_peercert_doc},
1507 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001508#ifdef OPENSSL_NPN_NEGOTIATED
1509 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1510#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001511 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001512 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1513 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001514#if HAVE_OPENSSL_FINISHED
1515 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1516 PySSL_tls_unique_cb_doc},
1517#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001518 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001519};
1520
Antoine Pitrou152efa22010-05-16 18:19:27 +00001521static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001522 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001523 "_ssl._SSLSocket", /*tp_name*/
1524 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001525 0, /*tp_itemsize*/
1526 /* methods */
1527 (destructor)PySSL_dealloc, /*tp_dealloc*/
1528 0, /*tp_print*/
1529 0, /*tp_getattr*/
1530 0, /*tp_setattr*/
1531 0, /*tp_reserved*/
1532 0, /*tp_repr*/
1533 0, /*tp_as_number*/
1534 0, /*tp_as_sequence*/
1535 0, /*tp_as_mapping*/
1536 0, /*tp_hash*/
1537 0, /*tp_call*/
1538 0, /*tp_str*/
1539 0, /*tp_getattro*/
1540 0, /*tp_setattro*/
1541 0, /*tp_as_buffer*/
1542 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1543 0, /*tp_doc*/
1544 0, /*tp_traverse*/
1545 0, /*tp_clear*/
1546 0, /*tp_richcompare*/
1547 0, /*tp_weaklistoffset*/
1548 0, /*tp_iter*/
1549 0, /*tp_iternext*/
1550 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001551};
1552
Antoine Pitrou152efa22010-05-16 18:19:27 +00001553
1554/*
1555 * _SSLContext objects
1556 */
1557
1558static PyObject *
1559context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1560{
1561 char *kwlist[] = {"protocol", NULL};
1562 PySSLContext *self;
1563 int proto_version = PY_SSL_VERSION_SSL23;
1564 SSL_CTX *ctx = NULL;
1565
1566 if (!PyArg_ParseTupleAndKeywords(
1567 args, kwds, "i:_SSLContext", kwlist,
1568 &proto_version))
1569 return NULL;
1570
1571 PySSL_BEGIN_ALLOW_THREADS
1572 if (proto_version == PY_SSL_VERSION_TLS1)
1573 ctx = SSL_CTX_new(TLSv1_method());
1574 else if (proto_version == PY_SSL_VERSION_SSL3)
1575 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001576#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001577 else if (proto_version == PY_SSL_VERSION_SSL2)
1578 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001579#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001580 else if (proto_version == PY_SSL_VERSION_SSL23)
1581 ctx = SSL_CTX_new(SSLv23_method());
1582 else
1583 proto_version = -1;
1584 PySSL_END_ALLOW_THREADS
1585
1586 if (proto_version == -1) {
1587 PyErr_SetString(PyExc_ValueError,
1588 "invalid protocol version");
1589 return NULL;
1590 }
1591 if (ctx == NULL) {
1592 PyErr_SetString(PySSLErrorObject,
1593 "failed to allocate SSL context");
1594 return NULL;
1595 }
1596
1597 assert(type != NULL && type->tp_alloc != NULL);
1598 self = (PySSLContext *) type->tp_alloc(type, 0);
1599 if (self == NULL) {
1600 SSL_CTX_free(ctx);
1601 return NULL;
1602 }
1603 self->ctx = ctx;
1604 /* Defaults */
1605 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001606 SSL_CTX_set_options(self->ctx,
1607 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001608
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001609#define SID_CTX "Python"
1610 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1611 sizeof(SID_CTX));
1612#undef SID_CTX
1613
Antoine Pitrou152efa22010-05-16 18:19:27 +00001614 return (PyObject *)self;
1615}
1616
1617static void
1618context_dealloc(PySSLContext *self)
1619{
1620 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001621#ifdef OPENSSL_NPN_NEGOTIATED
1622 PyMem_Free(self->npn_protocols);
1623#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001624 Py_TYPE(self)->tp_free(self);
1625}
1626
1627static PyObject *
1628set_ciphers(PySSLContext *self, PyObject *args)
1629{
1630 int ret;
1631 const char *cipherlist;
1632
1633 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1634 return NULL;
1635 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1636 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001637 /* Clearing the error queue is necessary on some OpenSSL versions,
1638 otherwise the error will be reported again when another SSL call
1639 is done. */
1640 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001641 PyErr_SetString(PySSLErrorObject,
1642 "No cipher can be selected.");
1643 return NULL;
1644 }
1645 Py_RETURN_NONE;
1646}
1647
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001648#ifdef OPENSSL_NPN_NEGOTIATED
1649/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
1650static int
1651_advertiseNPN_cb(SSL *s,
1652 const unsigned char **data, unsigned int *len,
1653 void *args)
1654{
1655 PySSLContext *ssl_ctx = (PySSLContext *) args;
1656
1657 if (ssl_ctx->npn_protocols == NULL) {
1658 *data = (unsigned char *) "";
1659 *len = 0;
1660 } else {
1661 *data = (unsigned char *) ssl_ctx->npn_protocols;
1662 *len = ssl_ctx->npn_protocols_len;
1663 }
1664
1665 return SSL_TLSEXT_ERR_OK;
1666}
1667/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
1668static int
1669_selectNPN_cb(SSL *s,
1670 unsigned char **out, unsigned char *outlen,
1671 const unsigned char *server, unsigned int server_len,
1672 void *args)
1673{
1674 PySSLContext *ssl_ctx = (PySSLContext *) args;
1675
1676 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
1677 int client_len;
1678
1679 if (client == NULL) {
1680 client = (unsigned char *) "";
1681 client_len = 0;
1682 } else {
1683 client_len = ssl_ctx->npn_protocols_len;
1684 }
1685
1686 SSL_select_next_proto(out, outlen,
1687 server, server_len,
1688 client, client_len);
1689
1690 return SSL_TLSEXT_ERR_OK;
1691}
1692#endif
1693
1694static PyObject *
1695_set_npn_protocols(PySSLContext *self, PyObject *args)
1696{
1697#ifdef OPENSSL_NPN_NEGOTIATED
1698 Py_buffer protos;
1699
1700 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
1701 return NULL;
1702
1703 self->npn_protocols = PyMem_Malloc(protos.len);
1704 if (self->npn_protocols == NULL) {
1705 PyBuffer_Release(&protos);
1706 return PyErr_NoMemory();
1707 }
1708 memcpy(self->npn_protocols, protos.buf, protos.len);
1709 self->npn_protocols_len = (int) protos.len;
1710
1711 /* set both server and client callbacks, because the context can
1712 * be used to create both types of sockets */
1713 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
1714 _advertiseNPN_cb,
1715 self);
1716 SSL_CTX_set_next_proto_select_cb(self->ctx,
1717 _selectNPN_cb,
1718 self);
1719
1720 PyBuffer_Release(&protos);
1721 Py_RETURN_NONE;
1722#else
1723 PyErr_SetString(PyExc_NotImplementedError,
1724 "The NPN extension requires OpenSSL 1.0.1 or later.");
1725 return NULL;
1726#endif
1727}
1728
Antoine Pitrou152efa22010-05-16 18:19:27 +00001729static PyObject *
1730get_verify_mode(PySSLContext *self, void *c)
1731{
1732 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1733 case SSL_VERIFY_NONE:
1734 return PyLong_FromLong(PY_SSL_CERT_NONE);
1735 case SSL_VERIFY_PEER:
1736 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1737 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1738 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1739 }
1740 PyErr_SetString(PySSLErrorObject,
1741 "invalid return value from SSL_CTX_get_verify_mode");
1742 return NULL;
1743}
1744
1745static int
1746set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1747{
1748 int n, mode;
1749 if (!PyArg_Parse(arg, "i", &n))
1750 return -1;
1751 if (n == PY_SSL_CERT_NONE)
1752 mode = SSL_VERIFY_NONE;
1753 else if (n == PY_SSL_CERT_OPTIONAL)
1754 mode = SSL_VERIFY_PEER;
1755 else if (n == PY_SSL_CERT_REQUIRED)
1756 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1757 else {
1758 PyErr_SetString(PyExc_ValueError,
1759 "invalid value for verify_mode");
1760 return -1;
1761 }
1762 SSL_CTX_set_verify(self->ctx, mode, NULL);
1763 return 0;
1764}
1765
1766static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001767get_options(PySSLContext *self, void *c)
1768{
1769 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1770}
1771
1772static int
1773set_options(PySSLContext *self, PyObject *arg, void *c)
1774{
1775 long new_opts, opts, set, clear;
1776 if (!PyArg_Parse(arg, "l", &new_opts))
1777 return -1;
1778 opts = SSL_CTX_get_options(self->ctx);
1779 clear = opts & ~new_opts;
1780 set = ~opts & new_opts;
1781 if (clear) {
1782#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1783 SSL_CTX_clear_options(self->ctx, clear);
1784#else
1785 PyErr_SetString(PyExc_ValueError,
1786 "can't clear options before OpenSSL 0.9.8m");
1787 return -1;
1788#endif
1789 }
1790 if (set)
1791 SSL_CTX_set_options(self->ctx, set);
1792 return 0;
1793}
1794
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001795typedef struct {
1796 PyThreadState *thread_state;
1797 PyObject *callable;
1798 char *password;
1799 Py_ssize_t size;
1800 int error;
1801} _PySSLPasswordInfo;
1802
1803static int
1804_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
1805 const char *bad_type_error)
1806{
1807 /* Set the password and size fields of a _PySSLPasswordInfo struct
1808 from a unicode, bytes, or byte array object.
1809 The password field will be dynamically allocated and must be freed
1810 by the caller */
1811 PyObject *password_bytes = NULL;
1812 const char *data = NULL;
1813 Py_ssize_t size;
1814
1815 if (PyUnicode_Check(password)) {
1816 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
1817 if (!password_bytes) {
1818 goto error;
1819 }
1820 data = PyBytes_AS_STRING(password_bytes);
1821 size = PyBytes_GET_SIZE(password_bytes);
1822 } else if (PyBytes_Check(password)) {
1823 data = PyBytes_AS_STRING(password);
1824 size = PyBytes_GET_SIZE(password);
1825 } else if (PyByteArray_Check(password)) {
1826 data = PyByteArray_AS_STRING(password);
1827 size = PyByteArray_GET_SIZE(password);
1828 } else {
1829 PyErr_SetString(PyExc_TypeError, bad_type_error);
1830 goto error;
1831 }
1832
1833 free(pw_info->password);
1834 pw_info->password = malloc(size);
1835 if (!pw_info->password) {
1836 PyErr_SetString(PyExc_MemoryError,
1837 "unable to allocate password buffer");
1838 goto error;
1839 }
1840 memcpy(pw_info->password, data, size);
1841 pw_info->size = size;
1842
1843 Py_XDECREF(password_bytes);
1844 return 1;
1845
1846error:
1847 Py_XDECREF(password_bytes);
1848 return 0;
1849}
1850
1851static int
1852_password_callback(char *buf, int size, int rwflag, void *userdata)
1853{
1854 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
1855 PyObject *fn_ret = NULL;
1856
1857 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
1858
1859 if (pw_info->callable) {
1860 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
1861 if (!fn_ret) {
1862 /* TODO: It would be nice to move _ctypes_add_traceback() into the
1863 core python API, so we could use it to add a frame here */
1864 goto error;
1865 }
1866
1867 if (!_pwinfo_set(pw_info, fn_ret,
1868 "password callback must return a string")) {
1869 goto error;
1870 }
1871 Py_CLEAR(fn_ret);
1872 }
1873
1874 if (pw_info->size > size) {
1875 PyErr_Format(PyExc_ValueError,
1876 "password cannot be longer than %d bytes", size);
1877 goto error;
1878 }
1879
1880 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
1881 memcpy(buf, pw_info->password, pw_info->size);
1882 return pw_info->size;
1883
1884error:
1885 Py_XDECREF(fn_ret);
1886 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
1887 pw_info->error = 1;
1888 return -1;
1889}
1890
Antoine Pitroub5218772010-05-21 09:56:06 +00001891static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001892load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
1893{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001894 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
1895 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001896 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001897 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
1898 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
1899 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00001900 int r;
1901
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001902 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00001903 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001904 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001905 "O|OO:load_cert_chain", kwlist,
1906 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00001907 return NULL;
1908 if (keyfile == Py_None)
1909 keyfile = NULL;
1910 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
1911 PyErr_SetString(PyExc_TypeError,
1912 "certfile should be a valid filesystem path");
1913 return NULL;
1914 }
1915 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
1916 PyErr_SetString(PyExc_TypeError,
1917 "keyfile should be a valid filesystem path");
1918 goto error;
1919 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001920 if (password && password != Py_None) {
1921 if (PyCallable_Check(password)) {
1922 pw_info.callable = password;
1923 } else if (!_pwinfo_set(&pw_info, password,
1924 "password should be a string or callable")) {
1925 goto error;
1926 }
1927 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
1928 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
1929 }
1930 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001931 r = SSL_CTX_use_certificate_chain_file(self->ctx,
1932 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001933 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001934 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001935 if (pw_info.error) {
1936 ERR_clear_error();
1937 /* the password callback has already set the error information */
1938 }
1939 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001940 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001941 PyErr_SetFromErrno(PyExc_IOError);
1942 }
1943 else {
1944 _setSSLError(NULL, 0, __FILE__, __LINE__);
1945 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001946 goto error;
1947 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001948 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02001949 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001950 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
1951 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001952 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
1953 Py_CLEAR(keyfile_bytes);
1954 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001955 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001956 if (pw_info.error) {
1957 ERR_clear_error();
1958 /* the password callback has already set the error information */
1959 }
1960 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001961 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001962 PyErr_SetFromErrno(PyExc_IOError);
1963 }
1964 else {
1965 _setSSLError(NULL, 0, __FILE__, __LINE__);
1966 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001967 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001968 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001969 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001970 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001971 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001972 if (r != 1) {
1973 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001974 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001975 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001976 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
1977 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
1978 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001979 Py_RETURN_NONE;
1980
1981error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001982 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
1983 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
1984 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001985 Py_XDECREF(keyfile_bytes);
1986 Py_XDECREF(certfile_bytes);
1987 return NULL;
1988}
1989
1990static PyObject *
1991load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
1992{
1993 char *kwlist[] = {"cafile", "capath", NULL};
1994 PyObject *cafile = NULL, *capath = NULL;
1995 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
1996 const char *cafile_buf = NULL, *capath_buf = NULL;
1997 int r;
1998
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001999 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002000 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2001 "|OO:load_verify_locations", kwlist,
2002 &cafile, &capath))
2003 return NULL;
2004 if (cafile == Py_None)
2005 cafile = NULL;
2006 if (capath == Py_None)
2007 capath = NULL;
2008 if (cafile == NULL && capath == NULL) {
2009 PyErr_SetString(PyExc_TypeError,
2010 "cafile and capath cannot be both omitted");
2011 return NULL;
2012 }
2013 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2014 PyErr_SetString(PyExc_TypeError,
2015 "cafile should be a valid filesystem path");
2016 return NULL;
2017 }
2018 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00002019 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002020 PyErr_SetString(PyExc_TypeError,
2021 "capath should be a valid filesystem path");
2022 return NULL;
2023 }
2024 if (cafile)
2025 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2026 if (capath)
2027 capath_buf = PyBytes_AS_STRING(capath_bytes);
2028 PySSL_BEGIN_ALLOW_THREADS
2029 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2030 PySSL_END_ALLOW_THREADS
2031 Py_XDECREF(cafile_bytes);
2032 Py_XDECREF(capath_bytes);
2033 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002034 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002035 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002036 PyErr_SetFromErrno(PyExc_IOError);
2037 }
2038 else {
2039 _setSSLError(NULL, 0, __FILE__, __LINE__);
2040 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002041 return NULL;
2042 }
2043 Py_RETURN_NONE;
2044}
2045
2046static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002047load_dh_params(PySSLContext *self, PyObject *filepath)
2048{
2049 FILE *f;
2050 DH *dh;
2051
2052 f = _Py_fopen(filepath, "rb");
2053 if (f == NULL) {
2054 if (!PyErr_Occurred())
2055 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2056 return NULL;
2057 }
2058 errno = 0;
2059 PySSL_BEGIN_ALLOW_THREADS
2060 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
2061 PySSL_END_ALLOW_THREADS
2062 if (dh == NULL) {
2063 if (errno != 0) {
2064 ERR_clear_error();
2065 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2066 }
2067 else {
2068 _setSSLError(NULL, 0, __FILE__, __LINE__);
2069 }
2070 return NULL;
2071 }
2072 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2073 _setSSLError(NULL, 0, __FILE__, __LINE__);
2074 DH_free(dh);
2075 Py_RETURN_NONE;
2076}
2077
2078static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002079context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2080{
Antoine Pitroud5323212010-10-22 18:19:07 +00002081 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002082 PySocketSockObject *sock;
2083 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002084 char *hostname = NULL;
2085 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002086
Antoine Pitroud5323212010-10-22 18:19:07 +00002087 /* server_hostname is either None (or absent), or to be encoded
2088 using the idna encoding. */
2089 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002090 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002091 &sock, &server_side,
2092 Py_TYPE(Py_None), &hostname_obj)) {
2093 PyErr_Clear();
2094 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2095 PySocketModule.Sock_Type,
2096 &sock, &server_side,
2097 "idna", &hostname))
2098 return NULL;
2099#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
2100 PyMem_Free(hostname);
2101 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2102 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002103 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002104#endif
2105 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002106
Antoine Pitroud5323212010-10-22 18:19:07 +00002107 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
2108 hostname);
2109 if (hostname != NULL)
2110 PyMem_Free(hostname);
2111 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002112}
2113
Antoine Pitroub0182c82010-10-12 20:09:02 +00002114static PyObject *
2115session_stats(PySSLContext *self, PyObject *unused)
2116{
2117 int r;
2118 PyObject *value, *stats = PyDict_New();
2119 if (!stats)
2120 return NULL;
2121
2122#define ADD_STATS(SSL_NAME, KEY_NAME) \
2123 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2124 if (value == NULL) \
2125 goto error; \
2126 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2127 Py_DECREF(value); \
2128 if (r < 0) \
2129 goto error;
2130
2131 ADD_STATS(number, "number");
2132 ADD_STATS(connect, "connect");
2133 ADD_STATS(connect_good, "connect_good");
2134 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2135 ADD_STATS(accept, "accept");
2136 ADD_STATS(accept_good, "accept_good");
2137 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2138 ADD_STATS(accept, "accept");
2139 ADD_STATS(hits, "hits");
2140 ADD_STATS(misses, "misses");
2141 ADD_STATS(timeouts, "timeouts");
2142 ADD_STATS(cache_full, "cache_full");
2143
2144#undef ADD_STATS
2145
2146 return stats;
2147
2148error:
2149 Py_DECREF(stats);
2150 return NULL;
2151}
2152
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002153static PyObject *
2154set_default_verify_paths(PySSLContext *self, PyObject *unused)
2155{
2156 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2157 _setSSLError(NULL, 0, __FILE__, __LINE__);
2158 return NULL;
2159 }
2160 Py_RETURN_NONE;
2161}
2162
Antoine Pitrou501da612011-12-21 09:27:41 +01002163#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002164static PyObject *
2165set_ecdh_curve(PySSLContext *self, PyObject *name)
2166{
2167 PyObject *name_bytes;
2168 int nid;
2169 EC_KEY *key;
2170
2171 if (!PyUnicode_FSConverter(name, &name_bytes))
2172 return NULL;
2173 assert(PyBytes_Check(name_bytes));
2174 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2175 Py_DECREF(name_bytes);
2176 if (nid == 0) {
2177 PyErr_Format(PyExc_ValueError,
2178 "unknown elliptic curve name %R", name);
2179 return NULL;
2180 }
2181 key = EC_KEY_new_by_curve_name(nid);
2182 if (key == NULL) {
2183 _setSSLError(NULL, 0, __FILE__, __LINE__);
2184 return NULL;
2185 }
2186 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2187 EC_KEY_free(key);
2188 Py_RETURN_NONE;
2189}
Antoine Pitrou501da612011-12-21 09:27:41 +01002190#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002191
Antoine Pitrou152efa22010-05-16 18:19:27 +00002192static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002193 {"options", (getter) get_options,
2194 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002195 {"verify_mode", (getter) get_verify_mode,
2196 (setter) set_verify_mode, NULL},
2197 {NULL}, /* sentinel */
2198};
2199
2200static struct PyMethodDef context_methods[] = {
2201 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2202 METH_VARARGS | METH_KEYWORDS, NULL},
2203 {"set_ciphers", (PyCFunction) set_ciphers,
2204 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002205 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2206 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002207 {"load_cert_chain", (PyCFunction) load_cert_chain,
2208 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002209 {"load_dh_params", (PyCFunction) load_dh_params,
2210 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002211 {"load_verify_locations", (PyCFunction) load_verify_locations,
2212 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002213 {"session_stats", (PyCFunction) session_stats,
2214 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002215 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2216 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002217#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002218 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2219 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002220#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002221 {NULL, NULL} /* sentinel */
2222};
2223
2224static PyTypeObject PySSLContext_Type = {
2225 PyVarObject_HEAD_INIT(NULL, 0)
2226 "_ssl._SSLContext", /*tp_name*/
2227 sizeof(PySSLContext), /*tp_basicsize*/
2228 0, /*tp_itemsize*/
2229 (destructor)context_dealloc, /*tp_dealloc*/
2230 0, /*tp_print*/
2231 0, /*tp_getattr*/
2232 0, /*tp_setattr*/
2233 0, /*tp_reserved*/
2234 0, /*tp_repr*/
2235 0, /*tp_as_number*/
2236 0, /*tp_as_sequence*/
2237 0, /*tp_as_mapping*/
2238 0, /*tp_hash*/
2239 0, /*tp_call*/
2240 0, /*tp_str*/
2241 0, /*tp_getattro*/
2242 0, /*tp_setattro*/
2243 0, /*tp_as_buffer*/
2244 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
2245 0, /*tp_doc*/
2246 0, /*tp_traverse*/
2247 0, /*tp_clear*/
2248 0, /*tp_richcompare*/
2249 0, /*tp_weaklistoffset*/
2250 0, /*tp_iter*/
2251 0, /*tp_iternext*/
2252 context_methods, /*tp_methods*/
2253 0, /*tp_members*/
2254 context_getsetlist, /*tp_getset*/
2255 0, /*tp_base*/
2256 0, /*tp_dict*/
2257 0, /*tp_descr_get*/
2258 0, /*tp_descr_set*/
2259 0, /*tp_dictoffset*/
2260 0, /*tp_init*/
2261 0, /*tp_alloc*/
2262 context_new, /*tp_new*/
2263};
2264
2265
2266
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002267#ifdef HAVE_OPENSSL_RAND
2268
2269/* helper routines for seeding the SSL PRNG */
2270static PyObject *
2271PySSL_RAND_add(PyObject *self, PyObject *args)
2272{
2273 char *buf;
2274 int len;
2275 double entropy;
2276
2277 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002278 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002279 RAND_add(buf, len, entropy);
2280 Py_INCREF(Py_None);
2281 return Py_None;
2282}
2283
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002284PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002285"RAND_add(string, entropy)\n\
2286\n\
2287Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002288bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002289
2290static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002291PySSL_RAND(int len, int pseudo)
2292{
2293 int ok;
2294 PyObject *bytes;
2295 unsigned long err;
2296 const char *errstr;
2297 PyObject *v;
2298
2299 bytes = PyBytes_FromStringAndSize(NULL, len);
2300 if (bytes == NULL)
2301 return NULL;
2302 if (pseudo) {
2303 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2304 if (ok == 0 || ok == 1)
2305 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2306 }
2307 else {
2308 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2309 if (ok == 1)
2310 return bytes;
2311 }
2312 Py_DECREF(bytes);
2313
2314 err = ERR_get_error();
2315 errstr = ERR_reason_error_string(err);
2316 v = Py_BuildValue("(ks)", err, errstr);
2317 if (v != NULL) {
2318 PyErr_SetObject(PySSLErrorObject, v);
2319 Py_DECREF(v);
2320 }
2321 return NULL;
2322}
2323
2324static PyObject *
2325PySSL_RAND_bytes(PyObject *self, PyObject *args)
2326{
2327 int len;
2328 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2329 return NULL;
2330 return PySSL_RAND(len, 0);
2331}
2332
2333PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2334"RAND_bytes(n) -> bytes\n\
2335\n\
2336Generate n cryptographically strong pseudo-random bytes.");
2337
2338static PyObject *
2339PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2340{
2341 int len;
2342 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2343 return NULL;
2344 return PySSL_RAND(len, 1);
2345}
2346
2347PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2348"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2349\n\
2350Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2351generated are cryptographically strong.");
2352
2353static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002354PySSL_RAND_status(PyObject *self)
2355{
Christian Heimes217cfd12007-12-02 14:31:20 +00002356 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002357}
2358
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002359PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002360"RAND_status() -> 0 or 1\n\
2361\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002362Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2363It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2364using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002365
2366static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002367PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002368{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002369 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002370 int bytes;
2371
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002372 if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
2373 PyUnicode_FSConverter, &path))
2374 return NULL;
2375
2376 bytes = RAND_egd(PyBytes_AsString(path));
2377 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002378 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002379 PyErr_SetString(PySSLErrorObject,
2380 "EGD connection failed or EGD did not return "
2381 "enough data to seed the PRNG");
2382 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002383 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002384 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002385}
2386
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002387PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002388"RAND_egd(path) -> bytes\n\
2389\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002390Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2391Returns number of bytes read. Raises SSLError if connection to EGD\n\
2392fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002393
2394#endif
2395
Bill Janssen40a0f662008-08-12 16:56:25 +00002396
2397
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002398/* List of functions exported by this module. */
2399
2400static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002401 {"_test_decode_cert", PySSL_test_decode_certificate,
2402 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002403#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002404 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
2405 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02002406 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
2407 PySSL_RAND_bytes_doc},
2408 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
2409 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002410 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002411 PySSL_RAND_egd_doc},
2412 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
2413 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002414#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002415 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002416};
2417
2418
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002419#ifdef WITH_THREAD
2420
2421/* an implementation of OpenSSL threading operations in terms
2422 of the Python C thread library */
2423
2424static PyThread_type_lock *_ssl_locks = NULL;
2425
2426static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002427 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002428}
2429
Bill Janssen6e027db2007-11-15 22:23:56 +00002430static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002431 (int mode, int n, const char *file, int line) {
2432 /* this function is needed to perform locking on shared data
2433 structures. (Note that OpenSSL uses a number of global data
2434 structures that will be implicitly shared whenever multiple
2435 threads use OpenSSL.) Multi-threaded applications will
2436 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002437
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002438 locking_function() must be able to handle up to
2439 CRYPTO_num_locks() different mutex locks. It sets the n-th
2440 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002441
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002442 file and line are the file number of the function setting the
2443 lock. They can be useful for debugging.
2444 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002445
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002446 if ((_ssl_locks == NULL) ||
2447 (n < 0) || ((unsigned)n >= _ssl_locks_count))
2448 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002449
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002450 if (mode & CRYPTO_LOCK) {
2451 PyThread_acquire_lock(_ssl_locks[n], 1);
2452 } else {
2453 PyThread_release_lock(_ssl_locks[n]);
2454 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002455}
2456
2457static int _setup_ssl_threads(void) {
2458
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002459 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002460
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002461 if (_ssl_locks == NULL) {
2462 _ssl_locks_count = CRYPTO_num_locks();
2463 _ssl_locks = (PyThread_type_lock *)
2464 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2465 if (_ssl_locks == NULL)
2466 return 0;
2467 memset(_ssl_locks, 0,
2468 sizeof(PyThread_type_lock) * _ssl_locks_count);
2469 for (i = 0; i < _ssl_locks_count; i++) {
2470 _ssl_locks[i] = PyThread_allocate_lock();
2471 if (_ssl_locks[i] == NULL) {
2472 unsigned int j;
2473 for (j = 0; j < i; j++) {
2474 PyThread_free_lock(_ssl_locks[j]);
2475 }
2476 free(_ssl_locks);
2477 return 0;
2478 }
2479 }
2480 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
2481 CRYPTO_set_id_callback(_ssl_thread_id_function);
2482 }
2483 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002484}
2485
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002486#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002487
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002488PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002489"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002490for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002491
Martin v. Löwis1a214512008-06-11 05:26:20 +00002492
2493static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002494 PyModuleDef_HEAD_INIT,
2495 "_ssl",
2496 module_doc,
2497 -1,
2498 PySSL_methods,
2499 NULL,
2500 NULL,
2501 NULL,
2502 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002503};
2504
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002505
2506static void
2507parse_openssl_version(unsigned long libver,
2508 unsigned int *major, unsigned int *minor,
2509 unsigned int *fix, unsigned int *patch,
2510 unsigned int *status)
2511{
2512 *status = libver & 0xF;
2513 libver >>= 4;
2514 *patch = libver & 0xFF;
2515 libver >>= 8;
2516 *fix = libver & 0xFF;
2517 libver >>= 8;
2518 *minor = libver & 0xFF;
2519 libver >>= 8;
2520 *major = libver & 0xFF;
2521}
2522
Antoine Pitroua0e0e232011-10-22 23:41:52 +02002523PyDoc_STRVAR(SSLError_doc,
2524"An error occurred in the SSL implementation.");
2525
Antoine Pitrou41032a62011-10-27 23:56:55 +02002526PyDoc_STRVAR(SSLZeroReturnError_doc,
2527"SSL/TLS session closed cleanly.");
2528
2529PyDoc_STRVAR(SSLWantReadError_doc,
2530"Non-blocking SSL socket needs to read more data\n"
2531"before the requested operation can be completed.");
2532
2533PyDoc_STRVAR(SSLWantWriteError_doc,
2534"Non-blocking SSL socket needs to write more data\n"
2535"before the requested operation can be completed.");
2536
2537PyDoc_STRVAR(SSLSyscallError_doc,
2538"System error when attempting SSL operation.");
2539
2540PyDoc_STRVAR(SSLEOFError_doc,
2541"SSL/TLS connection terminated abruptly.");
2542
Antoine Pitroua0e0e232011-10-22 23:41:52 +02002543
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002544PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002545PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002546{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002547 PyObject *m, *d, *r;
2548 unsigned long libver;
2549 unsigned int major, minor, fix, patch, status;
2550 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002551
Antoine Pitrou152efa22010-05-16 18:19:27 +00002552 if (PyType_Ready(&PySSLContext_Type) < 0)
2553 return NULL;
2554 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002555 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002556
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002557 m = PyModule_Create(&_sslmodule);
2558 if (m == NULL)
2559 return NULL;
2560 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002561
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002562 /* Load _socket module and its C API */
2563 socket_api = PySocketModule_ImportModuleAndAPI();
2564 if (!socket_api)
2565 return NULL;
2566 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002567
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002568 /* Init OpenSSL */
2569 SSL_load_error_strings();
2570 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002571#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002572 /* note that this will start threading if not already started */
2573 if (!_setup_ssl_threads()) {
2574 return NULL;
2575 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002576#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002577 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002578
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002579 /* Add symbols to module dict */
Antoine Pitroua0e0e232011-10-22 23:41:52 +02002580 PySSLErrorObject = PyErr_NewExceptionWithDoc("ssl.SSLError",
2581 SSLError_doc,
2582 PyExc_OSError,
2583 NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002584 if (PySSLErrorObject == NULL)
2585 return NULL;
Antoine Pitrou41032a62011-10-27 23:56:55 +02002586 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
2587 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
2588 PySSLErrorObject, NULL);
2589 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
2590 "ssl.SSLWantReadError", SSLWantReadError_doc,
2591 PySSLErrorObject, NULL);
2592 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
2593 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
2594 PySSLErrorObject, NULL);
2595 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
2596 "ssl.SSLSyscallError", SSLSyscallError_doc,
2597 PySSLErrorObject, NULL);
2598 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
2599 "ssl.SSLEOFError", SSLEOFError_doc,
2600 PySSLErrorObject, NULL);
2601 if (PySSLZeroReturnErrorObject == NULL
2602 || PySSLWantReadErrorObject == NULL
2603 || PySSLWantWriteErrorObject == NULL
2604 || PySSLSyscallErrorObject == NULL
2605 || PySSLEOFErrorObject == NULL)
2606 return NULL;
2607 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
2608 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
2609 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
2610 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
2611 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
2612 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002613 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002614 if (PyDict_SetItemString(d, "_SSLContext",
2615 (PyObject *)&PySSLContext_Type) != 0)
2616 return NULL;
2617 if (PyDict_SetItemString(d, "_SSLSocket",
2618 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002619 return NULL;
2620 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2621 PY_SSL_ERROR_ZERO_RETURN);
2622 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2623 PY_SSL_ERROR_WANT_READ);
2624 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2625 PY_SSL_ERROR_WANT_WRITE);
2626 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2627 PY_SSL_ERROR_WANT_X509_LOOKUP);
2628 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2629 PY_SSL_ERROR_SYSCALL);
2630 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2631 PY_SSL_ERROR_SSL);
2632 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2633 PY_SSL_ERROR_WANT_CONNECT);
2634 /* non ssl.h errorcodes */
2635 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2636 PY_SSL_ERROR_EOF);
2637 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2638 PY_SSL_ERROR_INVALID_ERROR_CODE);
2639 /* cert requirements */
2640 PyModule_AddIntConstant(m, "CERT_NONE",
2641 PY_SSL_CERT_NONE);
2642 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2643 PY_SSL_CERT_OPTIONAL);
2644 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2645 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002646
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002647 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02002648#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002649 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2650 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02002651#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002652 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2653 PY_SSL_VERSION_SSL3);
2654 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2655 PY_SSL_VERSION_SSL23);
2656 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2657 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002658
Antoine Pitroub5218772010-05-21 09:56:06 +00002659 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01002660 PyModule_AddIntConstant(m, "OP_ALL",
2661 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00002662 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2663 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2664 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou6db49442011-12-19 13:27:11 +01002665 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
2666 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002667 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002668#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002669 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002670#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002671#ifdef SSL_OP_NO_COMPRESSION
2672 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
2673 SSL_OP_NO_COMPRESSION);
2674#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00002675
Antoine Pitroud5323212010-10-22 18:19:07 +00002676#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2677 r = Py_True;
2678#else
2679 r = Py_False;
2680#endif
2681 Py_INCREF(r);
2682 PyModule_AddObject(m, "HAS_SNI", r);
2683
Antoine Pitroud6494802011-07-21 01:11:30 +02002684#if HAVE_OPENSSL_FINISHED
2685 r = Py_True;
2686#else
2687 r = Py_False;
2688#endif
2689 Py_INCREF(r);
2690 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
2691
Antoine Pitrou501da612011-12-21 09:27:41 +01002692#ifdef OPENSSL_NO_ECDH
2693 r = Py_False;
2694#else
2695 r = Py_True;
2696#endif
2697 Py_INCREF(r);
2698 PyModule_AddObject(m, "HAS_ECDH", r);
2699
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002700#ifdef OPENSSL_NPN_NEGOTIATED
2701 r = Py_True;
2702#else
2703 r = Py_False;
2704#endif
2705 Py_INCREF(r);
2706 PyModule_AddObject(m, "HAS_NPN", r);
2707
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002708 /* OpenSSL version */
2709 /* SSLeay() gives us the version of the library linked against,
2710 which could be different from the headers version.
2711 */
2712 libver = SSLeay();
2713 r = PyLong_FromUnsignedLong(libver);
2714 if (r == NULL)
2715 return NULL;
2716 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2717 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002718 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002719 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2720 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2721 return NULL;
2722 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2723 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2724 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002725
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002726 libver = OPENSSL_VERSION_NUMBER;
2727 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
2728 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2729 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
2730 return NULL;
2731
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002732 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002733}