blob: f8428c4d5b52ca5abeb65a1e90ea6b02a537cd97 [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
Antoine Pitroub5218772010-05-21 09:56:06 +0000116/* SSL_CTX_clear_options() and SSL_clear_options() were first added in OpenSSL 0.9.8m */
117#if OPENSSL_VERSION_NUMBER >= 0x009080dfL
118# define HAVE_SSL_CTX_CLEAR_OPTIONS
119#else
120# undef HAVE_SSL_CTX_CLEAR_OPTIONS
121#endif
122
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000123typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000124 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000125 SSL_CTX *ctx;
126} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000127
Antoine Pitrou152efa22010-05-16 18:19:27 +0000128typedef struct {
129 PyObject_HEAD
130 PyObject *Socket; /* weakref to socket on which we're layered */
131 SSL *ssl;
132 X509 *peer_cert;
133 int shutdown_seen_zero;
134} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000135
Antoine Pitrou152efa22010-05-16 18:19:27 +0000136static PyTypeObject PySSLContext_Type;
137static PyTypeObject PySSLSocket_Type;
138
139static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
140static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000141static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000142 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000143static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
144static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000145
Antoine Pitrou152efa22010-05-16 18:19:27 +0000146#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
147#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000148
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000149typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000150 SOCKET_IS_NONBLOCKING,
151 SOCKET_IS_BLOCKING,
152 SOCKET_HAS_TIMED_OUT,
153 SOCKET_HAS_BEEN_CLOSED,
154 SOCKET_TOO_LARGE_FOR_SELECT,
155 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000156} timeout_state;
157
Thomas Woutersed03b412007-08-28 21:37:11 +0000158/* Wrap error strings with filename and line # */
159#define STRINGIFY1(x) #x
160#define STRINGIFY2(x) STRINGIFY1(x)
161#define ERRSTR1(x,y,z) (x ":" y ": " z)
162#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
163
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000164/* XXX It might be helpful to augment the error message generated
165 below with the name of the SSL function that generated the error.
166 I expect it's obvious most of the time.
167*/
168
169static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000170PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000171{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000172 PyObject *v;
173 char buf[2048];
174 char *errstr;
175 int err;
176 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000177
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000178 assert(ret <= 0);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000179
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000180 if (obj->ssl != NULL) {
181 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000182
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000183 switch (err) {
184 case SSL_ERROR_ZERO_RETURN:
185 errstr = "TLS/SSL connection has been closed";
186 p = PY_SSL_ERROR_ZERO_RETURN;
187 break;
188 case SSL_ERROR_WANT_READ:
189 errstr = "The operation did not complete (read)";
190 p = PY_SSL_ERROR_WANT_READ;
191 break;
192 case SSL_ERROR_WANT_WRITE:
193 p = PY_SSL_ERROR_WANT_WRITE;
194 errstr = "The operation did not complete (write)";
195 break;
196 case SSL_ERROR_WANT_X509_LOOKUP:
197 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000198 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000199 break;
200 case SSL_ERROR_WANT_CONNECT:
201 p = PY_SSL_ERROR_WANT_CONNECT;
202 errstr = "The operation did not complete (connect)";
203 break;
204 case SSL_ERROR_SYSCALL:
205 {
206 unsigned long e = ERR_get_error();
207 if (e == 0) {
208 PySocketSockObject *s
209 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
210 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000211 p = PY_SSL_ERROR_EOF;
212 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000213 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000214 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000215 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000216 ERR_clear_error();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000217 v = s->errorhandler();
218 Py_DECREF(s);
219 return v;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000220 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000221 p = PY_SSL_ERROR_SYSCALL;
222 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000223 }
224 } else {
225 p = PY_SSL_ERROR_SYSCALL;
226 /* XXX Protected by global interpreter lock */
227 errstr = ERR_error_string(e, NULL);
228 }
229 break;
230 }
231 case SSL_ERROR_SSL:
232 {
233 unsigned long e = ERR_get_error();
234 p = PY_SSL_ERROR_SSL;
235 if (e != 0)
236 /* XXX Protected by global interpreter lock */
237 errstr = ERR_error_string(e, NULL);
238 else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000239 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000240 }
241 break;
242 }
243 default:
244 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
245 errstr = "Invalid error code";
246 }
247 } else {
248 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
249 }
250 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000251 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000252 v = Py_BuildValue("(is)", p, buf);
253 if (v != NULL) {
254 PyErr_SetObject(PySSLErrorObject, v);
255 Py_DECREF(v);
256 }
257 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000258}
259
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000260static PyObject *
261_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
262
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000263 char buf[2048];
264 PyObject *v;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000265
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000266 if (errstr == NULL) {
267 errcode = ERR_peek_last_error();
268 errstr = ERR_error_string(errcode, NULL);
269 }
270 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000271 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000272 v = Py_BuildValue("(is)", errcode, buf);
273 if (v != NULL) {
274 PyErr_SetObject(PySSLErrorObject, v);
275 Py_DECREF(v);
276 }
277 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000278}
279
Antoine Pitrou152efa22010-05-16 18:19:27 +0000280static PySSLSocket *
281newPySSLSocket(SSL_CTX *ctx, PySocketSockObject *sock,
282 enum py_ssl_server_or_client socket_type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000283{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000284 PySSLSocket *self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000285
Antoine Pitrou152efa22010-05-16 18:19:27 +0000286 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000287 if (self == NULL)
288 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000289
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000290 self->peer_cert = NULL;
291 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000292 self->Socket = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000293
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000294 /* Make sure the SSL error state is initialized */
295 (void) ERR_get_state();
296 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000297
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000298 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000299 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000300 PySSL_END_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000301 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000302#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000303 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000304#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000305
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000306 /* If the socket is in non-blocking mode or timeout mode, set the BIO
307 * to non-blocking mode (blocking is the default)
308 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000309 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000310 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
311 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
312 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000313
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000314 PySSL_BEGIN_ALLOW_THREADS
315 if (socket_type == PY_SSL_CLIENT)
316 SSL_set_connect_state(self->ssl);
317 else
318 SSL_set_accept_state(self->ssl);
319 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000320
Antoine Pitrou152efa22010-05-16 18:19:27 +0000321 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000322 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000323}
324
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000325/* SSL object methods */
326
Antoine Pitrou152efa22010-05-16 18:19:27 +0000327static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000328{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000329 int ret;
330 int err;
331 int sockstate, nonblocking;
332 PySocketSockObject *sock
333 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000334
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000335 if (((PyObject*)sock) == Py_None) {
336 _setSSLError("Underlying socket connection gone",
337 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
338 return NULL;
339 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000340 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000341
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000342 /* just in case the blocking state of the socket has been changed */
343 nonblocking = (sock->sock_timeout >= 0.0);
344 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
345 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000346
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000347 /* Actually negotiate SSL connection */
348 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
349 sockstate = 0;
350 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000351 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000352 ret = SSL_do_handshake(self->ssl);
353 err = SSL_get_error(self->ssl, ret);
354 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000355 if (PyErr_CheckSignals())
356 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000357 if (err == SSL_ERROR_WANT_READ) {
358 sockstate = check_socket_and_wait_for_timeout(sock, 0);
359 } else if (err == SSL_ERROR_WANT_WRITE) {
360 sockstate = check_socket_and_wait_for_timeout(sock, 1);
361 } else {
362 sockstate = SOCKET_OPERATION_OK;
363 }
364 if (sockstate == SOCKET_HAS_TIMED_OUT) {
365 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000366 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000367 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000368 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
369 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000370 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000371 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000372 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
373 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000374 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000375 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000376 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
377 break;
378 }
379 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000380 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000381 if (ret < 1)
382 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000383
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000384 if (self->peer_cert)
385 X509_free (self->peer_cert);
386 PySSL_BEGIN_ALLOW_THREADS
387 self->peer_cert = SSL_get_peer_certificate(self->ssl);
388 PySSL_END_ALLOW_THREADS
389
390 Py_INCREF(Py_None);
391 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000392
393error:
394 Py_DECREF(sock);
395 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000396}
397
Thomas Woutersed03b412007-08-28 21:37:11 +0000398static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000399_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000400
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000401 char namebuf[X509_NAME_MAXLEN];
402 int buflen;
403 PyObject *name_obj;
404 PyObject *value_obj;
405 PyObject *attr;
406 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000407
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000408 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
409 if (buflen < 0) {
410 _setSSLError(NULL, 0, __FILE__, __LINE__);
411 goto fail;
412 }
413 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
414 if (name_obj == NULL)
415 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000416
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000417 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
418 if (buflen < 0) {
419 _setSSLError(NULL, 0, __FILE__, __LINE__);
420 Py_DECREF(name_obj);
421 goto fail;
422 }
423 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000424 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000425 OPENSSL_free(valuebuf);
426 if (value_obj == NULL) {
427 Py_DECREF(name_obj);
428 goto fail;
429 }
430 attr = PyTuple_New(2);
431 if (attr == NULL) {
432 Py_DECREF(name_obj);
433 Py_DECREF(value_obj);
434 goto fail;
435 }
436 PyTuple_SET_ITEM(attr, 0, name_obj);
437 PyTuple_SET_ITEM(attr, 1, value_obj);
438 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000439
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000440 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000441 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000442}
443
444static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000445_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000446{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000447 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
448 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
449 PyObject *rdnt;
450 PyObject *attr = NULL; /* tuple to hold an attribute */
451 int entry_count = X509_NAME_entry_count(xname);
452 X509_NAME_ENTRY *entry;
453 ASN1_OBJECT *name;
454 ASN1_STRING *value;
455 int index_counter;
456 int rdn_level = -1;
457 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000458
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000459 dn = PyList_New(0);
460 if (dn == NULL)
461 return NULL;
462 /* now create another tuple to hold the top-level RDN */
463 rdn = PyList_New(0);
464 if (rdn == NULL)
465 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000466
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000467 for (index_counter = 0;
468 index_counter < entry_count;
469 index_counter++)
470 {
471 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000472
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000473 /* check to see if we've gotten to a new RDN */
474 if (rdn_level >= 0) {
475 if (rdn_level != entry->set) {
476 /* yes, new RDN */
477 /* add old RDN to DN */
478 rdnt = PyList_AsTuple(rdn);
479 Py_DECREF(rdn);
480 if (rdnt == NULL)
481 goto fail0;
482 retcode = PyList_Append(dn, rdnt);
483 Py_DECREF(rdnt);
484 if (retcode < 0)
485 goto fail0;
486 /* create new RDN */
487 rdn = PyList_New(0);
488 if (rdn == NULL)
489 goto fail0;
490 }
491 }
492 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000493
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000494 /* now add this attribute to the current RDN */
495 name = X509_NAME_ENTRY_get_object(entry);
496 value = X509_NAME_ENTRY_get_data(entry);
497 attr = _create_tuple_for_attribute(name, value);
498 /*
499 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
500 entry->set,
501 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
502 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
503 */
504 if (attr == NULL)
505 goto fail1;
506 retcode = PyList_Append(rdn, attr);
507 Py_DECREF(attr);
508 if (retcode < 0)
509 goto fail1;
510 }
511 /* now, there's typically a dangling RDN */
512 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
513 rdnt = PyList_AsTuple(rdn);
514 Py_DECREF(rdn);
515 if (rdnt == NULL)
516 goto fail0;
517 retcode = PyList_Append(dn, rdnt);
518 Py_DECREF(rdnt);
519 if (retcode < 0)
520 goto fail0;
521 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000522
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000523 /* convert list to tuple */
524 rdnt = PyList_AsTuple(dn);
525 Py_DECREF(dn);
526 if (rdnt == NULL)
527 return NULL;
528 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000529
530 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000531 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000532
533 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000534 Py_XDECREF(dn);
535 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000536}
537
538static PyObject *
539_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000540
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000541 /* this code follows the procedure outlined in
542 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
543 function to extract the STACK_OF(GENERAL_NAME),
544 then iterates through the stack to add the
545 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000546
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000547 int i, j;
548 PyObject *peer_alt_names = Py_None;
549 PyObject *v, *t;
550 X509_EXTENSION *ext = NULL;
551 GENERAL_NAMES *names = NULL;
552 GENERAL_NAME *name;
553 X509V3_EXT_METHOD *method;
554 BIO *biobuf = NULL;
555 char buf[2048];
556 char *vptr;
557 int len;
558 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000559#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000560 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000561#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000562 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000563#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000564
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000565 if (certificate == NULL)
566 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000567
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000568 /* get a memory buffer */
569 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000570
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000571 i = 0;
572 while ((i = X509_get_ext_by_NID(
573 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000574
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000575 if (peer_alt_names == Py_None) {
576 peer_alt_names = PyList_New(0);
577 if (peer_alt_names == NULL)
578 goto fail;
579 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000580
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000581 /* now decode the altName */
582 ext = X509_get_ext(certificate, i);
583 if(!(method = X509V3_EXT_get(ext))) {
584 PyErr_SetString
585 (PySSLErrorObject,
586 ERRSTR("No method for internalizing subjectAltName!"));
587 goto fail;
588 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000589
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000590 p = ext->value->data;
591 if (method->it)
592 names = (GENERAL_NAMES*)
593 (ASN1_item_d2i(NULL,
594 &p,
595 ext->value->length,
596 ASN1_ITEM_ptr(method->it)));
597 else
598 names = (GENERAL_NAMES*)
599 (method->d2i(NULL,
600 &p,
601 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000602
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000603 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000604
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000605 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000606
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000607 name = sk_GENERAL_NAME_value(names, j);
608 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000609
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000610 /* we special-case DirName as a tuple of
611 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000612
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000613 t = PyTuple_New(2);
614 if (t == NULL) {
615 goto fail;
616 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000617
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000618 v = PyUnicode_FromString("DirName");
619 if (v == NULL) {
620 Py_DECREF(t);
621 goto fail;
622 }
623 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000624
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000625 v = _create_tuple_for_X509_NAME (name->d.dirn);
626 if (v == NULL) {
627 Py_DECREF(t);
628 goto fail;
629 }
630 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000631
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000632 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000633
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000634 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000635
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000636 (void) BIO_reset(biobuf);
637 GENERAL_NAME_print(biobuf, name);
638 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
639 if (len < 0) {
640 _setSSLError(NULL, 0, __FILE__, __LINE__);
641 goto fail;
642 }
643 vptr = strchr(buf, ':');
644 if (vptr == NULL)
645 goto fail;
646 t = PyTuple_New(2);
647 if (t == NULL)
648 goto fail;
649 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
650 if (v == NULL) {
651 Py_DECREF(t);
652 goto fail;
653 }
654 PyTuple_SET_ITEM(t, 0, v);
655 v = PyUnicode_FromStringAndSize((vptr + 1),
656 (len - (vptr - buf + 1)));
657 if (v == NULL) {
658 Py_DECREF(t);
659 goto fail;
660 }
661 PyTuple_SET_ITEM(t, 1, v);
662 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000663
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000664 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000665
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000666 if (PyList_Append(peer_alt_names, t) < 0) {
667 Py_DECREF(t);
668 goto fail;
669 }
670 Py_DECREF(t);
671 }
672 }
673 BIO_free(biobuf);
674 if (peer_alt_names != Py_None) {
675 v = PyList_AsTuple(peer_alt_names);
676 Py_DECREF(peer_alt_names);
677 return v;
678 } else {
679 return peer_alt_names;
680 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000681
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000682
683 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000684 if (biobuf != NULL)
685 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000686
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000687 if (peer_alt_names != Py_None) {
688 Py_XDECREF(peer_alt_names);
689 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000690
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000691 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000692}
693
694static PyObject *
695_decode_certificate (X509 *certificate, int verbose) {
696
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000697 PyObject *retval = NULL;
698 BIO *biobuf = NULL;
699 PyObject *peer;
700 PyObject *peer_alt_names = NULL;
701 PyObject *issuer;
702 PyObject *version;
703 PyObject *sn_obj;
704 ASN1_INTEGER *serialNumber;
705 char buf[2048];
706 int len;
707 ASN1_TIME *notBefore, *notAfter;
708 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000709
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000710 retval = PyDict_New();
711 if (retval == NULL)
712 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000713
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000714 peer = _create_tuple_for_X509_NAME(
715 X509_get_subject_name(certificate));
716 if (peer == NULL)
717 goto fail0;
718 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
719 Py_DECREF(peer);
720 goto fail0;
721 }
722 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000723
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000724 if (verbose) {
725 issuer = _create_tuple_for_X509_NAME(
726 X509_get_issuer_name(certificate));
727 if (issuer == NULL)
728 goto fail0;
729 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
730 Py_DECREF(issuer);
731 goto fail0;
732 }
733 Py_DECREF(issuer);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000734
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000735 version = PyLong_FromLong(X509_get_version(certificate) + 1);
736 if (PyDict_SetItemString(retval, "version", version) < 0) {
737 Py_DECREF(version);
738 goto fail0;
739 }
740 Py_DECREF(version);
741 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000742
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000743 /* get a memory buffer */
744 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000745
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000746 if (verbose) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000747
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000748 (void) BIO_reset(biobuf);
749 serialNumber = X509_get_serialNumber(certificate);
750 /* should not exceed 20 octets, 160 bits, so buf is big enough */
751 i2a_ASN1_INTEGER(biobuf, serialNumber);
752 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
753 if (len < 0) {
754 _setSSLError(NULL, 0, __FILE__, __LINE__);
755 goto fail1;
756 }
757 sn_obj = PyUnicode_FromStringAndSize(buf, len);
758 if (sn_obj == NULL)
759 goto fail1;
760 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
761 Py_DECREF(sn_obj);
762 goto fail1;
763 }
764 Py_DECREF(sn_obj);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000765
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000766 (void) BIO_reset(biobuf);
767 notBefore = X509_get_notBefore(certificate);
768 ASN1_TIME_print(biobuf, notBefore);
769 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
770 if (len < 0) {
771 _setSSLError(NULL, 0, __FILE__, __LINE__);
772 goto fail1;
773 }
774 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
775 if (pnotBefore == NULL)
776 goto fail1;
777 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
778 Py_DECREF(pnotBefore);
779 goto fail1;
780 }
781 Py_DECREF(pnotBefore);
782 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000783
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000784 (void) BIO_reset(biobuf);
785 notAfter = X509_get_notAfter(certificate);
786 ASN1_TIME_print(biobuf, notAfter);
787 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
788 if (len < 0) {
789 _setSSLError(NULL, 0, __FILE__, __LINE__);
790 goto fail1;
791 }
792 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
793 if (pnotAfter == NULL)
794 goto fail1;
795 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
796 Py_DECREF(pnotAfter);
797 goto fail1;
798 }
799 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000800
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000801 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000802
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 peer_alt_names = _get_peer_alt_names(certificate);
804 if (peer_alt_names == NULL)
805 goto fail1;
806 else if (peer_alt_names != Py_None) {
807 if (PyDict_SetItemString(retval, "subjectAltName",
808 peer_alt_names) < 0) {
809 Py_DECREF(peer_alt_names);
810 goto fail1;
811 }
812 Py_DECREF(peer_alt_names);
813 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000814
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000815 BIO_free(biobuf);
816 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000817
818 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000819 if (biobuf != NULL)
820 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000821 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000822 Py_XDECREF(retval);
823 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000824}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000825
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000826
827static PyObject *
828PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
829
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000830 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +0000831 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000832 X509 *x=NULL;
833 BIO *cert;
834 int verbose = 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000835
Victor Stinner3800e1e2010-05-16 21:23:48 +0000836 if (!PyArg_ParseTuple(args, "O&|i:test_decode_certificate",
837 PyUnicode_FSConverter, &filename, &verbose))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000838 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000839
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000840 if ((cert=BIO_new(BIO_s_file())) == NULL) {
841 PyErr_SetString(PySSLErrorObject,
842 "Can't malloc memory to read file");
843 goto fail0;
844 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000845
Victor Stinner3800e1e2010-05-16 21:23:48 +0000846 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000847 PyErr_SetString(PySSLErrorObject,
848 "Can't open file");
849 goto fail0;
850 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000851
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000852 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
853 if (x == NULL) {
854 PyErr_SetString(PySSLErrorObject,
855 "Error decoding PEM-encoded file");
856 goto fail0;
857 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000858
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000859 retval = _decode_certificate(x, verbose);
Mark Dickinsonee55df52010-08-03 18:31:54 +0000860 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000861
862 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +0000863 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000864 if (cert != NULL) BIO_free(cert);
865 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000866}
867
868
869static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000870PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000871{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000872 PyObject *retval = NULL;
873 int len;
874 int verification;
875 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000876
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000877 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
878 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000879
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000880 if (!self->peer_cert)
881 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000882
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000883 if (PyObject_IsTrue(binary_mode)) {
884 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000885
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000886 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000887
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000888 bytes_buf = NULL;
889 len = i2d_X509(self->peer_cert, &bytes_buf);
890 if (len < 0) {
891 PySSL_SetError(self, len, __FILE__, __LINE__);
892 return NULL;
893 }
894 /* this is actually an immutable bytes sequence */
895 retval = PyBytes_FromStringAndSize
896 ((const char *) bytes_buf, len);
897 OPENSSL_free(bytes_buf);
898 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000899
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000900 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000901 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000902 if ((verification & SSL_VERIFY_PEER) == 0)
903 return PyDict_New();
904 else
905 return _decode_certificate (self->peer_cert, 0);
906 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000907}
908
909PyDoc_STRVAR(PySSL_peercert_doc,
910"peer_certificate([der=False]) -> certificate\n\
911\n\
912Returns the certificate for the peer. If no certificate was provided,\n\
913returns None. If a certificate was provided, but not validated, returns\n\
914an empty dictionary. Otherwise returns a dict containing information\n\
915about the peer certificate.\n\
916\n\
917If the optional argument is True, returns a DER-encoded copy of the\n\
918peer certificate, or None if no certificate was provided. This will\n\
919return the certificate even if it wasn't validated.");
920
Antoine Pitrou152efa22010-05-16 18:19:27 +0000921static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000922
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000923 PyObject *retval, *v;
924 SSL_CIPHER *current;
925 char *cipher_name;
926 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000927
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000928 if (self->ssl == NULL)
929 return Py_None;
930 current = SSL_get_current_cipher(self->ssl);
931 if (current == NULL)
932 return Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000933
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000934 retval = PyTuple_New(3);
935 if (retval == NULL)
936 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000937
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 cipher_name = (char *) SSL_CIPHER_get_name(current);
939 if (cipher_name == NULL) {
940 PyTuple_SET_ITEM(retval, 0, Py_None);
941 } else {
942 v = PyUnicode_FromString(cipher_name);
943 if (v == NULL)
944 goto fail0;
945 PyTuple_SET_ITEM(retval, 0, v);
946 }
947 cipher_protocol = SSL_CIPHER_get_version(current);
948 if (cipher_protocol == NULL) {
949 PyTuple_SET_ITEM(retval, 1, Py_None);
950 } else {
951 v = PyUnicode_FromString(cipher_protocol);
952 if (v == NULL)
953 goto fail0;
954 PyTuple_SET_ITEM(retval, 1, v);
955 }
956 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
957 if (v == NULL)
958 goto fail0;
959 PyTuple_SET_ITEM(retval, 2, v);
960 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000961
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000962 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000963 Py_DECREF(retval);
964 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000965}
966
Antoine Pitrou152efa22010-05-16 18:19:27 +0000967static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000968{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000969 if (self->peer_cert) /* Possible not to have one? */
970 X509_free (self->peer_cert);
971 if (self->ssl)
972 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000973 Py_XDECREF(self->Socket);
974 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000975}
976
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000977/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000978 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000979 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000980 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000981
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000982static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000983check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000984{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000985 fd_set fds;
986 struct timeval tv;
987 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000988
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000989 /* Nothing to do unless we're in timeout mode (not non-blocking) */
990 if (s->sock_timeout < 0.0)
991 return SOCKET_IS_BLOCKING;
992 else if (s->sock_timeout == 0.0)
993 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000994
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000995 /* Guard against closed socket */
996 if (s->sock_fd < 0)
997 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000998
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000999 /* Prefer poll, if available, since you can poll() any fd
1000 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001001#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001002 {
1003 struct pollfd pollfd;
1004 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001005
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001006 pollfd.fd = s->sock_fd;
1007 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001008
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001009 /* s->sock_timeout is in seconds, timeout in ms */
1010 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1011 PySSL_BEGIN_ALLOW_THREADS
1012 rc = poll(&pollfd, 1, timeout);
1013 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001014
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001015 goto normal_return;
1016 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001017#endif
1018
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001019 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001020#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001021 if (s->sock_fd >= FD_SETSIZE)
1022 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001023#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001024
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001025 /* Construct the arguments to select */
1026 tv.tv_sec = (int)s->sock_timeout;
1027 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1028 FD_ZERO(&fds);
1029 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001030
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001031 /* See if the socket is ready */
1032 PySSL_BEGIN_ALLOW_THREADS
1033 if (writing)
1034 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1035 else
1036 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1037 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001038
Bill Janssen6e027db2007-11-15 22:23:56 +00001039#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001040normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001041#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001042 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1043 (when we are able to write or when there's something to read) */
1044 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001045}
1046
Antoine Pitrou152efa22010-05-16 18:19:27 +00001047static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001048{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001049 Py_buffer buf;
1050 int len;
1051 int sockstate;
1052 int err;
1053 int nonblocking;
1054 PySocketSockObject *sock
1055 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001056
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 if (((PyObject*)sock) == Py_None) {
1058 _setSSLError("Underlying socket connection gone",
1059 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1060 return NULL;
1061 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001062 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001063
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001064 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1065 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001066 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001067 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001068
1069 /* just in case the blocking state of the socket has been changed */
1070 nonblocking = (sock->sock_timeout >= 0.0);
1071 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1072 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1073
1074 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1075 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1076 PyErr_SetString(PySSLErrorObject,
1077 "The write operation timed out");
1078 goto error;
1079 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1080 PyErr_SetString(PySSLErrorObject,
1081 "Underlying socket has been closed.");
1082 goto error;
1083 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1084 PyErr_SetString(PySSLErrorObject,
1085 "Underlying socket too large for select().");
1086 goto error;
1087 }
1088 do {
1089 err = 0;
1090 PySSL_BEGIN_ALLOW_THREADS
1091 len = SSL_write(self->ssl, buf.buf, buf.len);
1092 err = SSL_get_error(self->ssl, len);
1093 PySSL_END_ALLOW_THREADS
1094 if (PyErr_CheckSignals()) {
1095 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001096 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001097 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001098 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001099 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001100 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001101 } else {
1102 sockstate = SOCKET_OPERATION_OK;
1103 }
1104 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1105 PyErr_SetString(PySSLErrorObject,
1106 "The write operation timed out");
1107 goto error;
1108 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1109 PyErr_SetString(PySSLErrorObject,
1110 "Underlying socket has been closed.");
1111 goto error;
1112 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1113 break;
1114 }
1115 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001116
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001117 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001118 PyBuffer_Release(&buf);
1119 if (len > 0)
1120 return PyLong_FromLong(len);
1121 else
1122 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001123
1124error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001125 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001126 PyBuffer_Release(&buf);
1127 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001128}
1129
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001130PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001131"write(s) -> len\n\
1132\n\
1133Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001134of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001135
Antoine Pitrou152efa22010-05-16 18:19:27 +00001136static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001137{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001138 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001139
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001140 PySSL_BEGIN_ALLOW_THREADS
1141 count = SSL_pending(self->ssl);
1142 PySSL_END_ALLOW_THREADS
1143 if (count < 0)
1144 return PySSL_SetError(self, count, __FILE__, __LINE__);
1145 else
1146 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001147}
1148
1149PyDoc_STRVAR(PySSL_SSLpending_doc,
1150"pending() -> count\n\
1151\n\
1152Returns the number of already decrypted bytes available for read,\n\
1153pending on the connection.\n");
1154
Antoine Pitrou152efa22010-05-16 18:19:27 +00001155static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001156{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001157 PyObject *dest = NULL;
1158 Py_buffer buf;
1159 int buf_passed = 0;
1160 int count = -1;
1161 char *mem;
1162 /* XXX this should use Py_ssize_t */
1163 int len = 1024;
1164 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
1177 if (!PyArg_ParseTuple(args, "|Oi:read", &dest, &count))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001178 goto error;
1179
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001180 if ((dest == NULL) || (dest == Py_None)) {
1181 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001182 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001183 mem = PyByteArray_AS_STRING(dest);
1184 } else if (PyLong_Check(dest)) {
1185 len = PyLong_AS_LONG(dest);
1186 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001187 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001188 mem = PyByteArray_AS_STRING(dest);
1189 } else {
1190 if (PyObject_GetBuffer(dest, &buf, PyBUF_CONTIG) < 0)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001191 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001192 mem = buf.buf;
1193 len = buf.len;
1194 if ((count > 0) && (count <= len))
1195 len = count;
1196 buf_passed = 1;
1197 }
1198
1199 /* just in case the blocking state of the socket has been changed */
1200 nonblocking = (sock->sock_timeout >= 0.0);
1201 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1202 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1203
1204 /* first check if there are bytes ready to be read */
1205 PySSL_BEGIN_ALLOW_THREADS
1206 count = SSL_pending(self->ssl);
1207 PySSL_END_ALLOW_THREADS
1208
1209 if (!count) {
1210 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1211 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1212 PyErr_SetString(PySSLErrorObject,
1213 "The read operation timed out");
1214 goto error;
1215 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1216 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001217 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001218 goto error;
1219 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1220 count = 0;
1221 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001222 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001223 }
1224 do {
1225 err = 0;
1226 PySSL_BEGIN_ALLOW_THREADS
1227 count = SSL_read(self->ssl, mem, len);
1228 err = SSL_get_error(self->ssl, count);
1229 PySSL_END_ALLOW_THREADS
1230 if (PyErr_CheckSignals())
1231 goto error;
1232 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001233 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001234 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001235 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001236 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1237 (SSL_get_shutdown(self->ssl) ==
1238 SSL_RECEIVED_SHUTDOWN))
1239 {
1240 count = 0;
1241 goto done;
1242 } else {
1243 sockstate = SOCKET_OPERATION_OK;
1244 }
1245 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1246 PyErr_SetString(PySSLErrorObject,
1247 "The read operation timed out");
1248 goto error;
1249 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1250 break;
1251 }
1252 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1253 if (count <= 0) {
1254 PySSL_SetError(self, count, __FILE__, __LINE__);
1255 goto error;
1256 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001257 done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001258 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001259 if (!buf_passed) {
1260 PyObject *res = PyBytes_FromStringAndSize(mem, count);
1261 Py_DECREF(dest);
1262 return res;
1263 } else {
1264 PyBuffer_Release(&buf);
1265 return PyLong_FromLong(count);
1266 }
Benjamin Peterson56420b42009-02-28 19:06:54 +00001267 error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001268 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001269 if (!buf_passed) {
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001270 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001271 } else {
1272 PyBuffer_Release(&buf);
1273 }
1274 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001275}
1276
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001277PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001278"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001279\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001280Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001281
Antoine Pitrou152efa22010-05-16 18:19:27 +00001282static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001283{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001284 int err, ssl_err, sockstate, nonblocking;
1285 int zeros = 0;
1286 PySocketSockObject *sock
1287 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001288
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001289 /* Guard against closed socket */
1290 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1291 _setSSLError("Underlying socket connection gone",
1292 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1293 return NULL;
1294 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001295 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001296
1297 /* Just in case the blocking state of the socket has been changed */
1298 nonblocking = (sock->sock_timeout >= 0.0);
1299 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1300 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1301
1302 while (1) {
1303 PySSL_BEGIN_ALLOW_THREADS
1304 /* Disable read-ahead so that unwrap can work correctly.
1305 * Otherwise OpenSSL might read in too much data,
1306 * eating clear text data that happens to be
1307 * transmitted after the SSL shutdown.
1308 * Should be safe to call repeatedly everytime this
1309 * function is used and the shutdown_seen_zero != 0
1310 * condition is met.
1311 */
1312 if (self->shutdown_seen_zero)
1313 SSL_set_read_ahead(self->ssl, 0);
1314 err = SSL_shutdown(self->ssl);
1315 PySSL_END_ALLOW_THREADS
1316 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1317 if (err > 0)
1318 break;
1319 if (err == 0) {
1320 /* Don't loop endlessly; instead preserve legacy
1321 behaviour of trying SSL_shutdown() only twice.
1322 This looks necessary for OpenSSL < 0.9.8m */
1323 if (++zeros > 1)
1324 break;
1325 /* Shutdown was sent, now try receiving */
1326 self->shutdown_seen_zero = 1;
1327 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001328 }
1329
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001330 /* Possibly retry shutdown until timeout or failure */
1331 ssl_err = SSL_get_error(self->ssl, err);
1332 if (ssl_err == SSL_ERROR_WANT_READ)
1333 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1334 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1335 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1336 else
1337 break;
1338 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1339 if (ssl_err == SSL_ERROR_WANT_READ)
1340 PyErr_SetString(PySSLErrorObject,
1341 "The read operation timed out");
1342 else
1343 PyErr_SetString(PySSLErrorObject,
1344 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001345 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001346 }
1347 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1348 PyErr_SetString(PySSLErrorObject,
1349 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001350 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001351 }
1352 else if (sockstate != SOCKET_OPERATION_OK)
1353 /* Retain the SSL error code */
1354 break;
1355 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001356
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001357 if (err < 0) {
1358 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001359 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001360 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001361 else
1362 /* It's already INCREF'ed */
1363 return (PyObject *) sock;
1364
1365error:
1366 Py_DECREF(sock);
1367 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001368}
1369
1370PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1371"shutdown(s) -> socket\n\
1372\n\
1373Does the SSL shutdown handshake with the remote end, and returns\n\
1374the underlying socket object.");
1375
1376
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001377static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001378 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1379 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1380 PySSL_SSLwrite_doc},
1381 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1382 PySSL_SSLread_doc},
1383 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1384 PySSL_SSLpending_doc},
1385 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1386 PySSL_peercert_doc},
1387 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1388 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1389 PySSL_SSLshutdown_doc},
1390 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001391};
1392
Antoine Pitrou152efa22010-05-16 18:19:27 +00001393static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001394 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001395 "_ssl._SSLSocket", /*tp_name*/
1396 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001397 0, /*tp_itemsize*/
1398 /* methods */
1399 (destructor)PySSL_dealloc, /*tp_dealloc*/
1400 0, /*tp_print*/
1401 0, /*tp_getattr*/
1402 0, /*tp_setattr*/
1403 0, /*tp_reserved*/
1404 0, /*tp_repr*/
1405 0, /*tp_as_number*/
1406 0, /*tp_as_sequence*/
1407 0, /*tp_as_mapping*/
1408 0, /*tp_hash*/
1409 0, /*tp_call*/
1410 0, /*tp_str*/
1411 0, /*tp_getattro*/
1412 0, /*tp_setattro*/
1413 0, /*tp_as_buffer*/
1414 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1415 0, /*tp_doc*/
1416 0, /*tp_traverse*/
1417 0, /*tp_clear*/
1418 0, /*tp_richcompare*/
1419 0, /*tp_weaklistoffset*/
1420 0, /*tp_iter*/
1421 0, /*tp_iternext*/
1422 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001423};
1424
Antoine Pitrou152efa22010-05-16 18:19:27 +00001425
1426/*
1427 * _SSLContext objects
1428 */
1429
1430static PyObject *
1431context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1432{
1433 char *kwlist[] = {"protocol", NULL};
1434 PySSLContext *self;
1435 int proto_version = PY_SSL_VERSION_SSL23;
1436 SSL_CTX *ctx = NULL;
1437
1438 if (!PyArg_ParseTupleAndKeywords(
1439 args, kwds, "i:_SSLContext", kwlist,
1440 &proto_version))
1441 return NULL;
1442
1443 PySSL_BEGIN_ALLOW_THREADS
1444 if (proto_version == PY_SSL_VERSION_TLS1)
1445 ctx = SSL_CTX_new(TLSv1_method());
1446 else if (proto_version == PY_SSL_VERSION_SSL3)
1447 ctx = SSL_CTX_new(SSLv3_method());
1448 else if (proto_version == PY_SSL_VERSION_SSL2)
1449 ctx = SSL_CTX_new(SSLv2_method());
1450 else if (proto_version == PY_SSL_VERSION_SSL23)
1451 ctx = SSL_CTX_new(SSLv23_method());
1452 else
1453 proto_version = -1;
1454 PySSL_END_ALLOW_THREADS
1455
1456 if (proto_version == -1) {
1457 PyErr_SetString(PyExc_ValueError,
1458 "invalid protocol version");
1459 return NULL;
1460 }
1461 if (ctx == NULL) {
1462 PyErr_SetString(PySSLErrorObject,
1463 "failed to allocate SSL context");
1464 return NULL;
1465 }
1466
1467 assert(type != NULL && type->tp_alloc != NULL);
1468 self = (PySSLContext *) type->tp_alloc(type, 0);
1469 if (self == NULL) {
1470 SSL_CTX_free(ctx);
1471 return NULL;
1472 }
1473 self->ctx = ctx;
1474 /* Defaults */
1475 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
1476 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
1477
1478 return (PyObject *)self;
1479}
1480
1481static void
1482context_dealloc(PySSLContext *self)
1483{
1484 SSL_CTX_free(self->ctx);
1485 Py_TYPE(self)->tp_free(self);
1486}
1487
1488static PyObject *
1489set_ciphers(PySSLContext *self, PyObject *args)
1490{
1491 int ret;
1492 const char *cipherlist;
1493
1494 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1495 return NULL;
1496 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1497 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001498 /* Clearing the error queue is necessary on some OpenSSL versions,
1499 otherwise the error will be reported again when another SSL call
1500 is done. */
1501 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001502 PyErr_SetString(PySSLErrorObject,
1503 "No cipher can be selected.");
1504 return NULL;
1505 }
1506 Py_RETURN_NONE;
1507}
1508
1509static PyObject *
1510get_verify_mode(PySSLContext *self, void *c)
1511{
1512 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1513 case SSL_VERIFY_NONE:
1514 return PyLong_FromLong(PY_SSL_CERT_NONE);
1515 case SSL_VERIFY_PEER:
1516 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1517 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1518 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1519 }
1520 PyErr_SetString(PySSLErrorObject,
1521 "invalid return value from SSL_CTX_get_verify_mode");
1522 return NULL;
1523}
1524
1525static int
1526set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1527{
1528 int n, mode;
1529 if (!PyArg_Parse(arg, "i", &n))
1530 return -1;
1531 if (n == PY_SSL_CERT_NONE)
1532 mode = SSL_VERIFY_NONE;
1533 else if (n == PY_SSL_CERT_OPTIONAL)
1534 mode = SSL_VERIFY_PEER;
1535 else if (n == PY_SSL_CERT_REQUIRED)
1536 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1537 else {
1538 PyErr_SetString(PyExc_ValueError,
1539 "invalid value for verify_mode");
1540 return -1;
1541 }
1542 SSL_CTX_set_verify(self->ctx, mode, NULL);
1543 return 0;
1544}
1545
1546static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001547get_options(PySSLContext *self, void *c)
1548{
1549 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1550}
1551
1552static int
1553set_options(PySSLContext *self, PyObject *arg, void *c)
1554{
1555 long new_opts, opts, set, clear;
1556 if (!PyArg_Parse(arg, "l", &new_opts))
1557 return -1;
1558 opts = SSL_CTX_get_options(self->ctx);
1559 clear = opts & ~new_opts;
1560 set = ~opts & new_opts;
1561 if (clear) {
1562#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1563 SSL_CTX_clear_options(self->ctx, clear);
1564#else
1565 PyErr_SetString(PyExc_ValueError,
1566 "can't clear options before OpenSSL 0.9.8m");
1567 return -1;
1568#endif
1569 }
1570 if (set)
1571 SSL_CTX_set_options(self->ctx, set);
1572 return 0;
1573}
1574
1575static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001576load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
1577{
1578 char *kwlist[] = {"certfile", "keyfile", NULL};
1579 PyObject *certfile, *keyfile = NULL;
1580 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
1581 int r;
1582
1583 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1584 "O|O:load_cert_chain", kwlist,
1585 &certfile, &keyfile))
1586 return NULL;
1587 if (keyfile == Py_None)
1588 keyfile = NULL;
1589 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
1590 PyErr_SetString(PyExc_TypeError,
1591 "certfile should be a valid filesystem path");
1592 return NULL;
1593 }
1594 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
1595 PyErr_SetString(PyExc_TypeError,
1596 "keyfile should be a valid filesystem path");
1597 goto error;
1598 }
1599 PySSL_BEGIN_ALLOW_THREADS
1600 r = SSL_CTX_use_certificate_chain_file(self->ctx,
1601 PyBytes_AS_STRING(certfile_bytes));
1602 PySSL_END_ALLOW_THREADS
1603 if (r != 1) {
1604 _setSSLError(NULL, 0, __FILE__, __LINE__);
1605 goto error;
1606 }
1607 PySSL_BEGIN_ALLOW_THREADS
1608 r = SSL_CTX_use_RSAPrivateKey_file(self->ctx,
1609 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
1610 SSL_FILETYPE_PEM);
1611 PySSL_END_ALLOW_THREADS
1612 Py_XDECREF(keyfile_bytes);
1613 Py_XDECREF(certfile_bytes);
1614 if (r != 1) {
1615 _setSSLError(NULL, 0, __FILE__, __LINE__);
1616 return NULL;
1617 }
1618 PySSL_BEGIN_ALLOW_THREADS
1619 r = SSL_CTX_check_private_key(self->ctx);
1620 PySSL_END_ALLOW_THREADS
1621 if (r != 1) {
1622 _setSSLError(NULL, 0, __FILE__, __LINE__);
1623 return NULL;
1624 }
1625 Py_RETURN_NONE;
1626
1627error:
1628 Py_XDECREF(keyfile_bytes);
1629 Py_XDECREF(certfile_bytes);
1630 return NULL;
1631}
1632
1633static PyObject *
1634load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
1635{
1636 char *kwlist[] = {"cafile", "capath", NULL};
1637 PyObject *cafile = NULL, *capath = NULL;
1638 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
1639 const char *cafile_buf = NULL, *capath_buf = NULL;
1640 int r;
1641
1642 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1643 "|OO:load_verify_locations", kwlist,
1644 &cafile, &capath))
1645 return NULL;
1646 if (cafile == Py_None)
1647 cafile = NULL;
1648 if (capath == Py_None)
1649 capath = NULL;
1650 if (cafile == NULL && capath == NULL) {
1651 PyErr_SetString(PyExc_TypeError,
1652 "cafile and capath cannot be both omitted");
1653 return NULL;
1654 }
1655 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
1656 PyErr_SetString(PyExc_TypeError,
1657 "cafile should be a valid filesystem path");
1658 return NULL;
1659 }
1660 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
1661 Py_DECREF(cafile_bytes);
1662 PyErr_SetString(PyExc_TypeError,
1663 "capath should be a valid filesystem path");
1664 return NULL;
1665 }
1666 if (cafile)
1667 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
1668 if (capath)
1669 capath_buf = PyBytes_AS_STRING(capath_bytes);
1670 PySSL_BEGIN_ALLOW_THREADS
1671 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
1672 PySSL_END_ALLOW_THREADS
1673 Py_XDECREF(cafile_bytes);
1674 Py_XDECREF(capath_bytes);
1675 if (r != 1) {
1676 _setSSLError(NULL, 0, __FILE__, __LINE__);
1677 return NULL;
1678 }
1679 Py_RETURN_NONE;
1680}
1681
1682static PyObject *
1683context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
1684{
1685 char *kwlist[] = {"sock", "server_side", NULL};
1686 PySocketSockObject *sock;
1687 int server_side = 0;
1688
1689 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i:_wrap_socket", kwlist,
1690 PySocketModule.Sock_Type,
1691 &sock, &server_side))
1692 return NULL;
1693
1694 return (PyObject *) newPySSLSocket(self->ctx, sock, server_side);
1695}
1696
1697static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00001698 {"options", (getter) get_options,
1699 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00001700 {"verify_mode", (getter) get_verify_mode,
1701 (setter) set_verify_mode, NULL},
1702 {NULL}, /* sentinel */
1703};
1704
1705static struct PyMethodDef context_methods[] = {
1706 {"_wrap_socket", (PyCFunction) context_wrap_socket,
1707 METH_VARARGS | METH_KEYWORDS, NULL},
1708 {"set_ciphers", (PyCFunction) set_ciphers,
1709 METH_VARARGS, NULL},
1710 {"load_cert_chain", (PyCFunction) load_cert_chain,
1711 METH_VARARGS | METH_KEYWORDS, NULL},
1712 {"load_verify_locations", (PyCFunction) load_verify_locations,
1713 METH_VARARGS | METH_KEYWORDS, NULL},
1714 {NULL, NULL} /* sentinel */
1715};
1716
1717static PyTypeObject PySSLContext_Type = {
1718 PyVarObject_HEAD_INIT(NULL, 0)
1719 "_ssl._SSLContext", /*tp_name*/
1720 sizeof(PySSLContext), /*tp_basicsize*/
1721 0, /*tp_itemsize*/
1722 (destructor)context_dealloc, /*tp_dealloc*/
1723 0, /*tp_print*/
1724 0, /*tp_getattr*/
1725 0, /*tp_setattr*/
1726 0, /*tp_reserved*/
1727 0, /*tp_repr*/
1728 0, /*tp_as_number*/
1729 0, /*tp_as_sequence*/
1730 0, /*tp_as_mapping*/
1731 0, /*tp_hash*/
1732 0, /*tp_call*/
1733 0, /*tp_str*/
1734 0, /*tp_getattro*/
1735 0, /*tp_setattro*/
1736 0, /*tp_as_buffer*/
1737 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
1738 0, /*tp_doc*/
1739 0, /*tp_traverse*/
1740 0, /*tp_clear*/
1741 0, /*tp_richcompare*/
1742 0, /*tp_weaklistoffset*/
1743 0, /*tp_iter*/
1744 0, /*tp_iternext*/
1745 context_methods, /*tp_methods*/
1746 0, /*tp_members*/
1747 context_getsetlist, /*tp_getset*/
1748 0, /*tp_base*/
1749 0, /*tp_dict*/
1750 0, /*tp_descr_get*/
1751 0, /*tp_descr_set*/
1752 0, /*tp_dictoffset*/
1753 0, /*tp_init*/
1754 0, /*tp_alloc*/
1755 context_new, /*tp_new*/
1756};
1757
1758
1759
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001760#ifdef HAVE_OPENSSL_RAND
1761
1762/* helper routines for seeding the SSL PRNG */
1763static PyObject *
1764PySSL_RAND_add(PyObject *self, PyObject *args)
1765{
1766 char *buf;
1767 int len;
1768 double entropy;
1769
1770 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00001771 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001772 RAND_add(buf, len, entropy);
1773 Py_INCREF(Py_None);
1774 return Py_None;
1775}
1776
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001777PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001778"RAND_add(string, entropy)\n\
1779\n\
1780Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001781bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001782
1783static PyObject *
1784PySSL_RAND_status(PyObject *self)
1785{
Christian Heimes217cfd12007-12-02 14:31:20 +00001786 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001787}
1788
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001789PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001790"RAND_status() -> 0 or 1\n\
1791\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001792Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1793It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1794using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001795
1796static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001797PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001798{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001799 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001800 int bytes;
1801
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001802 if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
1803 PyUnicode_FSConverter, &path))
1804 return NULL;
1805
1806 bytes = RAND_egd(PyBytes_AsString(path));
1807 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001808 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001809 PyErr_SetString(PySSLErrorObject,
1810 "EGD connection failed or EGD did not return "
1811 "enough data to seed the PRNG");
1812 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001813 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001814 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001815}
1816
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001817PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001818"RAND_egd(path) -> bytes\n\
1819\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001820Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1821Returns number of bytes read. Raises SSLError if connection to EGD\n\
1822fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001823
1824#endif
1825
Bill Janssen40a0f662008-08-12 16:56:25 +00001826
1827
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001828/* List of functions exported by this module. */
1829
1830static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001831 {"_test_decode_cert", PySSL_test_decode_certificate,
1832 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001833#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001834 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1835 PySSL_RAND_add_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001836 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001837 PySSL_RAND_egd_doc},
1838 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1839 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001840#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001841 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001842};
1843
1844
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001845#ifdef WITH_THREAD
1846
1847/* an implementation of OpenSSL threading operations in terms
1848 of the Python C thread library */
1849
1850static PyThread_type_lock *_ssl_locks = NULL;
1851
1852static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001853 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001854}
1855
Bill Janssen6e027db2007-11-15 22:23:56 +00001856static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001857 (int mode, int n, const char *file, int line) {
1858 /* this function is needed to perform locking on shared data
1859 structures. (Note that OpenSSL uses a number of global data
1860 structures that will be implicitly shared whenever multiple
1861 threads use OpenSSL.) Multi-threaded applications will
1862 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001863
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001864 locking_function() must be able to handle up to
1865 CRYPTO_num_locks() different mutex locks. It sets the n-th
1866 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001867
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001868 file and line are the file number of the function setting the
1869 lock. They can be useful for debugging.
1870 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001871
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001872 if ((_ssl_locks == NULL) ||
1873 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1874 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001875
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001876 if (mode & CRYPTO_LOCK) {
1877 PyThread_acquire_lock(_ssl_locks[n], 1);
1878 } else {
1879 PyThread_release_lock(_ssl_locks[n]);
1880 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001881}
1882
1883static int _setup_ssl_threads(void) {
1884
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001885 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001886
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001887 if (_ssl_locks == NULL) {
1888 _ssl_locks_count = CRYPTO_num_locks();
1889 _ssl_locks = (PyThread_type_lock *)
1890 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1891 if (_ssl_locks == NULL)
1892 return 0;
1893 memset(_ssl_locks, 0,
1894 sizeof(PyThread_type_lock) * _ssl_locks_count);
1895 for (i = 0; i < _ssl_locks_count; i++) {
1896 _ssl_locks[i] = PyThread_allocate_lock();
1897 if (_ssl_locks[i] == NULL) {
1898 unsigned int j;
1899 for (j = 0; j < i; j++) {
1900 PyThread_free_lock(_ssl_locks[j]);
1901 }
1902 free(_ssl_locks);
1903 return 0;
1904 }
1905 }
1906 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1907 CRYPTO_set_id_callback(_ssl_thread_id_function);
1908 }
1909 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001910}
1911
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001912#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001913
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001914PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001915"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001916for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001917
Martin v. Löwis1a214512008-06-11 05:26:20 +00001918
1919static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001920 PyModuleDef_HEAD_INIT,
1921 "_ssl",
1922 module_doc,
1923 -1,
1924 PySSL_methods,
1925 NULL,
1926 NULL,
1927 NULL,
1928 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001929};
1930
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001931PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001932PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001933{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001934 PyObject *m, *d, *r;
1935 unsigned long libver;
1936 unsigned int major, minor, fix, patch, status;
1937 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001938
Antoine Pitrou152efa22010-05-16 18:19:27 +00001939 if (PyType_Ready(&PySSLContext_Type) < 0)
1940 return NULL;
1941 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001942 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001943
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001944 m = PyModule_Create(&_sslmodule);
1945 if (m == NULL)
1946 return NULL;
1947 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001948
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001949 /* Load _socket module and its C API */
1950 socket_api = PySocketModule_ImportModuleAndAPI();
1951 if (!socket_api)
1952 return NULL;
1953 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001954
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001955 /* Init OpenSSL */
1956 SSL_load_error_strings();
1957 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001958#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001959 /* note that this will start threading if not already started */
1960 if (!_setup_ssl_threads()) {
1961 return NULL;
1962 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001963#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001964 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001965
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001966 /* Add symbols to module dict */
1967 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
1968 PySocketModule.error,
1969 NULL);
1970 if (PySSLErrorObject == NULL)
1971 return NULL;
1972 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
1973 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001974 if (PyDict_SetItemString(d, "_SSLContext",
1975 (PyObject *)&PySSLContext_Type) != 0)
1976 return NULL;
1977 if (PyDict_SetItemString(d, "_SSLSocket",
1978 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001979 return NULL;
1980 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
1981 PY_SSL_ERROR_ZERO_RETURN);
1982 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
1983 PY_SSL_ERROR_WANT_READ);
1984 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
1985 PY_SSL_ERROR_WANT_WRITE);
1986 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
1987 PY_SSL_ERROR_WANT_X509_LOOKUP);
1988 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
1989 PY_SSL_ERROR_SYSCALL);
1990 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
1991 PY_SSL_ERROR_SSL);
1992 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1993 PY_SSL_ERROR_WANT_CONNECT);
1994 /* non ssl.h errorcodes */
1995 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1996 PY_SSL_ERROR_EOF);
1997 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1998 PY_SSL_ERROR_INVALID_ERROR_CODE);
1999 /* cert requirements */
2000 PyModule_AddIntConstant(m, "CERT_NONE",
2001 PY_SSL_CERT_NONE);
2002 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2003 PY_SSL_CERT_OPTIONAL);
2004 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2005 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002006
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002007 /* protocol versions */
2008 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2009 PY_SSL_VERSION_SSL2);
2010 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2011 PY_SSL_VERSION_SSL3);
2012 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2013 PY_SSL_VERSION_SSL23);
2014 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2015 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002016
Antoine Pitroub5218772010-05-21 09:56:06 +00002017 /* protocol options */
2018 PyModule_AddIntConstant(m, "OP_ALL", SSL_OP_ALL);
2019 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2020 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2021 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
2022
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002023 /* OpenSSL version */
2024 /* SSLeay() gives us the version of the library linked against,
2025 which could be different from the headers version.
2026 */
2027 libver = SSLeay();
2028 r = PyLong_FromUnsignedLong(libver);
2029 if (r == NULL)
2030 return NULL;
2031 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2032 return NULL;
2033 status = libver & 0xF;
2034 libver >>= 4;
2035 patch = libver & 0xFF;
2036 libver >>= 8;
2037 fix = libver & 0xFF;
2038 libver >>= 8;
2039 minor = libver & 0xFF;
2040 libver >>= 8;
2041 major = libver & 0xFF;
2042 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2043 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2044 return NULL;
2045 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2046 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2047 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002048
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002049 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002050}