blob: e1cd3dcacce030bf3a16a63575e8071f7f2aad86 [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"
21#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000022 PyThreadState *_save = NULL; \
23 if (_ssl_locks_count>0) {_save = PyEval_SaveThread();}
24#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)};
25#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()};
26#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \
27 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000028
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000029#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000030
31#define PySSL_BEGIN_ALLOW_THREADS
32#define PySSL_BLOCK_THREADS
33#define PySSL_UNBLOCK_THREADS
34#define PySSL_END_ALLOW_THREADS
35
36#endif
37
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000038enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000039 /* these mirror ssl.h */
40 PY_SSL_ERROR_NONE,
41 PY_SSL_ERROR_SSL,
42 PY_SSL_ERROR_WANT_READ,
43 PY_SSL_ERROR_WANT_WRITE,
44 PY_SSL_ERROR_WANT_X509_LOOKUP,
45 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
46 PY_SSL_ERROR_ZERO_RETURN,
47 PY_SSL_ERROR_WANT_CONNECT,
48 /* start of non ssl.h errorcodes */
49 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
50 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
51 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000052};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000053
Thomas Woutersed03b412007-08-28 21:37:11 +000054enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000055 PY_SSL_CLIENT,
56 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +000057};
58
59enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000060 PY_SSL_CERT_NONE,
61 PY_SSL_CERT_OPTIONAL,
62 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +000063};
64
65enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000066 PY_SSL_VERSION_SSL2,
67 PY_SSL_VERSION_SSL3,
68 PY_SSL_VERSION_SSL23,
69 PY_SSL_VERSION_TLS1
Thomas Woutersed03b412007-08-28 21:37:11 +000070};
71
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000072/* Include symbols from _socket module */
73#include "socketmodule.h"
74
Benjamin Petersonb173f782009-05-05 22:31:58 +000075static PySocketModule_APIObject PySocketModule;
76
Thomas Woutersed03b412007-08-28 21:37:11 +000077#if defined(HAVE_POLL_H)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000078#include <poll.h>
79#elif defined(HAVE_SYS_POLL_H)
80#include <sys/poll.h>
81#endif
82
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000083/* Include OpenSSL header files */
84#include "openssl/rsa.h"
85#include "openssl/crypto.h"
86#include "openssl/x509.h"
Thomas Wouters1b7f8912007-09-19 03:06:30 +000087#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000088#include "openssl/pem.h"
89#include "openssl/ssl.h"
90#include "openssl/err.h"
91#include "openssl/rand.h"
92
93/* SSL error object */
94static PyObject *PySSLErrorObject;
95
Thomas Wouters1b7f8912007-09-19 03:06:30 +000096#ifdef WITH_THREAD
97
98/* serves as a flag to see whether we've initialized the SSL thread support. */
99/* 0 means no, greater than 0 means yes */
100
101static unsigned int _ssl_locks_count = 0;
102
103#endif /* def WITH_THREAD */
104
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000105/* SSL socket object */
106
107#define X509_NAME_MAXLEN 256
108
109/* RAND_* APIs got added to OpenSSL in 0.9.5 */
110#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
111# define HAVE_OPENSSL_RAND 1
112#else
113# undef HAVE_OPENSSL_RAND
114#endif
115
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000116/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
117 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
118 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
119#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000120# define HAVE_SSL_CTX_CLEAR_OPTIONS
121#else
122# undef HAVE_SSL_CTX_CLEAR_OPTIONS
123#endif
124
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000125typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000126 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000127 SSL_CTX *ctx;
128} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000129
Antoine Pitrou152efa22010-05-16 18:19:27 +0000130typedef struct {
131 PyObject_HEAD
132 PyObject *Socket; /* weakref to socket on which we're layered */
133 SSL *ssl;
134 X509 *peer_cert;
135 int shutdown_seen_zero;
136} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000137
Antoine Pitrou152efa22010-05-16 18:19:27 +0000138static PyTypeObject PySSLContext_Type;
139static PyTypeObject PySSLSocket_Type;
140
141static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
142static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000143static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000144 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000145static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
146static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000147
Antoine Pitrou152efa22010-05-16 18:19:27 +0000148#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
149#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000150
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000151typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000152 SOCKET_IS_NONBLOCKING,
153 SOCKET_IS_BLOCKING,
154 SOCKET_HAS_TIMED_OUT,
155 SOCKET_HAS_BEEN_CLOSED,
156 SOCKET_TOO_LARGE_FOR_SELECT,
157 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000158} timeout_state;
159
Thomas Woutersed03b412007-08-28 21:37:11 +0000160/* Wrap error strings with filename and line # */
161#define STRINGIFY1(x) #x
162#define STRINGIFY2(x) STRINGIFY1(x)
163#define ERRSTR1(x,y,z) (x ":" y ": " z)
164#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
165
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000166/* XXX It might be helpful to augment the error message generated
167 below with the name of the SSL function that generated the error.
168 I expect it's obvious most of the time.
169*/
170
171static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000172PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000173{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000174 PyObject *v;
175 char buf[2048];
176 char *errstr;
177 int err;
178 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000179
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000180 assert(ret <= 0);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000181
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000182 if (obj->ssl != NULL) {
183 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000184
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000185 switch (err) {
186 case SSL_ERROR_ZERO_RETURN:
187 errstr = "TLS/SSL connection has been closed";
188 p = PY_SSL_ERROR_ZERO_RETURN;
189 break;
190 case SSL_ERROR_WANT_READ:
191 errstr = "The operation did not complete (read)";
192 p = PY_SSL_ERROR_WANT_READ;
193 break;
194 case SSL_ERROR_WANT_WRITE:
195 p = PY_SSL_ERROR_WANT_WRITE;
196 errstr = "The operation did not complete (write)";
197 break;
198 case SSL_ERROR_WANT_X509_LOOKUP:
199 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000200 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000201 break;
202 case SSL_ERROR_WANT_CONNECT:
203 p = PY_SSL_ERROR_WANT_CONNECT;
204 errstr = "The operation did not complete (connect)";
205 break;
206 case SSL_ERROR_SYSCALL:
207 {
208 unsigned long e = ERR_get_error();
209 if (e == 0) {
210 PySocketSockObject *s
211 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
212 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000213 p = PY_SSL_ERROR_EOF;
214 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000215 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000216 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000217 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000218 ERR_clear_error();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000219 v = s->errorhandler();
220 Py_DECREF(s);
221 return v;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000222 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000223 p = PY_SSL_ERROR_SYSCALL;
224 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000225 }
226 } else {
227 p = PY_SSL_ERROR_SYSCALL;
228 /* XXX Protected by global interpreter lock */
229 errstr = ERR_error_string(e, NULL);
230 }
231 break;
232 }
233 case SSL_ERROR_SSL:
234 {
235 unsigned long e = ERR_get_error();
236 p = PY_SSL_ERROR_SSL;
237 if (e != 0)
238 /* XXX Protected by global interpreter lock */
239 errstr = ERR_error_string(e, NULL);
240 else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000241 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000242 }
243 break;
244 }
245 default:
246 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
247 errstr = "Invalid error code";
248 }
249 } else {
250 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
251 }
252 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000253 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000254 v = Py_BuildValue("(is)", p, buf);
255 if (v != NULL) {
256 PyErr_SetObject(PySSLErrorObject, v);
257 Py_DECREF(v);
258 }
259 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000260}
261
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000262static PyObject *
263_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
264
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000265 char buf[2048];
266 PyObject *v;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000267
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000268 if (errstr == NULL) {
269 errcode = ERR_peek_last_error();
270 errstr = ERR_error_string(errcode, NULL);
271 }
272 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000273 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000274 v = Py_BuildValue("(is)", errcode, buf);
275 if (v != NULL) {
276 PyErr_SetObject(PySSLErrorObject, v);
277 Py_DECREF(v);
278 }
279 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000280}
281
Antoine Pitrou152efa22010-05-16 18:19:27 +0000282static PySSLSocket *
283newPySSLSocket(SSL_CTX *ctx, PySocketSockObject *sock,
284 enum py_ssl_server_or_client socket_type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000285{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000286 PySSLSocket *self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000287
Antoine Pitrou152efa22010-05-16 18:19:27 +0000288 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000289 if (self == NULL)
290 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000291
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000292 self->peer_cert = NULL;
293 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000294 self->Socket = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000295
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000296 /* Make sure the SSL error state is initialized */
297 (void) ERR_get_state();
298 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000299
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000300 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000301 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000302 PySSL_END_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000303 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000304#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000305 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000306#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000307
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000308 /* If the socket is in non-blocking mode or timeout mode, set the BIO
309 * to non-blocking mode (blocking is the default)
310 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000311 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000312 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
313 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
314 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000315
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000316 PySSL_BEGIN_ALLOW_THREADS
317 if (socket_type == PY_SSL_CLIENT)
318 SSL_set_connect_state(self->ssl);
319 else
320 SSL_set_accept_state(self->ssl);
321 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000322
Antoine Pitrou152efa22010-05-16 18:19:27 +0000323 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000324 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000325}
326
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000327/* SSL object methods */
328
Antoine Pitrou152efa22010-05-16 18:19:27 +0000329static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000330{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000331 int ret;
332 int err;
333 int sockstate, nonblocking;
334 PySocketSockObject *sock
335 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000336
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000337 if (((PyObject*)sock) == Py_None) {
338 _setSSLError("Underlying socket connection gone",
339 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
340 return NULL;
341 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000342 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000343
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000344 /* just in case the blocking state of the socket has been changed */
345 nonblocking = (sock->sock_timeout >= 0.0);
346 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
347 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000348
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000349 /* Actually negotiate SSL connection */
350 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
351 sockstate = 0;
352 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000353 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000354 ret = SSL_do_handshake(self->ssl);
355 err = SSL_get_error(self->ssl, ret);
356 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000357 if (PyErr_CheckSignals())
358 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000359 if (err == SSL_ERROR_WANT_READ) {
360 sockstate = check_socket_and_wait_for_timeout(sock, 0);
361 } else if (err == SSL_ERROR_WANT_WRITE) {
362 sockstate = check_socket_and_wait_for_timeout(sock, 1);
363 } else {
364 sockstate = SOCKET_OPERATION_OK;
365 }
366 if (sockstate == SOCKET_HAS_TIMED_OUT) {
367 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000368 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000369 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000370 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
371 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000372 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000373 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000374 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
375 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000376 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000377 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000378 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
379 break;
380 }
381 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000382 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000383 if (ret < 1)
384 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000385
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000386 if (self->peer_cert)
387 X509_free (self->peer_cert);
388 PySSL_BEGIN_ALLOW_THREADS
389 self->peer_cert = SSL_get_peer_certificate(self->ssl);
390 PySSL_END_ALLOW_THREADS
391
392 Py_INCREF(Py_None);
393 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000394
395error:
396 Py_DECREF(sock);
397 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000398}
399
Thomas Woutersed03b412007-08-28 21:37:11 +0000400static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000401_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000402
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000403 char namebuf[X509_NAME_MAXLEN];
404 int buflen;
405 PyObject *name_obj;
406 PyObject *value_obj;
407 PyObject *attr;
408 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000409
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000410 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
411 if (buflen < 0) {
412 _setSSLError(NULL, 0, __FILE__, __LINE__);
413 goto fail;
414 }
415 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
416 if (name_obj == NULL)
417 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000418
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000419 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
420 if (buflen < 0) {
421 _setSSLError(NULL, 0, __FILE__, __LINE__);
422 Py_DECREF(name_obj);
423 goto fail;
424 }
425 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000426 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000427 OPENSSL_free(valuebuf);
428 if (value_obj == NULL) {
429 Py_DECREF(name_obj);
430 goto fail;
431 }
432 attr = PyTuple_New(2);
433 if (attr == NULL) {
434 Py_DECREF(name_obj);
435 Py_DECREF(value_obj);
436 goto fail;
437 }
438 PyTuple_SET_ITEM(attr, 0, name_obj);
439 PyTuple_SET_ITEM(attr, 1, value_obj);
440 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000441
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000442 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000443 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000444}
445
446static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000447_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000448{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000449 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
450 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
451 PyObject *rdnt;
452 PyObject *attr = NULL; /* tuple to hold an attribute */
453 int entry_count = X509_NAME_entry_count(xname);
454 X509_NAME_ENTRY *entry;
455 ASN1_OBJECT *name;
456 ASN1_STRING *value;
457 int index_counter;
458 int rdn_level = -1;
459 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000460
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000461 dn = PyList_New(0);
462 if (dn == NULL)
463 return NULL;
464 /* now create another tuple to hold the top-level RDN */
465 rdn = PyList_New(0);
466 if (rdn == NULL)
467 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000468
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000469 for (index_counter = 0;
470 index_counter < entry_count;
471 index_counter++)
472 {
473 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000474
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000475 /* check to see if we've gotten to a new RDN */
476 if (rdn_level >= 0) {
477 if (rdn_level != entry->set) {
478 /* yes, new RDN */
479 /* add old RDN to DN */
480 rdnt = PyList_AsTuple(rdn);
481 Py_DECREF(rdn);
482 if (rdnt == NULL)
483 goto fail0;
484 retcode = PyList_Append(dn, rdnt);
485 Py_DECREF(rdnt);
486 if (retcode < 0)
487 goto fail0;
488 /* create new RDN */
489 rdn = PyList_New(0);
490 if (rdn == NULL)
491 goto fail0;
492 }
493 }
494 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000495
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000496 /* now add this attribute to the current RDN */
497 name = X509_NAME_ENTRY_get_object(entry);
498 value = X509_NAME_ENTRY_get_data(entry);
499 attr = _create_tuple_for_attribute(name, value);
500 /*
501 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
502 entry->set,
503 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
504 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
505 */
506 if (attr == NULL)
507 goto fail1;
508 retcode = PyList_Append(rdn, attr);
509 Py_DECREF(attr);
510 if (retcode < 0)
511 goto fail1;
512 }
513 /* now, there's typically a dangling RDN */
514 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
515 rdnt = PyList_AsTuple(rdn);
516 Py_DECREF(rdn);
517 if (rdnt == NULL)
518 goto fail0;
519 retcode = PyList_Append(dn, rdnt);
520 Py_DECREF(rdnt);
521 if (retcode < 0)
522 goto fail0;
523 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000524
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000525 /* convert list to tuple */
526 rdnt = PyList_AsTuple(dn);
527 Py_DECREF(dn);
528 if (rdnt == NULL)
529 return NULL;
530 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000531
532 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000533 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000534
535 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000536 Py_XDECREF(dn);
537 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000538}
539
540static PyObject *
541_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000542
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000543 /* this code follows the procedure outlined in
544 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
545 function to extract the STACK_OF(GENERAL_NAME),
546 then iterates through the stack to add the
547 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000548
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000549 int i, j;
550 PyObject *peer_alt_names = Py_None;
551 PyObject *v, *t;
552 X509_EXTENSION *ext = NULL;
553 GENERAL_NAMES *names = NULL;
554 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000555 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000556 BIO *biobuf = NULL;
557 char buf[2048];
558 char *vptr;
559 int len;
560 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000561#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000562 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000563#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000564 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000565#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000566
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000567 if (certificate == NULL)
568 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000569
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000570 /* get a memory buffer */
571 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000572
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000573 i = 0;
574 while ((i = X509_get_ext_by_NID(
575 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000576
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000577 if (peer_alt_names == Py_None) {
578 peer_alt_names = PyList_New(0);
579 if (peer_alt_names == NULL)
580 goto fail;
581 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000582
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000583 /* now decode the altName */
584 ext = X509_get_ext(certificate, i);
585 if(!(method = X509V3_EXT_get(ext))) {
586 PyErr_SetString
587 (PySSLErrorObject,
588 ERRSTR("No method for internalizing subjectAltName!"));
589 goto fail;
590 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000591
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000592 p = ext->value->data;
593 if (method->it)
594 names = (GENERAL_NAMES*)
595 (ASN1_item_d2i(NULL,
596 &p,
597 ext->value->length,
598 ASN1_ITEM_ptr(method->it)));
599 else
600 names = (GENERAL_NAMES*)
601 (method->d2i(NULL,
602 &p,
603 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000604
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000605 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000606
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000607 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000608
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000609 name = sk_GENERAL_NAME_value(names, j);
610 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000611
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000612 /* we special-case DirName as a tuple of
613 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000614
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000615 t = PyTuple_New(2);
616 if (t == NULL) {
617 goto fail;
618 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000619
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000620 v = PyUnicode_FromString("DirName");
621 if (v == NULL) {
622 Py_DECREF(t);
623 goto fail;
624 }
625 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000626
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000627 v = _create_tuple_for_X509_NAME (name->d.dirn);
628 if (v == NULL) {
629 Py_DECREF(t);
630 goto fail;
631 }
632 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000633
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000634 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000635
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000636 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000637
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000638 (void) BIO_reset(biobuf);
639 GENERAL_NAME_print(biobuf, name);
640 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
641 if (len < 0) {
642 _setSSLError(NULL, 0, __FILE__, __LINE__);
643 goto fail;
644 }
645 vptr = strchr(buf, ':');
646 if (vptr == NULL)
647 goto fail;
648 t = PyTuple_New(2);
649 if (t == NULL)
650 goto fail;
651 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
652 if (v == NULL) {
653 Py_DECREF(t);
654 goto fail;
655 }
656 PyTuple_SET_ITEM(t, 0, v);
657 v = PyUnicode_FromStringAndSize((vptr + 1),
658 (len - (vptr - buf + 1)));
659 if (v == NULL) {
660 Py_DECREF(t);
661 goto fail;
662 }
663 PyTuple_SET_ITEM(t, 1, v);
664 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000665
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000666 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000667
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000668 if (PyList_Append(peer_alt_names, t) < 0) {
669 Py_DECREF(t);
670 goto fail;
671 }
672 Py_DECREF(t);
673 }
674 }
675 BIO_free(biobuf);
676 if (peer_alt_names != Py_None) {
677 v = PyList_AsTuple(peer_alt_names);
678 Py_DECREF(peer_alt_names);
679 return v;
680 } else {
681 return peer_alt_names;
682 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000683
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000684
685 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000686 if (biobuf != NULL)
687 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000688
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000689 if (peer_alt_names != Py_None) {
690 Py_XDECREF(peer_alt_names);
691 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000692
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000693 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000694}
695
696static PyObject *
697_decode_certificate (X509 *certificate, int verbose) {
698
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000699 PyObject *retval = NULL;
700 BIO *biobuf = NULL;
701 PyObject *peer;
702 PyObject *peer_alt_names = NULL;
703 PyObject *issuer;
704 PyObject *version;
705 PyObject *sn_obj;
706 ASN1_INTEGER *serialNumber;
707 char buf[2048];
708 int len;
709 ASN1_TIME *notBefore, *notAfter;
710 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000711
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000712 retval = PyDict_New();
713 if (retval == NULL)
714 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000715
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000716 peer = _create_tuple_for_X509_NAME(
717 X509_get_subject_name(certificate));
718 if (peer == NULL)
719 goto fail0;
720 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
721 Py_DECREF(peer);
722 goto fail0;
723 }
724 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000725
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000726 if (verbose) {
727 issuer = _create_tuple_for_X509_NAME(
728 X509_get_issuer_name(certificate));
729 if (issuer == NULL)
730 goto fail0;
731 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
732 Py_DECREF(issuer);
733 goto fail0;
734 }
735 Py_DECREF(issuer);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000736
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000737 version = PyLong_FromLong(X509_get_version(certificate) + 1);
738 if (PyDict_SetItemString(retval, "version", version) < 0) {
739 Py_DECREF(version);
740 goto fail0;
741 }
742 Py_DECREF(version);
743 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000744
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000745 /* get a memory buffer */
746 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000747
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000748 if (verbose) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000749
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000750 (void) BIO_reset(biobuf);
751 serialNumber = X509_get_serialNumber(certificate);
752 /* should not exceed 20 octets, 160 bits, so buf is big enough */
753 i2a_ASN1_INTEGER(biobuf, serialNumber);
754 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
755 if (len < 0) {
756 _setSSLError(NULL, 0, __FILE__, __LINE__);
757 goto fail1;
758 }
759 sn_obj = PyUnicode_FromStringAndSize(buf, len);
760 if (sn_obj == NULL)
761 goto fail1;
762 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
763 Py_DECREF(sn_obj);
764 goto fail1;
765 }
766 Py_DECREF(sn_obj);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000767
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000768 (void) BIO_reset(biobuf);
769 notBefore = X509_get_notBefore(certificate);
770 ASN1_TIME_print(biobuf, notBefore);
771 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
772 if (len < 0) {
773 _setSSLError(NULL, 0, __FILE__, __LINE__);
774 goto fail1;
775 }
776 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
777 if (pnotBefore == NULL)
778 goto fail1;
779 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
780 Py_DECREF(pnotBefore);
781 goto fail1;
782 }
783 Py_DECREF(pnotBefore);
784 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000785
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000786 (void) BIO_reset(biobuf);
787 notAfter = X509_get_notAfter(certificate);
788 ASN1_TIME_print(biobuf, notAfter);
789 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
790 if (len < 0) {
791 _setSSLError(NULL, 0, __FILE__, __LINE__);
792 goto fail1;
793 }
794 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
795 if (pnotAfter == NULL)
796 goto fail1;
797 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
798 Py_DECREF(pnotAfter);
799 goto fail1;
800 }
801 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000802
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000804
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000805 peer_alt_names = _get_peer_alt_names(certificate);
806 if (peer_alt_names == NULL)
807 goto fail1;
808 else if (peer_alt_names != Py_None) {
809 if (PyDict_SetItemString(retval, "subjectAltName",
810 peer_alt_names) < 0) {
811 Py_DECREF(peer_alt_names);
812 goto fail1;
813 }
814 Py_DECREF(peer_alt_names);
815 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000816
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000817 BIO_free(biobuf);
818 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000819
820 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000821 if (biobuf != NULL)
822 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000823 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000824 Py_XDECREF(retval);
825 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000826}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000827
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000828
829static PyObject *
830PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
831
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000832 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +0000833 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000834 X509 *x=NULL;
835 BIO *cert;
836 int verbose = 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000837
Victor Stinner3800e1e2010-05-16 21:23:48 +0000838 if (!PyArg_ParseTuple(args, "O&|i:test_decode_certificate",
839 PyUnicode_FSConverter, &filename, &verbose))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000840 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000841
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000842 if ((cert=BIO_new(BIO_s_file())) == NULL) {
843 PyErr_SetString(PySSLErrorObject,
844 "Can't malloc memory to read file");
845 goto fail0;
846 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000847
Victor Stinner3800e1e2010-05-16 21:23:48 +0000848 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000849 PyErr_SetString(PySSLErrorObject,
850 "Can't open file");
851 goto fail0;
852 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000853
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000854 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
855 if (x == NULL) {
856 PyErr_SetString(PySSLErrorObject,
857 "Error decoding PEM-encoded file");
858 goto fail0;
859 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000860
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000861 retval = _decode_certificate(x, verbose);
Mark Dickinsonee55df52010-08-03 18:31:54 +0000862 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000863
864 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +0000865 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000866 if (cert != NULL) BIO_free(cert);
867 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000868}
869
870
871static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000872PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000873{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000874 PyObject *retval = NULL;
875 int len;
876 int verification;
877 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000878
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000879 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
880 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000881
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000882 if (!self->peer_cert)
883 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000884
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000885 if (PyObject_IsTrue(binary_mode)) {
886 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000887
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000888 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000889
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000890 bytes_buf = NULL;
891 len = i2d_X509(self->peer_cert, &bytes_buf);
892 if (len < 0) {
893 PySSL_SetError(self, len, __FILE__, __LINE__);
894 return NULL;
895 }
896 /* this is actually an immutable bytes sequence */
897 retval = PyBytes_FromStringAndSize
898 ((const char *) bytes_buf, len);
899 OPENSSL_free(bytes_buf);
900 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000901
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000902 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000903 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000904 if ((verification & SSL_VERIFY_PEER) == 0)
905 return PyDict_New();
906 else
907 return _decode_certificate (self->peer_cert, 0);
908 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000909}
910
911PyDoc_STRVAR(PySSL_peercert_doc,
912"peer_certificate([der=False]) -> certificate\n\
913\n\
914Returns the certificate for the peer. If no certificate was provided,\n\
915returns None. If a certificate was provided, but not validated, returns\n\
916an empty dictionary. Otherwise returns a dict containing information\n\
917about the peer certificate.\n\
918\n\
919If the optional argument is True, returns a DER-encoded copy of the\n\
920peer certificate, or None if no certificate was provided. This will\n\
921return the certificate even if it wasn't validated.");
922
Antoine Pitrou152efa22010-05-16 18:19:27 +0000923static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000924
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000925 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000926 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000927 char *cipher_name;
928 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000929
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000930 if (self->ssl == NULL)
931 return Py_None;
932 current = SSL_get_current_cipher(self->ssl);
933 if (current == NULL)
934 return Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000935
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000936 retval = PyTuple_New(3);
937 if (retval == NULL)
938 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000939
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 cipher_name = (char *) SSL_CIPHER_get_name(current);
941 if (cipher_name == NULL) {
942 PyTuple_SET_ITEM(retval, 0, Py_None);
943 } else {
944 v = PyUnicode_FromString(cipher_name);
945 if (v == NULL)
946 goto fail0;
947 PyTuple_SET_ITEM(retval, 0, v);
948 }
949 cipher_protocol = SSL_CIPHER_get_version(current);
950 if (cipher_protocol == NULL) {
951 PyTuple_SET_ITEM(retval, 1, Py_None);
952 } else {
953 v = PyUnicode_FromString(cipher_protocol);
954 if (v == NULL)
955 goto fail0;
956 PyTuple_SET_ITEM(retval, 1, v);
957 }
958 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
959 if (v == NULL)
960 goto fail0;
961 PyTuple_SET_ITEM(retval, 2, v);
962 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000963
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000964 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000965 Py_DECREF(retval);
966 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000967}
968
Antoine Pitrou152efa22010-05-16 18:19:27 +0000969static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000970{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000971 if (self->peer_cert) /* Possible not to have one? */
972 X509_free (self->peer_cert);
973 if (self->ssl)
974 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000975 Py_XDECREF(self->Socket);
976 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000977}
978
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000979/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000980 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000981 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000982 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000983
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000984static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000985check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000986{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000987 fd_set fds;
988 struct timeval tv;
989 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000990
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000991 /* Nothing to do unless we're in timeout mode (not non-blocking) */
992 if (s->sock_timeout < 0.0)
993 return SOCKET_IS_BLOCKING;
994 else if (s->sock_timeout == 0.0)
995 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000996
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000997 /* Guard against closed socket */
998 if (s->sock_fd < 0)
999 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001000
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001001 /* Prefer poll, if available, since you can poll() any fd
1002 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001003#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001004 {
1005 struct pollfd pollfd;
1006 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001007
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001008 pollfd.fd = s->sock_fd;
1009 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001010
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001011 /* s->sock_timeout is in seconds, timeout in ms */
1012 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1013 PySSL_BEGIN_ALLOW_THREADS
1014 rc = poll(&pollfd, 1, timeout);
1015 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001016
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001017 goto normal_return;
1018 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001019#endif
1020
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001021 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001022#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001023 if (s->sock_fd >= FD_SETSIZE)
1024 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001025#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001026
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001027 /* Construct the arguments to select */
1028 tv.tv_sec = (int)s->sock_timeout;
1029 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1030 FD_ZERO(&fds);
1031 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001032
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001033 /* See if the socket is ready */
1034 PySSL_BEGIN_ALLOW_THREADS
1035 if (writing)
1036 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1037 else
1038 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1039 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001040
Bill Janssen6e027db2007-11-15 22:23:56 +00001041#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001042normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001043#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001044 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1045 (when we are able to write or when there's something to read) */
1046 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001047}
1048
Antoine Pitrou152efa22010-05-16 18:19:27 +00001049static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001050{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001051 Py_buffer buf;
1052 int len;
1053 int sockstate;
1054 int err;
1055 int nonblocking;
1056 PySocketSockObject *sock
1057 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001058
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001059 if (((PyObject*)sock) == Py_None) {
1060 _setSSLError("Underlying socket connection gone",
1061 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1062 return NULL;
1063 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001064 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001065
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001066 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1067 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001068 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001069 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001070
1071 /* just in case the blocking state of the socket has been changed */
1072 nonblocking = (sock->sock_timeout >= 0.0);
1073 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1074 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1075
1076 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1077 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1078 PyErr_SetString(PySSLErrorObject,
1079 "The write operation timed out");
1080 goto error;
1081 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1082 PyErr_SetString(PySSLErrorObject,
1083 "Underlying socket has been closed.");
1084 goto error;
1085 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1086 PyErr_SetString(PySSLErrorObject,
1087 "Underlying socket too large for select().");
1088 goto error;
1089 }
1090 do {
1091 err = 0;
1092 PySSL_BEGIN_ALLOW_THREADS
1093 len = SSL_write(self->ssl, buf.buf, buf.len);
1094 err = SSL_get_error(self->ssl, len);
1095 PySSL_END_ALLOW_THREADS
1096 if (PyErr_CheckSignals()) {
1097 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001098 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001099 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001100 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001101 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001102 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001103 } else {
1104 sockstate = SOCKET_OPERATION_OK;
1105 }
1106 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1107 PyErr_SetString(PySSLErrorObject,
1108 "The write operation timed out");
1109 goto error;
1110 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1111 PyErr_SetString(PySSLErrorObject,
1112 "Underlying socket has been closed.");
1113 goto error;
1114 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1115 break;
1116 }
1117 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001118
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001119 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001120 PyBuffer_Release(&buf);
1121 if (len > 0)
1122 return PyLong_FromLong(len);
1123 else
1124 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001125
1126error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001127 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001128 PyBuffer_Release(&buf);
1129 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001130}
1131
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001132PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001133"write(s) -> len\n\
1134\n\
1135Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001136of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001137
Antoine Pitrou152efa22010-05-16 18:19:27 +00001138static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001139{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001140 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001141
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001142 PySSL_BEGIN_ALLOW_THREADS
1143 count = SSL_pending(self->ssl);
1144 PySSL_END_ALLOW_THREADS
1145 if (count < 0)
1146 return PySSL_SetError(self, count, __FILE__, __LINE__);
1147 else
1148 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001149}
1150
1151PyDoc_STRVAR(PySSL_SSLpending_doc,
1152"pending() -> count\n\
1153\n\
1154Returns the number of already decrypted bytes available for read,\n\
1155pending on the connection.\n");
1156
Antoine Pitrou152efa22010-05-16 18:19:27 +00001157static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001158{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001159 PyObject *dest = NULL;
1160 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001161 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001162 int len, count;
1163 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001164 int sockstate;
1165 int err;
1166 int nonblocking;
1167 PySocketSockObject *sock
1168 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001169
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001170 if (((PyObject*)sock) == Py_None) {
1171 _setSSLError("Underlying socket connection gone",
1172 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1173 return NULL;
1174 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001175 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001176
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001177 buf.obj = NULL;
1178 buf.buf = NULL;
1179 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001180 goto error;
1181
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001182 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1183 dest = PyBytes_FromStringAndSize(NULL, len);
1184 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001185 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001186 mem = PyBytes_AS_STRING(dest);
1187 }
1188 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001189 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001190 mem = buf.buf;
1191 if (len <= 0 || len > buf.len) {
1192 len = (int) buf.len;
1193 if (buf.len != len) {
1194 PyErr_SetString(PyExc_OverflowError,
1195 "maximum length can't fit in a C 'int'");
1196 goto error;
1197 }
1198 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001199 }
1200
1201 /* just in case the blocking state of the socket has been changed */
1202 nonblocking = (sock->sock_timeout >= 0.0);
1203 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1204 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1205
1206 /* first check if there are bytes ready to be read */
1207 PySSL_BEGIN_ALLOW_THREADS
1208 count = SSL_pending(self->ssl);
1209 PySSL_END_ALLOW_THREADS
1210
1211 if (!count) {
1212 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1213 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1214 PyErr_SetString(PySSLErrorObject,
1215 "The read operation timed out");
1216 goto error;
1217 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1218 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001219 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001220 goto error;
1221 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1222 count = 0;
1223 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001224 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001225 }
1226 do {
1227 err = 0;
1228 PySSL_BEGIN_ALLOW_THREADS
1229 count = SSL_read(self->ssl, mem, len);
1230 err = SSL_get_error(self->ssl, count);
1231 PySSL_END_ALLOW_THREADS
1232 if (PyErr_CheckSignals())
1233 goto error;
1234 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001235 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001236 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001237 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001238 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1239 (SSL_get_shutdown(self->ssl) ==
1240 SSL_RECEIVED_SHUTDOWN))
1241 {
1242 count = 0;
1243 goto done;
1244 } else {
1245 sockstate = SOCKET_OPERATION_OK;
1246 }
1247 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1248 PyErr_SetString(PySSLErrorObject,
1249 "The read operation timed out");
1250 goto error;
1251 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1252 break;
1253 }
1254 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1255 if (count <= 0) {
1256 PySSL_SetError(self, count, __FILE__, __LINE__);
1257 goto error;
1258 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001259
1260done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001261 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001262 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001263 _PyBytes_Resize(&dest, count);
1264 return dest;
1265 }
1266 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001267 PyBuffer_Release(&buf);
1268 return PyLong_FromLong(count);
1269 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001270
1271error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001272 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001273 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001274 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001275 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001277 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001278}
1279
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001280PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001281"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001282\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001283Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001284
Antoine Pitrou152efa22010-05-16 18:19:27 +00001285static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001286{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001287 int err, ssl_err, sockstate, nonblocking;
1288 int zeros = 0;
1289 PySocketSockObject *sock
1290 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001291
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001292 /* Guard against closed socket */
1293 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1294 _setSSLError("Underlying socket connection gone",
1295 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1296 return NULL;
1297 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001298 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001299
1300 /* Just in case the blocking state of the socket has been changed */
1301 nonblocking = (sock->sock_timeout >= 0.0);
1302 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1303 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1304
1305 while (1) {
1306 PySSL_BEGIN_ALLOW_THREADS
1307 /* Disable read-ahead so that unwrap can work correctly.
1308 * Otherwise OpenSSL might read in too much data,
1309 * eating clear text data that happens to be
1310 * transmitted after the SSL shutdown.
1311 * Should be safe to call repeatedly everytime this
1312 * function is used and the shutdown_seen_zero != 0
1313 * condition is met.
1314 */
1315 if (self->shutdown_seen_zero)
1316 SSL_set_read_ahead(self->ssl, 0);
1317 err = SSL_shutdown(self->ssl);
1318 PySSL_END_ALLOW_THREADS
1319 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1320 if (err > 0)
1321 break;
1322 if (err == 0) {
1323 /* Don't loop endlessly; instead preserve legacy
1324 behaviour of trying SSL_shutdown() only twice.
1325 This looks necessary for OpenSSL < 0.9.8m */
1326 if (++zeros > 1)
1327 break;
1328 /* Shutdown was sent, now try receiving */
1329 self->shutdown_seen_zero = 1;
1330 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001331 }
1332
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001333 /* Possibly retry shutdown until timeout or failure */
1334 ssl_err = SSL_get_error(self->ssl, err);
1335 if (ssl_err == SSL_ERROR_WANT_READ)
1336 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1337 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1338 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1339 else
1340 break;
1341 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1342 if (ssl_err == SSL_ERROR_WANT_READ)
1343 PyErr_SetString(PySSLErrorObject,
1344 "The read operation timed out");
1345 else
1346 PyErr_SetString(PySSLErrorObject,
1347 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001348 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001349 }
1350 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1351 PyErr_SetString(PySSLErrorObject,
1352 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001353 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001354 }
1355 else if (sockstate != SOCKET_OPERATION_OK)
1356 /* Retain the SSL error code */
1357 break;
1358 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001359
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001360 if (err < 0) {
1361 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001362 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001363 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001364 else
1365 /* It's already INCREF'ed */
1366 return (PyObject *) sock;
1367
1368error:
1369 Py_DECREF(sock);
1370 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001371}
1372
1373PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1374"shutdown(s) -> socket\n\
1375\n\
1376Does the SSL shutdown handshake with the remote end, and returns\n\
1377the underlying socket object.");
1378
1379
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001380static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001381 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1382 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1383 PySSL_SSLwrite_doc},
1384 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1385 PySSL_SSLread_doc},
1386 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1387 PySSL_SSLpending_doc},
1388 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1389 PySSL_peercert_doc},
1390 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1391 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1392 PySSL_SSLshutdown_doc},
1393 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001394};
1395
Antoine Pitrou152efa22010-05-16 18:19:27 +00001396static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001397 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001398 "_ssl._SSLSocket", /*tp_name*/
1399 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001400 0, /*tp_itemsize*/
1401 /* methods */
1402 (destructor)PySSL_dealloc, /*tp_dealloc*/
1403 0, /*tp_print*/
1404 0, /*tp_getattr*/
1405 0, /*tp_setattr*/
1406 0, /*tp_reserved*/
1407 0, /*tp_repr*/
1408 0, /*tp_as_number*/
1409 0, /*tp_as_sequence*/
1410 0, /*tp_as_mapping*/
1411 0, /*tp_hash*/
1412 0, /*tp_call*/
1413 0, /*tp_str*/
1414 0, /*tp_getattro*/
1415 0, /*tp_setattro*/
1416 0, /*tp_as_buffer*/
1417 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1418 0, /*tp_doc*/
1419 0, /*tp_traverse*/
1420 0, /*tp_clear*/
1421 0, /*tp_richcompare*/
1422 0, /*tp_weaklistoffset*/
1423 0, /*tp_iter*/
1424 0, /*tp_iternext*/
1425 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001426};
1427
Antoine Pitrou152efa22010-05-16 18:19:27 +00001428
1429/*
1430 * _SSLContext objects
1431 */
1432
1433static PyObject *
1434context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1435{
1436 char *kwlist[] = {"protocol", NULL};
1437 PySSLContext *self;
1438 int proto_version = PY_SSL_VERSION_SSL23;
1439 SSL_CTX *ctx = NULL;
1440
1441 if (!PyArg_ParseTupleAndKeywords(
1442 args, kwds, "i:_SSLContext", kwlist,
1443 &proto_version))
1444 return NULL;
1445
1446 PySSL_BEGIN_ALLOW_THREADS
1447 if (proto_version == PY_SSL_VERSION_TLS1)
1448 ctx = SSL_CTX_new(TLSv1_method());
1449 else if (proto_version == PY_SSL_VERSION_SSL3)
1450 ctx = SSL_CTX_new(SSLv3_method());
1451 else if (proto_version == PY_SSL_VERSION_SSL2)
1452 ctx = SSL_CTX_new(SSLv2_method());
1453 else if (proto_version == PY_SSL_VERSION_SSL23)
1454 ctx = SSL_CTX_new(SSLv23_method());
1455 else
1456 proto_version = -1;
1457 PySSL_END_ALLOW_THREADS
1458
1459 if (proto_version == -1) {
1460 PyErr_SetString(PyExc_ValueError,
1461 "invalid protocol version");
1462 return NULL;
1463 }
1464 if (ctx == NULL) {
1465 PyErr_SetString(PySSLErrorObject,
1466 "failed to allocate SSL context");
1467 return NULL;
1468 }
1469
1470 assert(type != NULL && type->tp_alloc != NULL);
1471 self = (PySSLContext *) type->tp_alloc(type, 0);
1472 if (self == NULL) {
1473 SSL_CTX_free(ctx);
1474 return NULL;
1475 }
1476 self->ctx = ctx;
1477 /* Defaults */
1478 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
1479 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
1480
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001481#define SID_CTX "Python"
1482 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1483 sizeof(SID_CTX));
1484#undef SID_CTX
1485
Antoine Pitrou152efa22010-05-16 18:19:27 +00001486 return (PyObject *)self;
1487}
1488
1489static void
1490context_dealloc(PySSLContext *self)
1491{
1492 SSL_CTX_free(self->ctx);
1493 Py_TYPE(self)->tp_free(self);
1494}
1495
1496static PyObject *
1497set_ciphers(PySSLContext *self, PyObject *args)
1498{
1499 int ret;
1500 const char *cipherlist;
1501
1502 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1503 return NULL;
1504 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1505 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001506 /* Clearing the error queue is necessary on some OpenSSL versions,
1507 otherwise the error will be reported again when another SSL call
1508 is done. */
1509 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001510 PyErr_SetString(PySSLErrorObject,
1511 "No cipher can be selected.");
1512 return NULL;
1513 }
1514 Py_RETURN_NONE;
1515}
1516
1517static PyObject *
1518get_verify_mode(PySSLContext *self, void *c)
1519{
1520 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1521 case SSL_VERIFY_NONE:
1522 return PyLong_FromLong(PY_SSL_CERT_NONE);
1523 case SSL_VERIFY_PEER:
1524 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1525 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1526 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1527 }
1528 PyErr_SetString(PySSLErrorObject,
1529 "invalid return value from SSL_CTX_get_verify_mode");
1530 return NULL;
1531}
1532
1533static int
1534set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1535{
1536 int n, mode;
1537 if (!PyArg_Parse(arg, "i", &n))
1538 return -1;
1539 if (n == PY_SSL_CERT_NONE)
1540 mode = SSL_VERIFY_NONE;
1541 else if (n == PY_SSL_CERT_OPTIONAL)
1542 mode = SSL_VERIFY_PEER;
1543 else if (n == PY_SSL_CERT_REQUIRED)
1544 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1545 else {
1546 PyErr_SetString(PyExc_ValueError,
1547 "invalid value for verify_mode");
1548 return -1;
1549 }
1550 SSL_CTX_set_verify(self->ctx, mode, NULL);
1551 return 0;
1552}
1553
1554static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001555get_options(PySSLContext *self, void *c)
1556{
1557 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1558}
1559
1560static int
1561set_options(PySSLContext *self, PyObject *arg, void *c)
1562{
1563 long new_opts, opts, set, clear;
1564 if (!PyArg_Parse(arg, "l", &new_opts))
1565 return -1;
1566 opts = SSL_CTX_get_options(self->ctx);
1567 clear = opts & ~new_opts;
1568 set = ~opts & new_opts;
1569 if (clear) {
1570#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1571 SSL_CTX_clear_options(self->ctx, clear);
1572#else
1573 PyErr_SetString(PyExc_ValueError,
1574 "can't clear options before OpenSSL 0.9.8m");
1575 return -1;
1576#endif
1577 }
1578 if (set)
1579 SSL_CTX_set_options(self->ctx, set);
1580 return 0;
1581}
1582
1583static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001584load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
1585{
1586 char *kwlist[] = {"certfile", "keyfile", NULL};
1587 PyObject *certfile, *keyfile = NULL;
1588 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
1589 int r;
1590
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001591 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00001592 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001593 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1594 "O|O:load_cert_chain", kwlist,
1595 &certfile, &keyfile))
1596 return NULL;
1597 if (keyfile == Py_None)
1598 keyfile = NULL;
1599 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
1600 PyErr_SetString(PyExc_TypeError,
1601 "certfile should be a valid filesystem path");
1602 return NULL;
1603 }
1604 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
1605 PyErr_SetString(PyExc_TypeError,
1606 "keyfile should be a valid filesystem path");
1607 goto error;
1608 }
1609 PySSL_BEGIN_ALLOW_THREADS
1610 r = SSL_CTX_use_certificate_chain_file(self->ctx,
1611 PyBytes_AS_STRING(certfile_bytes));
1612 PySSL_END_ALLOW_THREADS
1613 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001614 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001615 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001616 PyErr_SetFromErrno(PyExc_IOError);
1617 }
1618 else {
1619 _setSSLError(NULL, 0, __FILE__, __LINE__);
1620 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001621 goto error;
1622 }
1623 PySSL_BEGIN_ALLOW_THREADS
1624 r = SSL_CTX_use_RSAPrivateKey_file(self->ctx,
1625 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
1626 SSL_FILETYPE_PEM);
1627 PySSL_END_ALLOW_THREADS
1628 Py_XDECREF(keyfile_bytes);
1629 Py_XDECREF(certfile_bytes);
1630 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001631 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001632 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001633 PyErr_SetFromErrno(PyExc_IOError);
1634 }
1635 else {
1636 _setSSLError(NULL, 0, __FILE__, __LINE__);
1637 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001638 return NULL;
1639 }
1640 PySSL_BEGIN_ALLOW_THREADS
1641 r = SSL_CTX_check_private_key(self->ctx);
1642 PySSL_END_ALLOW_THREADS
1643 if (r != 1) {
1644 _setSSLError(NULL, 0, __FILE__, __LINE__);
1645 return NULL;
1646 }
1647 Py_RETURN_NONE;
1648
1649error:
1650 Py_XDECREF(keyfile_bytes);
1651 Py_XDECREF(certfile_bytes);
1652 return NULL;
1653}
1654
1655static PyObject *
1656load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
1657{
1658 char *kwlist[] = {"cafile", "capath", NULL};
1659 PyObject *cafile = NULL, *capath = NULL;
1660 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
1661 const char *cafile_buf = NULL, *capath_buf = NULL;
1662 int r;
1663
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001664 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001665 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1666 "|OO:load_verify_locations", kwlist,
1667 &cafile, &capath))
1668 return NULL;
1669 if (cafile == Py_None)
1670 cafile = NULL;
1671 if (capath == Py_None)
1672 capath = NULL;
1673 if (cafile == NULL && capath == NULL) {
1674 PyErr_SetString(PyExc_TypeError,
1675 "cafile and capath cannot be both omitted");
1676 return NULL;
1677 }
1678 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
1679 PyErr_SetString(PyExc_TypeError,
1680 "cafile should be a valid filesystem path");
1681 return NULL;
1682 }
1683 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
1684 Py_DECREF(cafile_bytes);
1685 PyErr_SetString(PyExc_TypeError,
1686 "capath should be a valid filesystem path");
1687 return NULL;
1688 }
1689 if (cafile)
1690 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
1691 if (capath)
1692 capath_buf = PyBytes_AS_STRING(capath_bytes);
1693 PySSL_BEGIN_ALLOW_THREADS
1694 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
1695 PySSL_END_ALLOW_THREADS
1696 Py_XDECREF(cafile_bytes);
1697 Py_XDECREF(capath_bytes);
1698 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001699 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001700 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001701 PyErr_SetFromErrno(PyExc_IOError);
1702 }
1703 else {
1704 _setSSLError(NULL, 0, __FILE__, __LINE__);
1705 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001706 return NULL;
1707 }
1708 Py_RETURN_NONE;
1709}
1710
1711static PyObject *
1712context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
1713{
1714 char *kwlist[] = {"sock", "server_side", NULL};
1715 PySocketSockObject *sock;
1716 int server_side = 0;
1717
1718 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i:_wrap_socket", kwlist,
1719 PySocketModule.Sock_Type,
1720 &sock, &server_side))
1721 return NULL;
1722
1723 return (PyObject *) newPySSLSocket(self->ctx, sock, server_side);
1724}
1725
Antoine Pitroub0182c82010-10-12 20:09:02 +00001726static PyObject *
1727session_stats(PySSLContext *self, PyObject *unused)
1728{
1729 int r;
1730 PyObject *value, *stats = PyDict_New();
1731 if (!stats)
1732 return NULL;
1733
1734#define ADD_STATS(SSL_NAME, KEY_NAME) \
1735 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
1736 if (value == NULL) \
1737 goto error; \
1738 r = PyDict_SetItemString(stats, KEY_NAME, value); \
1739 Py_DECREF(value); \
1740 if (r < 0) \
1741 goto error;
1742
1743 ADD_STATS(number, "number");
1744 ADD_STATS(connect, "connect");
1745 ADD_STATS(connect_good, "connect_good");
1746 ADD_STATS(connect_renegotiate, "connect_renegotiate");
1747 ADD_STATS(accept, "accept");
1748 ADD_STATS(accept_good, "accept_good");
1749 ADD_STATS(accept_renegotiate, "accept_renegotiate");
1750 ADD_STATS(accept, "accept");
1751 ADD_STATS(hits, "hits");
1752 ADD_STATS(misses, "misses");
1753 ADD_STATS(timeouts, "timeouts");
1754 ADD_STATS(cache_full, "cache_full");
1755
1756#undef ADD_STATS
1757
1758 return stats;
1759
1760error:
1761 Py_DECREF(stats);
1762 return NULL;
1763}
1764
Antoine Pitrou152efa22010-05-16 18:19:27 +00001765static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00001766 {"options", (getter) get_options,
1767 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00001768 {"verify_mode", (getter) get_verify_mode,
1769 (setter) set_verify_mode, NULL},
1770 {NULL}, /* sentinel */
1771};
1772
1773static struct PyMethodDef context_methods[] = {
1774 {"_wrap_socket", (PyCFunction) context_wrap_socket,
1775 METH_VARARGS | METH_KEYWORDS, NULL},
1776 {"set_ciphers", (PyCFunction) set_ciphers,
1777 METH_VARARGS, NULL},
1778 {"load_cert_chain", (PyCFunction) load_cert_chain,
1779 METH_VARARGS | METH_KEYWORDS, NULL},
1780 {"load_verify_locations", (PyCFunction) load_verify_locations,
1781 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00001782 {"session_stats", (PyCFunction) session_stats,
1783 METH_NOARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00001784 {NULL, NULL} /* sentinel */
1785};
1786
1787static PyTypeObject PySSLContext_Type = {
1788 PyVarObject_HEAD_INIT(NULL, 0)
1789 "_ssl._SSLContext", /*tp_name*/
1790 sizeof(PySSLContext), /*tp_basicsize*/
1791 0, /*tp_itemsize*/
1792 (destructor)context_dealloc, /*tp_dealloc*/
1793 0, /*tp_print*/
1794 0, /*tp_getattr*/
1795 0, /*tp_setattr*/
1796 0, /*tp_reserved*/
1797 0, /*tp_repr*/
1798 0, /*tp_as_number*/
1799 0, /*tp_as_sequence*/
1800 0, /*tp_as_mapping*/
1801 0, /*tp_hash*/
1802 0, /*tp_call*/
1803 0, /*tp_str*/
1804 0, /*tp_getattro*/
1805 0, /*tp_setattro*/
1806 0, /*tp_as_buffer*/
1807 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
1808 0, /*tp_doc*/
1809 0, /*tp_traverse*/
1810 0, /*tp_clear*/
1811 0, /*tp_richcompare*/
1812 0, /*tp_weaklistoffset*/
1813 0, /*tp_iter*/
1814 0, /*tp_iternext*/
1815 context_methods, /*tp_methods*/
1816 0, /*tp_members*/
1817 context_getsetlist, /*tp_getset*/
1818 0, /*tp_base*/
1819 0, /*tp_dict*/
1820 0, /*tp_descr_get*/
1821 0, /*tp_descr_set*/
1822 0, /*tp_dictoffset*/
1823 0, /*tp_init*/
1824 0, /*tp_alloc*/
1825 context_new, /*tp_new*/
1826};
1827
1828
1829
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001830#ifdef HAVE_OPENSSL_RAND
1831
1832/* helper routines for seeding the SSL PRNG */
1833static PyObject *
1834PySSL_RAND_add(PyObject *self, PyObject *args)
1835{
1836 char *buf;
1837 int len;
1838 double entropy;
1839
1840 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00001841 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001842 RAND_add(buf, len, entropy);
1843 Py_INCREF(Py_None);
1844 return Py_None;
1845}
1846
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001847PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001848"RAND_add(string, entropy)\n\
1849\n\
1850Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001851bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001852
1853static PyObject *
1854PySSL_RAND_status(PyObject *self)
1855{
Christian Heimes217cfd12007-12-02 14:31:20 +00001856 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001857}
1858
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001859PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001860"RAND_status() -> 0 or 1\n\
1861\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001862Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1863It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1864using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001865
1866static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001867PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001868{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001869 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001870 int bytes;
1871
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001872 if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
1873 PyUnicode_FSConverter, &path))
1874 return NULL;
1875
1876 bytes = RAND_egd(PyBytes_AsString(path));
1877 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001878 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001879 PyErr_SetString(PySSLErrorObject,
1880 "EGD connection failed or EGD did not return "
1881 "enough data to seed the PRNG");
1882 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001883 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001884 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001885}
1886
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001887PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001888"RAND_egd(path) -> bytes\n\
1889\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001890Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1891Returns number of bytes read. Raises SSLError if connection to EGD\n\
1892fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001893
1894#endif
1895
Bill Janssen40a0f662008-08-12 16:56:25 +00001896
1897
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001898/* List of functions exported by this module. */
1899
1900static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001901 {"_test_decode_cert", PySSL_test_decode_certificate,
1902 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001903#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001904 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1905 PySSL_RAND_add_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001906 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001907 PySSL_RAND_egd_doc},
1908 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1909 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001910#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001911 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001912};
1913
1914
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001915#ifdef WITH_THREAD
1916
1917/* an implementation of OpenSSL threading operations in terms
1918 of the Python C thread library */
1919
1920static PyThread_type_lock *_ssl_locks = NULL;
1921
1922static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001923 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001924}
1925
Bill Janssen6e027db2007-11-15 22:23:56 +00001926static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001927 (int mode, int n, const char *file, int line) {
1928 /* this function is needed to perform locking on shared data
1929 structures. (Note that OpenSSL uses a number of global data
1930 structures that will be implicitly shared whenever multiple
1931 threads use OpenSSL.) Multi-threaded applications will
1932 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001933
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001934 locking_function() must be able to handle up to
1935 CRYPTO_num_locks() different mutex locks. It sets the n-th
1936 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001937
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001938 file and line are the file number of the function setting the
1939 lock. They can be useful for debugging.
1940 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001941
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001942 if ((_ssl_locks == NULL) ||
1943 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1944 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001945
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001946 if (mode & CRYPTO_LOCK) {
1947 PyThread_acquire_lock(_ssl_locks[n], 1);
1948 } else {
1949 PyThread_release_lock(_ssl_locks[n]);
1950 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001951}
1952
1953static int _setup_ssl_threads(void) {
1954
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001955 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001956
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001957 if (_ssl_locks == NULL) {
1958 _ssl_locks_count = CRYPTO_num_locks();
1959 _ssl_locks = (PyThread_type_lock *)
1960 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1961 if (_ssl_locks == NULL)
1962 return 0;
1963 memset(_ssl_locks, 0,
1964 sizeof(PyThread_type_lock) * _ssl_locks_count);
1965 for (i = 0; i < _ssl_locks_count; i++) {
1966 _ssl_locks[i] = PyThread_allocate_lock();
1967 if (_ssl_locks[i] == NULL) {
1968 unsigned int j;
1969 for (j = 0; j < i; j++) {
1970 PyThread_free_lock(_ssl_locks[j]);
1971 }
1972 free(_ssl_locks);
1973 return 0;
1974 }
1975 }
1976 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1977 CRYPTO_set_id_callback(_ssl_thread_id_function);
1978 }
1979 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001980}
1981
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001982#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001983
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001984PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001985"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001986for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001987
Martin v. Löwis1a214512008-06-11 05:26:20 +00001988
1989static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001990 PyModuleDef_HEAD_INIT,
1991 "_ssl",
1992 module_doc,
1993 -1,
1994 PySSL_methods,
1995 NULL,
1996 NULL,
1997 NULL,
1998 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001999};
2000
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002001PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002002PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002003{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002004 PyObject *m, *d, *r;
2005 unsigned long libver;
2006 unsigned int major, minor, fix, patch, status;
2007 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002008
Antoine Pitrou152efa22010-05-16 18:19:27 +00002009 if (PyType_Ready(&PySSLContext_Type) < 0)
2010 return NULL;
2011 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002012 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002013
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002014 m = PyModule_Create(&_sslmodule);
2015 if (m == NULL)
2016 return NULL;
2017 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002018
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002019 /* Load _socket module and its C API */
2020 socket_api = PySocketModule_ImportModuleAndAPI();
2021 if (!socket_api)
2022 return NULL;
2023 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002024
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002025 /* Init OpenSSL */
2026 SSL_load_error_strings();
2027 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002028#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002029 /* note that this will start threading if not already started */
2030 if (!_setup_ssl_threads()) {
2031 return NULL;
2032 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002033#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002034 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002035
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002036 /* Add symbols to module dict */
2037 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
2038 PySocketModule.error,
2039 NULL);
2040 if (PySSLErrorObject == NULL)
2041 return NULL;
2042 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
2043 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002044 if (PyDict_SetItemString(d, "_SSLContext",
2045 (PyObject *)&PySSLContext_Type) != 0)
2046 return NULL;
2047 if (PyDict_SetItemString(d, "_SSLSocket",
2048 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002049 return NULL;
2050 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2051 PY_SSL_ERROR_ZERO_RETURN);
2052 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2053 PY_SSL_ERROR_WANT_READ);
2054 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2055 PY_SSL_ERROR_WANT_WRITE);
2056 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2057 PY_SSL_ERROR_WANT_X509_LOOKUP);
2058 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2059 PY_SSL_ERROR_SYSCALL);
2060 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2061 PY_SSL_ERROR_SSL);
2062 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2063 PY_SSL_ERROR_WANT_CONNECT);
2064 /* non ssl.h errorcodes */
2065 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2066 PY_SSL_ERROR_EOF);
2067 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2068 PY_SSL_ERROR_INVALID_ERROR_CODE);
2069 /* cert requirements */
2070 PyModule_AddIntConstant(m, "CERT_NONE",
2071 PY_SSL_CERT_NONE);
2072 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2073 PY_SSL_CERT_OPTIONAL);
2074 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2075 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002076
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002077 /* protocol versions */
2078 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2079 PY_SSL_VERSION_SSL2);
2080 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2081 PY_SSL_VERSION_SSL3);
2082 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2083 PY_SSL_VERSION_SSL23);
2084 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2085 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002086
Antoine Pitroub5218772010-05-21 09:56:06 +00002087 /* protocol options */
2088 PyModule_AddIntConstant(m, "OP_ALL", SSL_OP_ALL);
2089 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2090 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2091 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
2092
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002093 /* OpenSSL version */
2094 /* SSLeay() gives us the version of the library linked against,
2095 which could be different from the headers version.
2096 */
2097 libver = SSLeay();
2098 r = PyLong_FromUnsignedLong(libver);
2099 if (r == NULL)
2100 return NULL;
2101 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2102 return NULL;
2103 status = libver & 0xF;
2104 libver >>= 4;
2105 patch = libver & 0xFF;
2106 libver >>= 8;
2107 fix = libver & 0xFF;
2108 libver >>= 8;
2109 minor = libver & 0xFF;
2110 libver >>= 8;
2111 major = libver & 0xFF;
2112 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2113 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2114 return NULL;
2115 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2116 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2117 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002118
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002119 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002120}