blob: dcde4ff2afe0d3c5a7c985cea938ddb1e74be36e [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
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000148typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000149 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000150 SSL_CTX *ctx;
151} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000152
Antoine Pitrou152efa22010-05-16 18:19:27 +0000153typedef struct {
154 PyObject_HEAD
155 PyObject *Socket; /* weakref to socket on which we're layered */
156 SSL *ssl;
157 X509 *peer_cert;
158 int shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200159 enum py_ssl_server_or_client socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000160} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000161
Antoine Pitrou152efa22010-05-16 18:19:27 +0000162static PyTypeObject PySSLContext_Type;
163static PyTypeObject PySSLSocket_Type;
164
165static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
166static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000167static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000168 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000169static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
170static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000171
Antoine Pitrou152efa22010-05-16 18:19:27 +0000172#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
173#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000174
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000175typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000176 SOCKET_IS_NONBLOCKING,
177 SOCKET_IS_BLOCKING,
178 SOCKET_HAS_TIMED_OUT,
179 SOCKET_HAS_BEEN_CLOSED,
180 SOCKET_TOO_LARGE_FOR_SELECT,
181 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000182} timeout_state;
183
Thomas Woutersed03b412007-08-28 21:37:11 +0000184/* Wrap error strings with filename and line # */
185#define STRINGIFY1(x) #x
186#define STRINGIFY2(x) STRINGIFY1(x)
187#define ERRSTR1(x,y,z) (x ":" y ": " z)
188#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
189
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000190/* XXX It might be helpful to augment the error message generated
191 below with the name of the SSL function that generated the error.
192 I expect it's obvious most of the time.
193*/
194
195static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000196PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000197{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000198 PyObject *v;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200199 PyObject *type = PySSLErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000200 char buf[2048];
201 char *errstr;
202 int err;
203 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000204
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000205 assert(ret <= 0);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000206
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000207 if (obj->ssl != NULL) {
208 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000209
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000210 switch (err) {
211 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200212 errstr = "TLS/SSL connection has been closed (EOF)";
213 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000214 p = PY_SSL_ERROR_ZERO_RETURN;
215 break;
216 case SSL_ERROR_WANT_READ:
217 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200218 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000219 p = PY_SSL_ERROR_WANT_READ;
220 break;
221 case SSL_ERROR_WANT_WRITE:
222 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200223 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000224 errstr = "The operation did not complete (write)";
225 break;
226 case SSL_ERROR_WANT_X509_LOOKUP:
227 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000228 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000229 break;
230 case SSL_ERROR_WANT_CONNECT:
231 p = PY_SSL_ERROR_WANT_CONNECT;
232 errstr = "The operation did not complete (connect)";
233 break;
234 case SSL_ERROR_SYSCALL:
235 {
236 unsigned long e = ERR_get_error();
237 if (e == 0) {
238 PySocketSockObject *s
239 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
240 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000241 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200242 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000243 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000244 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000245 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000246 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000247 ERR_clear_error();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000248 v = s->errorhandler();
249 Py_DECREF(s);
250 return v;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000251 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000252 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200253 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000254 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000255 }
256 } else {
257 p = PY_SSL_ERROR_SYSCALL;
258 /* XXX Protected by global interpreter lock */
259 errstr = ERR_error_string(e, NULL);
260 }
261 break;
262 }
263 case SSL_ERROR_SSL:
264 {
265 unsigned long e = ERR_get_error();
266 p = PY_SSL_ERROR_SSL;
267 if (e != 0)
268 /* XXX Protected by global interpreter lock */
269 errstr = ERR_error_string(e, NULL);
270 else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000271 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000272 }
273 break;
274 }
275 default:
276 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
277 errstr = "Invalid error code";
278 }
279 } else {
280 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
281 }
282 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000283 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000284 v = Py_BuildValue("(is)", p, buf);
285 if (v != NULL) {
Antoine Pitrou41032a62011-10-27 23:56:55 +0200286 PyErr_SetObject(type, v);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000287 Py_DECREF(v);
288 }
289 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000290}
291
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000292static PyObject *
293_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
294
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000295 char buf[2048];
296 PyObject *v;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000297
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000298 if (errstr == NULL) {
299 errcode = ERR_peek_last_error();
300 errstr = ERR_error_string(errcode, NULL);
301 }
302 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000303 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000304 v = Py_BuildValue("(is)", errcode, buf);
305 if (v != NULL) {
306 PyErr_SetObject(PySSLErrorObject, v);
307 Py_DECREF(v);
308 }
309 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000310}
311
Antoine Pitrou152efa22010-05-16 18:19:27 +0000312static PySSLSocket *
313newPySSLSocket(SSL_CTX *ctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000314 enum py_ssl_server_or_client socket_type,
315 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000316{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000317 PySSLSocket *self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000318
Antoine Pitrou152efa22010-05-16 18:19:27 +0000319 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000320 if (self == NULL)
321 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000322
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000323 self->peer_cert = NULL;
324 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000325 self->Socket = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000326
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000327 /* Make sure the SSL error state is initialized */
328 (void) ERR_get_state();
329 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000330
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000331 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000332 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000333 PySSL_END_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000334 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000335#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000336 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000337#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000338
Antoine Pitroud5323212010-10-22 18:19:07 +0000339#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
340 if (server_hostname != NULL)
341 SSL_set_tlsext_host_name(self->ssl, server_hostname);
342#endif
343
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000344 /* If the socket is in non-blocking mode or timeout mode, set the BIO
345 * to non-blocking mode (blocking is the default)
346 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000347 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000348 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
349 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
350 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000351
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000352 PySSL_BEGIN_ALLOW_THREADS
353 if (socket_type == PY_SSL_CLIENT)
354 SSL_set_connect_state(self->ssl);
355 else
356 SSL_set_accept_state(self->ssl);
357 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000358
Antoine Pitroud6494802011-07-21 01:11:30 +0200359 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000360 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000361 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000362}
363
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000364/* SSL object methods */
365
Antoine Pitrou152efa22010-05-16 18:19:27 +0000366static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000367{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000368 int ret;
369 int err;
370 int sockstate, nonblocking;
371 PySocketSockObject *sock
372 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000373
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000374 if (((PyObject*)sock) == Py_None) {
375 _setSSLError("Underlying socket connection gone",
376 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
377 return NULL;
378 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000379 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000380
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000381 /* just in case the blocking state of the socket has been changed */
382 nonblocking = (sock->sock_timeout >= 0.0);
383 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
384 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000385
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000386 /* Actually negotiate SSL connection */
387 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000388 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000389 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000390 ret = SSL_do_handshake(self->ssl);
391 err = SSL_get_error(self->ssl, ret);
392 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000393 if (PyErr_CheckSignals())
394 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000395 if (err == SSL_ERROR_WANT_READ) {
396 sockstate = check_socket_and_wait_for_timeout(sock, 0);
397 } else if (err == SSL_ERROR_WANT_WRITE) {
398 sockstate = check_socket_and_wait_for_timeout(sock, 1);
399 } else {
400 sockstate = SOCKET_OPERATION_OK;
401 }
402 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000403 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000404 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000405 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000406 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
407 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000408 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000409 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000410 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
411 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000412 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000413 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000414 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
415 break;
416 }
417 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000418 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000419 if (ret < 1)
420 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000421
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000422 if (self->peer_cert)
423 X509_free (self->peer_cert);
424 PySSL_BEGIN_ALLOW_THREADS
425 self->peer_cert = SSL_get_peer_certificate(self->ssl);
426 PySSL_END_ALLOW_THREADS
427
428 Py_INCREF(Py_None);
429 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000430
431error:
432 Py_DECREF(sock);
433 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000434}
435
Thomas Woutersed03b412007-08-28 21:37:11 +0000436static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000437_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000438
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000439 char namebuf[X509_NAME_MAXLEN];
440 int buflen;
441 PyObject *name_obj;
442 PyObject *value_obj;
443 PyObject *attr;
444 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000445
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000446 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
447 if (buflen < 0) {
448 _setSSLError(NULL, 0, __FILE__, __LINE__);
449 goto fail;
450 }
451 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
452 if (name_obj == NULL)
453 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000454
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000455 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
456 if (buflen < 0) {
457 _setSSLError(NULL, 0, __FILE__, __LINE__);
458 Py_DECREF(name_obj);
459 goto fail;
460 }
461 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000462 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000463 OPENSSL_free(valuebuf);
464 if (value_obj == NULL) {
465 Py_DECREF(name_obj);
466 goto fail;
467 }
468 attr = PyTuple_New(2);
469 if (attr == NULL) {
470 Py_DECREF(name_obj);
471 Py_DECREF(value_obj);
472 goto fail;
473 }
474 PyTuple_SET_ITEM(attr, 0, name_obj);
475 PyTuple_SET_ITEM(attr, 1, value_obj);
476 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000477
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000478 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000479 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000480}
481
482static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000483_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000484{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000485 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
486 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
487 PyObject *rdnt;
488 PyObject *attr = NULL; /* tuple to hold an attribute */
489 int entry_count = X509_NAME_entry_count(xname);
490 X509_NAME_ENTRY *entry;
491 ASN1_OBJECT *name;
492 ASN1_STRING *value;
493 int index_counter;
494 int rdn_level = -1;
495 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000496
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000497 dn = PyList_New(0);
498 if (dn == NULL)
499 return NULL;
500 /* now create another tuple to hold the top-level RDN */
501 rdn = PyList_New(0);
502 if (rdn == NULL)
503 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000504
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000505 for (index_counter = 0;
506 index_counter < entry_count;
507 index_counter++)
508 {
509 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000510
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000511 /* check to see if we've gotten to a new RDN */
512 if (rdn_level >= 0) {
513 if (rdn_level != entry->set) {
514 /* yes, new RDN */
515 /* add old RDN to DN */
516 rdnt = PyList_AsTuple(rdn);
517 Py_DECREF(rdn);
518 if (rdnt == NULL)
519 goto fail0;
520 retcode = PyList_Append(dn, rdnt);
521 Py_DECREF(rdnt);
522 if (retcode < 0)
523 goto fail0;
524 /* create new RDN */
525 rdn = PyList_New(0);
526 if (rdn == NULL)
527 goto fail0;
528 }
529 }
530 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000531
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000532 /* now add this attribute to the current RDN */
533 name = X509_NAME_ENTRY_get_object(entry);
534 value = X509_NAME_ENTRY_get_data(entry);
535 attr = _create_tuple_for_attribute(name, value);
536 /*
537 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
538 entry->set,
539 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
540 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
541 */
542 if (attr == NULL)
543 goto fail1;
544 retcode = PyList_Append(rdn, attr);
545 Py_DECREF(attr);
546 if (retcode < 0)
547 goto fail1;
548 }
549 /* now, there's typically a dangling RDN */
550 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
551 rdnt = PyList_AsTuple(rdn);
552 Py_DECREF(rdn);
553 if (rdnt == NULL)
554 goto fail0;
555 retcode = PyList_Append(dn, rdnt);
556 Py_DECREF(rdnt);
557 if (retcode < 0)
558 goto fail0;
559 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000560
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000561 /* convert list to tuple */
562 rdnt = PyList_AsTuple(dn);
563 Py_DECREF(dn);
564 if (rdnt == NULL)
565 return NULL;
566 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000567
568 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000569 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000570
571 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000572 Py_XDECREF(dn);
573 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000574}
575
576static PyObject *
577_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000578
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000579 /* this code follows the procedure outlined in
580 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
581 function to extract the STACK_OF(GENERAL_NAME),
582 then iterates through the stack to add the
583 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000584
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000585 int i, j;
586 PyObject *peer_alt_names = Py_None;
587 PyObject *v, *t;
588 X509_EXTENSION *ext = NULL;
589 GENERAL_NAMES *names = NULL;
590 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000591 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000592 BIO *biobuf = NULL;
593 char buf[2048];
594 char *vptr;
595 int len;
596 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000597#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000598 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000599#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000600 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000601#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000602
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000603 if (certificate == NULL)
604 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000605
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000606 /* get a memory buffer */
607 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000608
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200609 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000610 while ((i = X509_get_ext_by_NID(
611 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000612
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000613 if (peer_alt_names == Py_None) {
614 peer_alt_names = PyList_New(0);
615 if (peer_alt_names == NULL)
616 goto fail;
617 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000618
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000619 /* now decode the altName */
620 ext = X509_get_ext(certificate, i);
621 if(!(method = X509V3_EXT_get(ext))) {
622 PyErr_SetString
623 (PySSLErrorObject,
624 ERRSTR("No method for internalizing subjectAltName!"));
625 goto fail;
626 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000627
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000628 p = ext->value->data;
629 if (method->it)
630 names = (GENERAL_NAMES*)
631 (ASN1_item_d2i(NULL,
632 &p,
633 ext->value->length,
634 ASN1_ITEM_ptr(method->it)));
635 else
636 names = (GENERAL_NAMES*)
637 (method->d2i(NULL,
638 &p,
639 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000640
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000641 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000642
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000643 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000644
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000645 name = sk_GENERAL_NAME_value(names, j);
646 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000647
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000648 /* we special-case DirName as a tuple of
649 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000650
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000651 t = PyTuple_New(2);
652 if (t == NULL) {
653 goto fail;
654 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000655
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000656 v = PyUnicode_FromString("DirName");
657 if (v == NULL) {
658 Py_DECREF(t);
659 goto fail;
660 }
661 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000662
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000663 v = _create_tuple_for_X509_NAME (name->d.dirn);
664 if (v == NULL) {
665 Py_DECREF(t);
666 goto fail;
667 }
668 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000669
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000670 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000671
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000672 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000673
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000674 (void) BIO_reset(biobuf);
675 GENERAL_NAME_print(biobuf, name);
676 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
677 if (len < 0) {
678 _setSSLError(NULL, 0, __FILE__, __LINE__);
679 goto fail;
680 }
681 vptr = strchr(buf, ':');
682 if (vptr == NULL)
683 goto fail;
684 t = PyTuple_New(2);
685 if (t == NULL)
686 goto fail;
687 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
688 if (v == NULL) {
689 Py_DECREF(t);
690 goto fail;
691 }
692 PyTuple_SET_ITEM(t, 0, v);
693 v = PyUnicode_FromStringAndSize((vptr + 1),
694 (len - (vptr - buf + 1)));
695 if (v == NULL) {
696 Py_DECREF(t);
697 goto fail;
698 }
699 PyTuple_SET_ITEM(t, 1, v);
700 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000701
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000702 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000703
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000704 if (PyList_Append(peer_alt_names, t) < 0) {
705 Py_DECREF(t);
706 goto fail;
707 }
708 Py_DECREF(t);
709 }
710 }
711 BIO_free(biobuf);
712 if (peer_alt_names != Py_None) {
713 v = PyList_AsTuple(peer_alt_names);
714 Py_DECREF(peer_alt_names);
715 return v;
716 } else {
717 return peer_alt_names;
718 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000719
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000720
721 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000722 if (biobuf != NULL)
723 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000724
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000725 if (peer_alt_names != Py_None) {
726 Py_XDECREF(peer_alt_names);
727 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000728
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000729 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000730}
731
732static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000733_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000734
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000735 PyObject *retval = NULL;
736 BIO *biobuf = NULL;
737 PyObject *peer;
738 PyObject *peer_alt_names = NULL;
739 PyObject *issuer;
740 PyObject *version;
741 PyObject *sn_obj;
742 ASN1_INTEGER *serialNumber;
743 char buf[2048];
744 int len;
745 ASN1_TIME *notBefore, *notAfter;
746 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000747
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000748 retval = PyDict_New();
749 if (retval == NULL)
750 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000751
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000752 peer = _create_tuple_for_X509_NAME(
753 X509_get_subject_name(certificate));
754 if (peer == NULL)
755 goto fail0;
756 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
757 Py_DECREF(peer);
758 goto fail0;
759 }
760 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000761
Antoine Pitroufb046912010-11-09 20:21:19 +0000762 issuer = _create_tuple_for_X509_NAME(
763 X509_get_issuer_name(certificate));
764 if (issuer == NULL)
765 goto fail0;
766 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000767 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000768 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000769 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000770 Py_DECREF(issuer);
771
772 version = PyLong_FromLong(X509_get_version(certificate) + 1);
773 if (PyDict_SetItemString(retval, "version", version) < 0) {
774 Py_DECREF(version);
775 goto fail0;
776 }
777 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000778
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000779 /* get a memory buffer */
780 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000781
Antoine Pitroufb046912010-11-09 20:21:19 +0000782 (void) BIO_reset(biobuf);
783 serialNumber = X509_get_serialNumber(certificate);
784 /* should not exceed 20 octets, 160 bits, so buf is big enough */
785 i2a_ASN1_INTEGER(biobuf, serialNumber);
786 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
787 if (len < 0) {
788 _setSSLError(NULL, 0, __FILE__, __LINE__);
789 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000790 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000791 sn_obj = PyUnicode_FromStringAndSize(buf, len);
792 if (sn_obj == NULL)
793 goto fail1;
794 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
795 Py_DECREF(sn_obj);
796 goto fail1;
797 }
798 Py_DECREF(sn_obj);
799
800 (void) BIO_reset(biobuf);
801 notBefore = X509_get_notBefore(certificate);
802 ASN1_TIME_print(biobuf, notBefore);
803 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
804 if (len < 0) {
805 _setSSLError(NULL, 0, __FILE__, __LINE__);
806 goto fail1;
807 }
808 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
809 if (pnotBefore == NULL)
810 goto fail1;
811 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
812 Py_DECREF(pnotBefore);
813 goto fail1;
814 }
815 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000816
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000817 (void) BIO_reset(biobuf);
818 notAfter = X509_get_notAfter(certificate);
819 ASN1_TIME_print(biobuf, notAfter);
820 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
821 if (len < 0) {
822 _setSSLError(NULL, 0, __FILE__, __LINE__);
823 goto fail1;
824 }
825 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
826 if (pnotAfter == NULL)
827 goto fail1;
828 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
829 Py_DECREF(pnotAfter);
830 goto fail1;
831 }
832 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000833
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000834 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000835
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000836 peer_alt_names = _get_peer_alt_names(certificate);
837 if (peer_alt_names == NULL)
838 goto fail1;
839 else if (peer_alt_names != Py_None) {
840 if (PyDict_SetItemString(retval, "subjectAltName",
841 peer_alt_names) < 0) {
842 Py_DECREF(peer_alt_names);
843 goto fail1;
844 }
845 Py_DECREF(peer_alt_names);
846 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000847
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000848 BIO_free(biobuf);
849 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000850
851 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000852 if (biobuf != NULL)
853 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000854 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000855 Py_XDECREF(retval);
856 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000857}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000858
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000859
860static PyObject *
861PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
862
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000863 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +0000864 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000865 X509 *x=NULL;
866 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000867
Antoine Pitroufb046912010-11-09 20:21:19 +0000868 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
869 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000870 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000871
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000872 if ((cert=BIO_new(BIO_s_file())) == NULL) {
873 PyErr_SetString(PySSLErrorObject,
874 "Can't malloc memory to read file");
875 goto fail0;
876 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000877
Victor Stinner3800e1e2010-05-16 21:23:48 +0000878 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000879 PyErr_SetString(PySSLErrorObject,
880 "Can't open file");
881 goto fail0;
882 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000883
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000884 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
885 if (x == NULL) {
886 PyErr_SetString(PySSLErrorObject,
887 "Error decoding PEM-encoded file");
888 goto fail0;
889 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000890
Antoine Pitroufb046912010-11-09 20:21:19 +0000891 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +0000892 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000893
894 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +0000895 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000896 if (cert != NULL) BIO_free(cert);
897 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000898}
899
900
901static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000902PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000903{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000904 PyObject *retval = NULL;
905 int len;
906 int verification;
907 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000908
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000909 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
910 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000911
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000912 if (!self->peer_cert)
913 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000914
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000915 if (PyObject_IsTrue(binary_mode)) {
916 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000917
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000918 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000919
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000920 bytes_buf = NULL;
921 len = i2d_X509(self->peer_cert, &bytes_buf);
922 if (len < 0) {
923 PySSL_SetError(self, len, __FILE__, __LINE__);
924 return NULL;
925 }
926 /* this is actually an immutable bytes sequence */
927 retval = PyBytes_FromStringAndSize
928 ((const char *) bytes_buf, len);
929 OPENSSL_free(bytes_buf);
930 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000931
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000932 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000933 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000934 if ((verification & SSL_VERIFY_PEER) == 0)
935 return PyDict_New();
936 else
Antoine Pitroufb046912010-11-09 20:21:19 +0000937 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000939}
940
941PyDoc_STRVAR(PySSL_peercert_doc,
942"peer_certificate([der=False]) -> certificate\n\
943\n\
944Returns the certificate for the peer. If no certificate was provided,\n\
945returns None. If a certificate was provided, but not validated, returns\n\
946an empty dictionary. Otherwise returns a dict containing information\n\
947about the peer certificate.\n\
948\n\
949If the optional argument is True, returns a DER-encoded copy of the\n\
950peer certificate, or None if no certificate was provided. This will\n\
951return the certificate even if it wasn't validated.");
952
Antoine Pitrou152efa22010-05-16 18:19:27 +0000953static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000954
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000955 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000956 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000957 char *cipher_name;
958 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000959
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000960 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000961 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000962 current = SSL_get_current_cipher(self->ssl);
963 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000964 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000965
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000966 retval = PyTuple_New(3);
967 if (retval == NULL)
968 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000969
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000970 cipher_name = (char *) SSL_CIPHER_get_name(current);
971 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000972 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000973 PyTuple_SET_ITEM(retval, 0, Py_None);
974 } else {
975 v = PyUnicode_FromString(cipher_name);
976 if (v == NULL)
977 goto fail0;
978 PyTuple_SET_ITEM(retval, 0, v);
979 }
980 cipher_protocol = SSL_CIPHER_get_version(current);
981 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000982 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000983 PyTuple_SET_ITEM(retval, 1, Py_None);
984 } else {
985 v = PyUnicode_FromString(cipher_protocol);
986 if (v == NULL)
987 goto fail0;
988 PyTuple_SET_ITEM(retval, 1, v);
989 }
990 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
991 if (v == NULL)
992 goto fail0;
993 PyTuple_SET_ITEM(retval, 2, v);
994 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000995
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000996 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000997 Py_DECREF(retval);
998 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000999}
1000
Antoine Pitrou152efa22010-05-16 18:19:27 +00001001static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001002{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001003 if (self->peer_cert) /* Possible not to have one? */
1004 X509_free (self->peer_cert);
1005 if (self->ssl)
1006 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 Py_XDECREF(self->Socket);
1008 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001009}
1010
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001011/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001012 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001013 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001014 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001015
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001016static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001017check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001018{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001019 fd_set fds;
1020 struct timeval tv;
1021 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001022
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001023 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1024 if (s->sock_timeout < 0.0)
1025 return SOCKET_IS_BLOCKING;
1026 else if (s->sock_timeout == 0.0)
1027 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001028
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001029 /* Guard against closed socket */
1030 if (s->sock_fd < 0)
1031 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001032
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001033 /* Prefer poll, if available, since you can poll() any fd
1034 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001035#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001036 {
1037 struct pollfd pollfd;
1038 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001039
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001040 pollfd.fd = s->sock_fd;
1041 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001042
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001043 /* s->sock_timeout is in seconds, timeout in ms */
1044 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1045 PySSL_BEGIN_ALLOW_THREADS
1046 rc = poll(&pollfd, 1, timeout);
1047 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001048
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001049 goto normal_return;
1050 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001051#endif
1052
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001053 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001054 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001055 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001056
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 /* Construct the arguments to select */
1058 tv.tv_sec = (int)s->sock_timeout;
1059 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1060 FD_ZERO(&fds);
1061 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001062
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001063 /* See if the socket is ready */
1064 PySSL_BEGIN_ALLOW_THREADS
1065 if (writing)
1066 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1067 else
1068 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1069 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001070
Bill Janssen6e027db2007-11-15 22:23:56 +00001071#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001072normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001073#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001074 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1075 (when we are able to write or when there's something to read) */
1076 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001077}
1078
Antoine Pitrou152efa22010-05-16 18:19:27 +00001079static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001080{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001081 Py_buffer buf;
1082 int len;
1083 int sockstate;
1084 int err;
1085 int nonblocking;
1086 PySocketSockObject *sock
1087 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001088
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001089 if (((PyObject*)sock) == Py_None) {
1090 _setSSLError("Underlying socket connection gone",
1091 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1092 return NULL;
1093 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001094 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001095
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001096 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1097 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001098 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001099 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001100
1101 /* just in case the blocking state of the socket has been changed */
1102 nonblocking = (sock->sock_timeout >= 0.0);
1103 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1104 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1105
1106 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1107 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001108 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001109 "The write operation timed out");
1110 goto error;
1111 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1112 PyErr_SetString(PySSLErrorObject,
1113 "Underlying socket has been closed.");
1114 goto error;
1115 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1116 PyErr_SetString(PySSLErrorObject,
1117 "Underlying socket too large for select().");
1118 goto error;
1119 }
1120 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001121 PySSL_BEGIN_ALLOW_THREADS
1122 len = SSL_write(self->ssl, buf.buf, buf.len);
1123 err = SSL_get_error(self->ssl, len);
1124 PySSL_END_ALLOW_THREADS
1125 if (PyErr_CheckSignals()) {
1126 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001127 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001128 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001129 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001130 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001131 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001132 } else {
1133 sockstate = SOCKET_OPERATION_OK;
1134 }
1135 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001136 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001137 "The write operation timed out");
1138 goto error;
1139 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1140 PyErr_SetString(PySSLErrorObject,
1141 "Underlying socket has been closed.");
1142 goto error;
1143 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1144 break;
1145 }
1146 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001147
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001148 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001149 PyBuffer_Release(&buf);
1150 if (len > 0)
1151 return PyLong_FromLong(len);
1152 else
1153 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001154
1155error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001156 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001157 PyBuffer_Release(&buf);
1158 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001159}
1160
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001161PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001162"write(s) -> len\n\
1163\n\
1164Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001165of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001166
Antoine Pitrou152efa22010-05-16 18:19:27 +00001167static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001168{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001169 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001170
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001171 PySSL_BEGIN_ALLOW_THREADS
1172 count = SSL_pending(self->ssl);
1173 PySSL_END_ALLOW_THREADS
1174 if (count < 0)
1175 return PySSL_SetError(self, count, __FILE__, __LINE__);
1176 else
1177 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001178}
1179
1180PyDoc_STRVAR(PySSL_SSLpending_doc,
1181"pending() -> count\n\
1182\n\
1183Returns the number of already decrypted bytes available for read,\n\
1184pending on the connection.\n");
1185
Antoine Pitrou152efa22010-05-16 18:19:27 +00001186static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001187{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001188 PyObject *dest = NULL;
1189 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001190 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001191 int len, count;
1192 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001193 int sockstate;
1194 int err;
1195 int nonblocking;
1196 PySocketSockObject *sock
1197 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001198
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001199 if (((PyObject*)sock) == Py_None) {
1200 _setSSLError("Underlying socket connection gone",
1201 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1202 return NULL;
1203 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001204 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001205
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001206 buf.obj = NULL;
1207 buf.buf = NULL;
1208 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001209 goto error;
1210
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001211 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1212 dest = PyBytes_FromStringAndSize(NULL, len);
1213 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001214 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001215 mem = PyBytes_AS_STRING(dest);
1216 }
1217 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001218 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001219 mem = buf.buf;
1220 if (len <= 0 || len > buf.len) {
1221 len = (int) buf.len;
1222 if (buf.len != len) {
1223 PyErr_SetString(PyExc_OverflowError,
1224 "maximum length can't fit in a C 'int'");
1225 goto error;
1226 }
1227 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001228 }
1229
1230 /* just in case the blocking state of the socket has been changed */
1231 nonblocking = (sock->sock_timeout >= 0.0);
1232 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1233 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1234
1235 /* first check if there are bytes ready to be read */
1236 PySSL_BEGIN_ALLOW_THREADS
1237 count = SSL_pending(self->ssl);
1238 PySSL_END_ALLOW_THREADS
1239
1240 if (!count) {
1241 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1242 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001243 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001244 "The read operation timed out");
1245 goto error;
1246 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1247 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001248 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001249 goto error;
1250 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1251 count = 0;
1252 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001253 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001254 }
1255 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001256 PySSL_BEGIN_ALLOW_THREADS
1257 count = SSL_read(self->ssl, mem, len);
1258 err = SSL_get_error(self->ssl, count);
1259 PySSL_END_ALLOW_THREADS
1260 if (PyErr_CheckSignals())
1261 goto error;
1262 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001263 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001264 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001265 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001266 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1267 (SSL_get_shutdown(self->ssl) ==
1268 SSL_RECEIVED_SHUTDOWN))
1269 {
1270 count = 0;
1271 goto done;
1272 } else {
1273 sockstate = SOCKET_OPERATION_OK;
1274 }
1275 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001276 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001277 "The read operation timed out");
1278 goto error;
1279 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1280 break;
1281 }
1282 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1283 if (count <= 0) {
1284 PySSL_SetError(self, count, __FILE__, __LINE__);
1285 goto error;
1286 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001287
1288done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001289 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001290 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001291 _PyBytes_Resize(&dest, count);
1292 return dest;
1293 }
1294 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001295 PyBuffer_Release(&buf);
1296 return PyLong_FromLong(count);
1297 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001298
1299error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001300 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001301 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001302 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001303 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001304 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001305 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001306}
1307
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001308PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001309"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001310\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001311Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001312
Antoine Pitrou152efa22010-05-16 18:19:27 +00001313static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001314{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001315 int err, ssl_err, sockstate, nonblocking;
1316 int zeros = 0;
1317 PySocketSockObject *sock
1318 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001319
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001320 /* Guard against closed socket */
1321 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1322 _setSSLError("Underlying socket connection gone",
1323 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1324 return NULL;
1325 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001326 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001327
1328 /* Just in case the blocking state of the socket has been changed */
1329 nonblocking = (sock->sock_timeout >= 0.0);
1330 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1331 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1332
1333 while (1) {
1334 PySSL_BEGIN_ALLOW_THREADS
1335 /* Disable read-ahead so that unwrap can work correctly.
1336 * Otherwise OpenSSL might read in too much data,
1337 * eating clear text data that happens to be
1338 * transmitted after the SSL shutdown.
1339 * Should be safe to call repeatedly everytime this
1340 * function is used and the shutdown_seen_zero != 0
1341 * condition is met.
1342 */
1343 if (self->shutdown_seen_zero)
1344 SSL_set_read_ahead(self->ssl, 0);
1345 err = SSL_shutdown(self->ssl);
1346 PySSL_END_ALLOW_THREADS
1347 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1348 if (err > 0)
1349 break;
1350 if (err == 0) {
1351 /* Don't loop endlessly; instead preserve legacy
1352 behaviour of trying SSL_shutdown() only twice.
1353 This looks necessary for OpenSSL < 0.9.8m */
1354 if (++zeros > 1)
1355 break;
1356 /* Shutdown was sent, now try receiving */
1357 self->shutdown_seen_zero = 1;
1358 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001359 }
1360
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001361 /* Possibly retry shutdown until timeout or failure */
1362 ssl_err = SSL_get_error(self->ssl, err);
1363 if (ssl_err == SSL_ERROR_WANT_READ)
1364 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1365 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1366 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1367 else
1368 break;
1369 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1370 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001371 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001372 "The read operation timed out");
1373 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001374 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001375 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001376 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001377 }
1378 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1379 PyErr_SetString(PySSLErrorObject,
1380 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001381 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001382 }
1383 else if (sockstate != SOCKET_OPERATION_OK)
1384 /* Retain the SSL error code */
1385 break;
1386 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001387
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001388 if (err < 0) {
1389 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001390 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001391 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001392 else
1393 /* It's already INCREF'ed */
1394 return (PyObject *) sock;
1395
1396error:
1397 Py_DECREF(sock);
1398 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001399}
1400
1401PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1402"shutdown(s) -> socket\n\
1403\n\
1404Does the SSL shutdown handshake with the remote end, and returns\n\
1405the underlying socket object.");
1406
Antoine Pitroud6494802011-07-21 01:11:30 +02001407#if HAVE_OPENSSL_FINISHED
1408static PyObject *
1409PySSL_tls_unique_cb(PySSLSocket *self)
1410{
1411 PyObject *retval = NULL;
1412 char buf[PySSL_CB_MAXLEN];
1413 int len;
1414
1415 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1416 /* if session is resumed XOR we are the client */
1417 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1418 }
1419 else {
1420 /* if a new session XOR we are the server */
1421 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1422 }
1423
1424 /* It cannot be negative in current OpenSSL version as of July 2011 */
1425 assert(len >= 0);
1426 if (len == 0)
1427 Py_RETURN_NONE;
1428
1429 retval = PyBytes_FromStringAndSize(buf, len);
1430
1431 return retval;
1432}
1433
1434PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1435"tls_unique_cb() -> bytes\n\
1436\n\
1437Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1438\n\
1439If the TLS handshake is not yet complete, None is returned");
1440
1441#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001442
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001443static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001444 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1445 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1446 PySSL_SSLwrite_doc},
1447 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1448 PySSL_SSLread_doc},
1449 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1450 PySSL_SSLpending_doc},
1451 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1452 PySSL_peercert_doc},
1453 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1454 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1455 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001456#if HAVE_OPENSSL_FINISHED
1457 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1458 PySSL_tls_unique_cb_doc},
1459#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001460 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001461};
1462
Antoine Pitrou152efa22010-05-16 18:19:27 +00001463static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001464 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001465 "_ssl._SSLSocket", /*tp_name*/
1466 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001467 0, /*tp_itemsize*/
1468 /* methods */
1469 (destructor)PySSL_dealloc, /*tp_dealloc*/
1470 0, /*tp_print*/
1471 0, /*tp_getattr*/
1472 0, /*tp_setattr*/
1473 0, /*tp_reserved*/
1474 0, /*tp_repr*/
1475 0, /*tp_as_number*/
1476 0, /*tp_as_sequence*/
1477 0, /*tp_as_mapping*/
1478 0, /*tp_hash*/
1479 0, /*tp_call*/
1480 0, /*tp_str*/
1481 0, /*tp_getattro*/
1482 0, /*tp_setattro*/
1483 0, /*tp_as_buffer*/
1484 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1485 0, /*tp_doc*/
1486 0, /*tp_traverse*/
1487 0, /*tp_clear*/
1488 0, /*tp_richcompare*/
1489 0, /*tp_weaklistoffset*/
1490 0, /*tp_iter*/
1491 0, /*tp_iternext*/
1492 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001493};
1494
Antoine Pitrou152efa22010-05-16 18:19:27 +00001495
1496/*
1497 * _SSLContext objects
1498 */
1499
1500static PyObject *
1501context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1502{
1503 char *kwlist[] = {"protocol", NULL};
1504 PySSLContext *self;
1505 int proto_version = PY_SSL_VERSION_SSL23;
1506 SSL_CTX *ctx = NULL;
1507
1508 if (!PyArg_ParseTupleAndKeywords(
1509 args, kwds, "i:_SSLContext", kwlist,
1510 &proto_version))
1511 return NULL;
1512
1513 PySSL_BEGIN_ALLOW_THREADS
1514 if (proto_version == PY_SSL_VERSION_TLS1)
1515 ctx = SSL_CTX_new(TLSv1_method());
1516 else if (proto_version == PY_SSL_VERSION_SSL3)
1517 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001518#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001519 else if (proto_version == PY_SSL_VERSION_SSL2)
1520 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001521#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001522 else if (proto_version == PY_SSL_VERSION_SSL23)
1523 ctx = SSL_CTX_new(SSLv23_method());
1524 else
1525 proto_version = -1;
1526 PySSL_END_ALLOW_THREADS
1527
1528 if (proto_version == -1) {
1529 PyErr_SetString(PyExc_ValueError,
1530 "invalid protocol version");
1531 return NULL;
1532 }
1533 if (ctx == NULL) {
1534 PyErr_SetString(PySSLErrorObject,
1535 "failed to allocate SSL context");
1536 return NULL;
1537 }
1538
1539 assert(type != NULL && type->tp_alloc != NULL);
1540 self = (PySSLContext *) type->tp_alloc(type, 0);
1541 if (self == NULL) {
1542 SSL_CTX_free(ctx);
1543 return NULL;
1544 }
1545 self->ctx = ctx;
1546 /* Defaults */
1547 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
1548 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
1549
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001550#define SID_CTX "Python"
1551 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1552 sizeof(SID_CTX));
1553#undef SID_CTX
1554
Antoine Pitrou152efa22010-05-16 18:19:27 +00001555 return (PyObject *)self;
1556}
1557
1558static void
1559context_dealloc(PySSLContext *self)
1560{
1561 SSL_CTX_free(self->ctx);
1562 Py_TYPE(self)->tp_free(self);
1563}
1564
1565static PyObject *
1566set_ciphers(PySSLContext *self, PyObject *args)
1567{
1568 int ret;
1569 const char *cipherlist;
1570
1571 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1572 return NULL;
1573 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1574 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001575 /* Clearing the error queue is necessary on some OpenSSL versions,
1576 otherwise the error will be reported again when another SSL call
1577 is done. */
1578 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001579 PyErr_SetString(PySSLErrorObject,
1580 "No cipher can be selected.");
1581 return NULL;
1582 }
1583 Py_RETURN_NONE;
1584}
1585
1586static PyObject *
1587get_verify_mode(PySSLContext *self, void *c)
1588{
1589 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1590 case SSL_VERIFY_NONE:
1591 return PyLong_FromLong(PY_SSL_CERT_NONE);
1592 case SSL_VERIFY_PEER:
1593 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1594 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1595 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1596 }
1597 PyErr_SetString(PySSLErrorObject,
1598 "invalid return value from SSL_CTX_get_verify_mode");
1599 return NULL;
1600}
1601
1602static int
1603set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1604{
1605 int n, mode;
1606 if (!PyArg_Parse(arg, "i", &n))
1607 return -1;
1608 if (n == PY_SSL_CERT_NONE)
1609 mode = SSL_VERIFY_NONE;
1610 else if (n == PY_SSL_CERT_OPTIONAL)
1611 mode = SSL_VERIFY_PEER;
1612 else if (n == PY_SSL_CERT_REQUIRED)
1613 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1614 else {
1615 PyErr_SetString(PyExc_ValueError,
1616 "invalid value for verify_mode");
1617 return -1;
1618 }
1619 SSL_CTX_set_verify(self->ctx, mode, NULL);
1620 return 0;
1621}
1622
1623static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001624get_options(PySSLContext *self, void *c)
1625{
1626 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1627}
1628
1629static int
1630set_options(PySSLContext *self, PyObject *arg, void *c)
1631{
1632 long new_opts, opts, set, clear;
1633 if (!PyArg_Parse(arg, "l", &new_opts))
1634 return -1;
1635 opts = SSL_CTX_get_options(self->ctx);
1636 clear = opts & ~new_opts;
1637 set = ~opts & new_opts;
1638 if (clear) {
1639#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1640 SSL_CTX_clear_options(self->ctx, clear);
1641#else
1642 PyErr_SetString(PyExc_ValueError,
1643 "can't clear options before OpenSSL 0.9.8m");
1644 return -1;
1645#endif
1646 }
1647 if (set)
1648 SSL_CTX_set_options(self->ctx, set);
1649 return 0;
1650}
1651
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001652typedef struct {
1653 PyThreadState *thread_state;
1654 PyObject *callable;
1655 char *password;
1656 Py_ssize_t size;
1657 int error;
1658} _PySSLPasswordInfo;
1659
1660static int
1661_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
1662 const char *bad_type_error)
1663{
1664 /* Set the password and size fields of a _PySSLPasswordInfo struct
1665 from a unicode, bytes, or byte array object.
1666 The password field will be dynamically allocated and must be freed
1667 by the caller */
1668 PyObject *password_bytes = NULL;
1669 const char *data = NULL;
1670 Py_ssize_t size;
1671
1672 if (PyUnicode_Check(password)) {
1673 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
1674 if (!password_bytes) {
1675 goto error;
1676 }
1677 data = PyBytes_AS_STRING(password_bytes);
1678 size = PyBytes_GET_SIZE(password_bytes);
1679 } else if (PyBytes_Check(password)) {
1680 data = PyBytes_AS_STRING(password);
1681 size = PyBytes_GET_SIZE(password);
1682 } else if (PyByteArray_Check(password)) {
1683 data = PyByteArray_AS_STRING(password);
1684 size = PyByteArray_GET_SIZE(password);
1685 } else {
1686 PyErr_SetString(PyExc_TypeError, bad_type_error);
1687 goto error;
1688 }
1689
1690 free(pw_info->password);
1691 pw_info->password = malloc(size);
1692 if (!pw_info->password) {
1693 PyErr_SetString(PyExc_MemoryError,
1694 "unable to allocate password buffer");
1695 goto error;
1696 }
1697 memcpy(pw_info->password, data, size);
1698 pw_info->size = size;
1699
1700 Py_XDECREF(password_bytes);
1701 return 1;
1702
1703error:
1704 Py_XDECREF(password_bytes);
1705 return 0;
1706}
1707
1708static int
1709_password_callback(char *buf, int size, int rwflag, void *userdata)
1710{
1711 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
1712 PyObject *fn_ret = NULL;
1713
1714 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
1715
1716 if (pw_info->callable) {
1717 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
1718 if (!fn_ret) {
1719 /* TODO: It would be nice to move _ctypes_add_traceback() into the
1720 core python API, so we could use it to add a frame here */
1721 goto error;
1722 }
1723
1724 if (!_pwinfo_set(pw_info, fn_ret,
1725 "password callback must return a string")) {
1726 goto error;
1727 }
1728 Py_CLEAR(fn_ret);
1729 }
1730
1731 if (pw_info->size > size) {
1732 PyErr_Format(PyExc_ValueError,
1733 "password cannot be longer than %d bytes", size);
1734 goto error;
1735 }
1736
1737 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
1738 memcpy(buf, pw_info->password, pw_info->size);
1739 return pw_info->size;
1740
1741error:
1742 Py_XDECREF(fn_ret);
1743 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
1744 pw_info->error = 1;
1745 return -1;
1746}
1747
Antoine Pitroub5218772010-05-21 09:56:06 +00001748static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001749load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
1750{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001751 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
1752 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001753 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001754 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
1755 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
1756 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00001757 int r;
1758
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001759 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00001760 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001761 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001762 "O|OO:load_cert_chain", kwlist,
1763 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00001764 return NULL;
1765 if (keyfile == Py_None)
1766 keyfile = NULL;
1767 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
1768 PyErr_SetString(PyExc_TypeError,
1769 "certfile should be a valid filesystem path");
1770 return NULL;
1771 }
1772 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
1773 PyErr_SetString(PyExc_TypeError,
1774 "keyfile should be a valid filesystem path");
1775 goto error;
1776 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001777 if (password && password != Py_None) {
1778 if (PyCallable_Check(password)) {
1779 pw_info.callable = password;
1780 } else if (!_pwinfo_set(&pw_info, password,
1781 "password should be a string or callable")) {
1782 goto error;
1783 }
1784 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
1785 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
1786 }
1787 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001788 r = SSL_CTX_use_certificate_chain_file(self->ctx,
1789 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001790 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001791 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001792 if (pw_info.error) {
1793 ERR_clear_error();
1794 /* the password callback has already set the error information */
1795 }
1796 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001797 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001798 PyErr_SetFromErrno(PyExc_IOError);
1799 }
1800 else {
1801 _setSSLError(NULL, 0, __FILE__, __LINE__);
1802 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001803 goto error;
1804 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001805 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02001806 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001807 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
1808 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001809 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
1810 Py_CLEAR(keyfile_bytes);
1811 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001812 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001813 if (pw_info.error) {
1814 ERR_clear_error();
1815 /* the password callback has already set the error information */
1816 }
1817 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001818 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001819 PyErr_SetFromErrno(PyExc_IOError);
1820 }
1821 else {
1822 _setSSLError(NULL, 0, __FILE__, __LINE__);
1823 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001824 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001825 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001826 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001827 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001828 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001829 if (r != 1) {
1830 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001831 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001832 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001833 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
1834 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
1835 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001836 Py_RETURN_NONE;
1837
1838error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001839 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
1840 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
1841 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001842 Py_XDECREF(keyfile_bytes);
1843 Py_XDECREF(certfile_bytes);
1844 return NULL;
1845}
1846
1847static PyObject *
1848load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
1849{
1850 char *kwlist[] = {"cafile", "capath", NULL};
1851 PyObject *cafile = NULL, *capath = NULL;
1852 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
1853 const char *cafile_buf = NULL, *capath_buf = NULL;
1854 int r;
1855
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001856 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001857 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1858 "|OO:load_verify_locations", kwlist,
1859 &cafile, &capath))
1860 return NULL;
1861 if (cafile == Py_None)
1862 cafile = NULL;
1863 if (capath == Py_None)
1864 capath = NULL;
1865 if (cafile == NULL && capath == NULL) {
1866 PyErr_SetString(PyExc_TypeError,
1867 "cafile and capath cannot be both omitted");
1868 return NULL;
1869 }
1870 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
1871 PyErr_SetString(PyExc_TypeError,
1872 "cafile should be a valid filesystem path");
1873 return NULL;
1874 }
1875 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00001876 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001877 PyErr_SetString(PyExc_TypeError,
1878 "capath should be a valid filesystem path");
1879 return NULL;
1880 }
1881 if (cafile)
1882 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
1883 if (capath)
1884 capath_buf = PyBytes_AS_STRING(capath_bytes);
1885 PySSL_BEGIN_ALLOW_THREADS
1886 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
1887 PySSL_END_ALLOW_THREADS
1888 Py_XDECREF(cafile_bytes);
1889 Py_XDECREF(capath_bytes);
1890 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001891 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001892 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001893 PyErr_SetFromErrno(PyExc_IOError);
1894 }
1895 else {
1896 _setSSLError(NULL, 0, __FILE__, __LINE__);
1897 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001898 return NULL;
1899 }
1900 Py_RETURN_NONE;
1901}
1902
1903static PyObject *
1904context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
1905{
Antoine Pitroud5323212010-10-22 18:19:07 +00001906 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00001907 PySocketSockObject *sock;
1908 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00001909 char *hostname = NULL;
1910 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001911
Antoine Pitroud5323212010-10-22 18:19:07 +00001912 /* server_hostname is either None (or absent), or to be encoded
1913 using the idna encoding. */
1914 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001915 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00001916 &sock, &server_side,
1917 Py_TYPE(Py_None), &hostname_obj)) {
1918 PyErr_Clear();
1919 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
1920 PySocketModule.Sock_Type,
1921 &sock, &server_side,
1922 "idna", &hostname))
1923 return NULL;
1924#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
1925 PyMem_Free(hostname);
1926 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
1927 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00001928 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00001929#endif
1930 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001931
Antoine Pitroud5323212010-10-22 18:19:07 +00001932 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
1933 hostname);
1934 if (hostname != NULL)
1935 PyMem_Free(hostname);
1936 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001937}
1938
Antoine Pitroub0182c82010-10-12 20:09:02 +00001939static PyObject *
1940session_stats(PySSLContext *self, PyObject *unused)
1941{
1942 int r;
1943 PyObject *value, *stats = PyDict_New();
1944 if (!stats)
1945 return NULL;
1946
1947#define ADD_STATS(SSL_NAME, KEY_NAME) \
1948 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
1949 if (value == NULL) \
1950 goto error; \
1951 r = PyDict_SetItemString(stats, KEY_NAME, value); \
1952 Py_DECREF(value); \
1953 if (r < 0) \
1954 goto error;
1955
1956 ADD_STATS(number, "number");
1957 ADD_STATS(connect, "connect");
1958 ADD_STATS(connect_good, "connect_good");
1959 ADD_STATS(connect_renegotiate, "connect_renegotiate");
1960 ADD_STATS(accept, "accept");
1961 ADD_STATS(accept_good, "accept_good");
1962 ADD_STATS(accept_renegotiate, "accept_renegotiate");
1963 ADD_STATS(accept, "accept");
1964 ADD_STATS(hits, "hits");
1965 ADD_STATS(misses, "misses");
1966 ADD_STATS(timeouts, "timeouts");
1967 ADD_STATS(cache_full, "cache_full");
1968
1969#undef ADD_STATS
1970
1971 return stats;
1972
1973error:
1974 Py_DECREF(stats);
1975 return NULL;
1976}
1977
Antoine Pitrou664c2d12010-11-17 20:29:42 +00001978static PyObject *
1979set_default_verify_paths(PySSLContext *self, PyObject *unused)
1980{
1981 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
1982 _setSSLError(NULL, 0, __FILE__, __LINE__);
1983 return NULL;
1984 }
1985 Py_RETURN_NONE;
1986}
1987
Antoine Pitrou152efa22010-05-16 18:19:27 +00001988static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00001989 {"options", (getter) get_options,
1990 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00001991 {"verify_mode", (getter) get_verify_mode,
1992 (setter) set_verify_mode, NULL},
1993 {NULL}, /* sentinel */
1994};
1995
1996static struct PyMethodDef context_methods[] = {
1997 {"_wrap_socket", (PyCFunction) context_wrap_socket,
1998 METH_VARARGS | METH_KEYWORDS, NULL},
1999 {"set_ciphers", (PyCFunction) set_ciphers,
2000 METH_VARARGS, NULL},
2001 {"load_cert_chain", (PyCFunction) load_cert_chain,
2002 METH_VARARGS | METH_KEYWORDS, NULL},
2003 {"load_verify_locations", (PyCFunction) load_verify_locations,
2004 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002005 {"session_stats", (PyCFunction) session_stats,
2006 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002007 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2008 METH_NOARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002009 {NULL, NULL} /* sentinel */
2010};
2011
2012static PyTypeObject PySSLContext_Type = {
2013 PyVarObject_HEAD_INIT(NULL, 0)
2014 "_ssl._SSLContext", /*tp_name*/
2015 sizeof(PySSLContext), /*tp_basicsize*/
2016 0, /*tp_itemsize*/
2017 (destructor)context_dealloc, /*tp_dealloc*/
2018 0, /*tp_print*/
2019 0, /*tp_getattr*/
2020 0, /*tp_setattr*/
2021 0, /*tp_reserved*/
2022 0, /*tp_repr*/
2023 0, /*tp_as_number*/
2024 0, /*tp_as_sequence*/
2025 0, /*tp_as_mapping*/
2026 0, /*tp_hash*/
2027 0, /*tp_call*/
2028 0, /*tp_str*/
2029 0, /*tp_getattro*/
2030 0, /*tp_setattro*/
2031 0, /*tp_as_buffer*/
2032 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
2033 0, /*tp_doc*/
2034 0, /*tp_traverse*/
2035 0, /*tp_clear*/
2036 0, /*tp_richcompare*/
2037 0, /*tp_weaklistoffset*/
2038 0, /*tp_iter*/
2039 0, /*tp_iternext*/
2040 context_methods, /*tp_methods*/
2041 0, /*tp_members*/
2042 context_getsetlist, /*tp_getset*/
2043 0, /*tp_base*/
2044 0, /*tp_dict*/
2045 0, /*tp_descr_get*/
2046 0, /*tp_descr_set*/
2047 0, /*tp_dictoffset*/
2048 0, /*tp_init*/
2049 0, /*tp_alloc*/
2050 context_new, /*tp_new*/
2051};
2052
2053
2054
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002055#ifdef HAVE_OPENSSL_RAND
2056
2057/* helper routines for seeding the SSL PRNG */
2058static PyObject *
2059PySSL_RAND_add(PyObject *self, PyObject *args)
2060{
2061 char *buf;
2062 int len;
2063 double entropy;
2064
2065 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002066 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002067 RAND_add(buf, len, entropy);
2068 Py_INCREF(Py_None);
2069 return Py_None;
2070}
2071
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002072PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002073"RAND_add(string, entropy)\n\
2074\n\
2075Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002076bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002077
2078static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002079PySSL_RAND(int len, int pseudo)
2080{
2081 int ok;
2082 PyObject *bytes;
2083 unsigned long err;
2084 const char *errstr;
2085 PyObject *v;
2086
2087 bytes = PyBytes_FromStringAndSize(NULL, len);
2088 if (bytes == NULL)
2089 return NULL;
2090 if (pseudo) {
2091 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2092 if (ok == 0 || ok == 1)
2093 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2094 }
2095 else {
2096 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2097 if (ok == 1)
2098 return bytes;
2099 }
2100 Py_DECREF(bytes);
2101
2102 err = ERR_get_error();
2103 errstr = ERR_reason_error_string(err);
2104 v = Py_BuildValue("(ks)", err, errstr);
2105 if (v != NULL) {
2106 PyErr_SetObject(PySSLErrorObject, v);
2107 Py_DECREF(v);
2108 }
2109 return NULL;
2110}
2111
2112static PyObject *
2113PySSL_RAND_bytes(PyObject *self, PyObject *args)
2114{
2115 int len;
2116 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2117 return NULL;
2118 return PySSL_RAND(len, 0);
2119}
2120
2121PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2122"RAND_bytes(n) -> bytes\n\
2123\n\
2124Generate n cryptographically strong pseudo-random bytes.");
2125
2126static PyObject *
2127PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2128{
2129 int len;
2130 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2131 return NULL;
2132 return PySSL_RAND(len, 1);
2133}
2134
2135PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2136"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2137\n\
2138Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2139generated are cryptographically strong.");
2140
2141static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002142PySSL_RAND_status(PyObject *self)
2143{
Christian Heimes217cfd12007-12-02 14:31:20 +00002144 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002145}
2146
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002147PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002148"RAND_status() -> 0 or 1\n\
2149\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002150Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2151It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2152using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002153
2154static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002155PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002156{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002157 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002158 int bytes;
2159
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002160 if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
2161 PyUnicode_FSConverter, &path))
2162 return NULL;
2163
2164 bytes = RAND_egd(PyBytes_AsString(path));
2165 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002166 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002167 PyErr_SetString(PySSLErrorObject,
2168 "EGD connection failed or EGD did not return "
2169 "enough data to seed the PRNG");
2170 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002171 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002172 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002173}
2174
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002175PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002176"RAND_egd(path) -> bytes\n\
2177\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002178Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2179Returns number of bytes read. Raises SSLError if connection to EGD\n\
2180fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002181
2182#endif
2183
Bill Janssen40a0f662008-08-12 16:56:25 +00002184
2185
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002186/* List of functions exported by this module. */
2187
2188static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002189 {"_test_decode_cert", PySSL_test_decode_certificate,
2190 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002191#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002192 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
2193 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02002194 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
2195 PySSL_RAND_bytes_doc},
2196 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
2197 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002198 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002199 PySSL_RAND_egd_doc},
2200 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
2201 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002202#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002203 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002204};
2205
2206
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002207#ifdef WITH_THREAD
2208
2209/* an implementation of OpenSSL threading operations in terms
2210 of the Python C thread library */
2211
2212static PyThread_type_lock *_ssl_locks = NULL;
2213
2214static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002215 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002216}
2217
Bill Janssen6e027db2007-11-15 22:23:56 +00002218static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002219 (int mode, int n, const char *file, int line) {
2220 /* this function is needed to perform locking on shared data
2221 structures. (Note that OpenSSL uses a number of global data
2222 structures that will be implicitly shared whenever multiple
2223 threads use OpenSSL.) Multi-threaded applications will
2224 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002225
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002226 locking_function() must be able to handle up to
2227 CRYPTO_num_locks() different mutex locks. It sets the n-th
2228 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002229
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002230 file and line are the file number of the function setting the
2231 lock. They can be useful for debugging.
2232 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002233
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002234 if ((_ssl_locks == NULL) ||
2235 (n < 0) || ((unsigned)n >= _ssl_locks_count))
2236 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002237
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002238 if (mode & CRYPTO_LOCK) {
2239 PyThread_acquire_lock(_ssl_locks[n], 1);
2240 } else {
2241 PyThread_release_lock(_ssl_locks[n]);
2242 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002243}
2244
2245static int _setup_ssl_threads(void) {
2246
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002247 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002248
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002249 if (_ssl_locks == NULL) {
2250 _ssl_locks_count = CRYPTO_num_locks();
2251 _ssl_locks = (PyThread_type_lock *)
2252 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2253 if (_ssl_locks == NULL)
2254 return 0;
2255 memset(_ssl_locks, 0,
2256 sizeof(PyThread_type_lock) * _ssl_locks_count);
2257 for (i = 0; i < _ssl_locks_count; i++) {
2258 _ssl_locks[i] = PyThread_allocate_lock();
2259 if (_ssl_locks[i] == NULL) {
2260 unsigned int j;
2261 for (j = 0; j < i; j++) {
2262 PyThread_free_lock(_ssl_locks[j]);
2263 }
2264 free(_ssl_locks);
2265 return 0;
2266 }
2267 }
2268 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
2269 CRYPTO_set_id_callback(_ssl_thread_id_function);
2270 }
2271 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002272}
2273
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002274#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002275
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002276PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002277"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002278for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002279
Martin v. Löwis1a214512008-06-11 05:26:20 +00002280
2281static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002282 PyModuleDef_HEAD_INIT,
2283 "_ssl",
2284 module_doc,
2285 -1,
2286 PySSL_methods,
2287 NULL,
2288 NULL,
2289 NULL,
2290 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002291};
2292
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002293
2294static void
2295parse_openssl_version(unsigned long libver,
2296 unsigned int *major, unsigned int *minor,
2297 unsigned int *fix, unsigned int *patch,
2298 unsigned int *status)
2299{
2300 *status = libver & 0xF;
2301 libver >>= 4;
2302 *patch = libver & 0xFF;
2303 libver >>= 8;
2304 *fix = libver & 0xFF;
2305 libver >>= 8;
2306 *minor = libver & 0xFF;
2307 libver >>= 8;
2308 *major = libver & 0xFF;
2309}
2310
Antoine Pitroua0e0e232011-10-22 23:41:52 +02002311PyDoc_STRVAR(SSLError_doc,
2312"An error occurred in the SSL implementation.");
2313
Antoine Pitrou41032a62011-10-27 23:56:55 +02002314PyDoc_STRVAR(SSLZeroReturnError_doc,
2315"SSL/TLS session closed cleanly.");
2316
2317PyDoc_STRVAR(SSLWantReadError_doc,
2318"Non-blocking SSL socket needs to read more data\n"
2319"before the requested operation can be completed.");
2320
2321PyDoc_STRVAR(SSLWantWriteError_doc,
2322"Non-blocking SSL socket needs to write more data\n"
2323"before the requested operation can be completed.");
2324
2325PyDoc_STRVAR(SSLSyscallError_doc,
2326"System error when attempting SSL operation.");
2327
2328PyDoc_STRVAR(SSLEOFError_doc,
2329"SSL/TLS connection terminated abruptly.");
2330
Antoine Pitroua0e0e232011-10-22 23:41:52 +02002331
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002332PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002333PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002334{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002335 PyObject *m, *d, *r;
2336 unsigned long libver;
2337 unsigned int major, minor, fix, patch, status;
2338 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002339
Antoine Pitrou152efa22010-05-16 18:19:27 +00002340 if (PyType_Ready(&PySSLContext_Type) < 0)
2341 return NULL;
2342 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002343 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002344
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002345 m = PyModule_Create(&_sslmodule);
2346 if (m == NULL)
2347 return NULL;
2348 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002349
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002350 /* Load _socket module and its C API */
2351 socket_api = PySocketModule_ImportModuleAndAPI();
2352 if (!socket_api)
2353 return NULL;
2354 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002355
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002356 /* Init OpenSSL */
2357 SSL_load_error_strings();
2358 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002359#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002360 /* note that this will start threading if not already started */
2361 if (!_setup_ssl_threads()) {
2362 return NULL;
2363 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002364#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002365 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002366
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002367 /* Add symbols to module dict */
Antoine Pitroua0e0e232011-10-22 23:41:52 +02002368 PySSLErrorObject = PyErr_NewExceptionWithDoc("ssl.SSLError",
2369 SSLError_doc,
2370 PyExc_OSError,
2371 NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002372 if (PySSLErrorObject == NULL)
2373 return NULL;
Antoine Pitrou41032a62011-10-27 23:56:55 +02002374 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
2375 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
2376 PySSLErrorObject, NULL);
2377 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
2378 "ssl.SSLWantReadError", SSLWantReadError_doc,
2379 PySSLErrorObject, NULL);
2380 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
2381 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
2382 PySSLErrorObject, NULL);
2383 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
2384 "ssl.SSLSyscallError", SSLSyscallError_doc,
2385 PySSLErrorObject, NULL);
2386 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
2387 "ssl.SSLEOFError", SSLEOFError_doc,
2388 PySSLErrorObject, NULL);
2389 if (PySSLZeroReturnErrorObject == NULL
2390 || PySSLWantReadErrorObject == NULL
2391 || PySSLWantWriteErrorObject == NULL
2392 || PySSLSyscallErrorObject == NULL
2393 || PySSLEOFErrorObject == NULL)
2394 return NULL;
2395 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
2396 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
2397 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
2398 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
2399 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
2400 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002401 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002402 if (PyDict_SetItemString(d, "_SSLContext",
2403 (PyObject *)&PySSLContext_Type) != 0)
2404 return NULL;
2405 if (PyDict_SetItemString(d, "_SSLSocket",
2406 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002407 return NULL;
2408 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2409 PY_SSL_ERROR_ZERO_RETURN);
2410 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2411 PY_SSL_ERROR_WANT_READ);
2412 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2413 PY_SSL_ERROR_WANT_WRITE);
2414 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2415 PY_SSL_ERROR_WANT_X509_LOOKUP);
2416 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2417 PY_SSL_ERROR_SYSCALL);
2418 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2419 PY_SSL_ERROR_SSL);
2420 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2421 PY_SSL_ERROR_WANT_CONNECT);
2422 /* non ssl.h errorcodes */
2423 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2424 PY_SSL_ERROR_EOF);
2425 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2426 PY_SSL_ERROR_INVALID_ERROR_CODE);
2427 /* cert requirements */
2428 PyModule_AddIntConstant(m, "CERT_NONE",
2429 PY_SSL_CERT_NONE);
2430 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2431 PY_SSL_CERT_OPTIONAL);
2432 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2433 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002434
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002435 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02002436#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002437 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2438 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02002439#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002440 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2441 PY_SSL_VERSION_SSL3);
2442 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2443 PY_SSL_VERSION_SSL23);
2444 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2445 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002446
Antoine Pitroub5218772010-05-21 09:56:06 +00002447 /* protocol options */
2448 PyModule_AddIntConstant(m, "OP_ALL", SSL_OP_ALL);
2449 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2450 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2451 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
2452
Antoine Pitroud5323212010-10-22 18:19:07 +00002453#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2454 r = Py_True;
2455#else
2456 r = Py_False;
2457#endif
2458 Py_INCREF(r);
2459 PyModule_AddObject(m, "HAS_SNI", r);
2460
Antoine Pitroud6494802011-07-21 01:11:30 +02002461#if HAVE_OPENSSL_FINISHED
2462 r = Py_True;
2463#else
2464 r = Py_False;
2465#endif
2466 Py_INCREF(r);
2467 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
2468
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002469 /* OpenSSL version */
2470 /* SSLeay() gives us the version of the library linked against,
2471 which could be different from the headers version.
2472 */
2473 libver = SSLeay();
2474 r = PyLong_FromUnsignedLong(libver);
2475 if (r == NULL)
2476 return NULL;
2477 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2478 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002479 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002480 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2481 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2482 return NULL;
2483 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2484 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2485 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002486
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002487 libver = OPENSSL_VERSION_NUMBER;
2488 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
2489 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2490 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
2491 return NULL;
2492
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002493 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002494}