blob: 5428c7a8b87a5957afa881e36480e7c9e4dece3f [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);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000860
861 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +0000862 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000863 if (cert != NULL) BIO_free(cert);
864 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000865}
866
867
868static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000869PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000870{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000871 PyObject *retval = NULL;
872 int len;
873 int verification;
874 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000875
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000876 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
877 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000878
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000879 if (!self->peer_cert)
880 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000881
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000882 if (PyObject_IsTrue(binary_mode)) {
883 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000884
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000885 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000886
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000887 bytes_buf = NULL;
888 len = i2d_X509(self->peer_cert, &bytes_buf);
889 if (len < 0) {
890 PySSL_SetError(self, len, __FILE__, __LINE__);
891 return NULL;
892 }
893 /* this is actually an immutable bytes sequence */
894 retval = PyBytes_FromStringAndSize
895 ((const char *) bytes_buf, len);
896 OPENSSL_free(bytes_buf);
897 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000898
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000899 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000900 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000901 if ((verification & SSL_VERIFY_PEER) == 0)
902 return PyDict_New();
903 else
904 return _decode_certificate (self->peer_cert, 0);
905 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000906}
907
908PyDoc_STRVAR(PySSL_peercert_doc,
909"peer_certificate([der=False]) -> certificate\n\
910\n\
911Returns the certificate for the peer. If no certificate was provided,\n\
912returns None. If a certificate was provided, but not validated, returns\n\
913an empty dictionary. Otherwise returns a dict containing information\n\
914about the peer certificate.\n\
915\n\
916If the optional argument is True, returns a DER-encoded copy of the\n\
917peer certificate, or None if no certificate was provided. This will\n\
918return the certificate even if it wasn't validated.");
919
Antoine Pitrou152efa22010-05-16 18:19:27 +0000920static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000921
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000922 PyObject *retval, *v;
923 SSL_CIPHER *current;
924 char *cipher_name;
925 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000926
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000927 if (self->ssl == NULL)
928 return Py_None;
929 current = SSL_get_current_cipher(self->ssl);
930 if (current == NULL)
931 return Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000932
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000933 retval = PyTuple_New(3);
934 if (retval == NULL)
935 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000936
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000937 cipher_name = (char *) SSL_CIPHER_get_name(current);
938 if (cipher_name == NULL) {
939 PyTuple_SET_ITEM(retval, 0, Py_None);
940 } else {
941 v = PyUnicode_FromString(cipher_name);
942 if (v == NULL)
943 goto fail0;
944 PyTuple_SET_ITEM(retval, 0, v);
945 }
946 cipher_protocol = SSL_CIPHER_get_version(current);
947 if (cipher_protocol == NULL) {
948 PyTuple_SET_ITEM(retval, 1, Py_None);
949 } else {
950 v = PyUnicode_FromString(cipher_protocol);
951 if (v == NULL)
952 goto fail0;
953 PyTuple_SET_ITEM(retval, 1, v);
954 }
955 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
956 if (v == NULL)
957 goto fail0;
958 PyTuple_SET_ITEM(retval, 2, v);
959 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000960
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000961 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000962 Py_DECREF(retval);
963 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000964}
965
Antoine Pitrou152efa22010-05-16 18:19:27 +0000966static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000967{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000968 if (self->peer_cert) /* Possible not to have one? */
969 X509_free (self->peer_cert);
970 if (self->ssl)
971 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000972 Py_XDECREF(self->Socket);
973 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000974}
975
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000976/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000977 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000978 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000979 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000980
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000981static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000982check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000983{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000984 fd_set fds;
985 struct timeval tv;
986 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000987
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000988 /* Nothing to do unless we're in timeout mode (not non-blocking) */
989 if (s->sock_timeout < 0.0)
990 return SOCKET_IS_BLOCKING;
991 else if (s->sock_timeout == 0.0)
992 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000993
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000994 /* Guard against closed socket */
995 if (s->sock_fd < 0)
996 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000997
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000998 /* Prefer poll, if available, since you can poll() any fd
999 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001000#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001001 {
1002 struct pollfd pollfd;
1003 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001004
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001005 pollfd.fd = s->sock_fd;
1006 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001007
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001008 /* s->sock_timeout is in seconds, timeout in ms */
1009 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1010 PySSL_BEGIN_ALLOW_THREADS
1011 rc = poll(&pollfd, 1, timeout);
1012 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001013
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001014 goto normal_return;
1015 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001016#endif
1017
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001018 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001019#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001020 if (s->sock_fd >= FD_SETSIZE)
1021 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001022#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001023
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001024 /* Construct the arguments to select */
1025 tv.tv_sec = (int)s->sock_timeout;
1026 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1027 FD_ZERO(&fds);
1028 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001029
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001030 /* See if the socket is ready */
1031 PySSL_BEGIN_ALLOW_THREADS
1032 if (writing)
1033 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1034 else
1035 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1036 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001037
Bill Janssen6e027db2007-11-15 22:23:56 +00001038#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001039normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001040#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001041 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1042 (when we are able to write or when there's something to read) */
1043 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001044}
1045
Antoine Pitrou152efa22010-05-16 18:19:27 +00001046static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001047{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001048 Py_buffer buf;
1049 int len;
1050 int sockstate;
1051 int err;
1052 int nonblocking;
1053 PySocketSockObject *sock
1054 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001055
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001056 if (((PyObject*)sock) == Py_None) {
1057 _setSSLError("Underlying socket connection gone",
1058 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1059 return NULL;
1060 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001061 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001062
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001063 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1064 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001065 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001066 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001067
1068 /* just in case the blocking state of the socket has been changed */
1069 nonblocking = (sock->sock_timeout >= 0.0);
1070 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1071 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1072
1073 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1074 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1075 PyErr_SetString(PySSLErrorObject,
1076 "The write operation timed out");
1077 goto error;
1078 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1079 PyErr_SetString(PySSLErrorObject,
1080 "Underlying socket has been closed.");
1081 goto error;
1082 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1083 PyErr_SetString(PySSLErrorObject,
1084 "Underlying socket too large for select().");
1085 goto error;
1086 }
1087 do {
1088 err = 0;
1089 PySSL_BEGIN_ALLOW_THREADS
1090 len = SSL_write(self->ssl, buf.buf, buf.len);
1091 err = SSL_get_error(self->ssl, len);
1092 PySSL_END_ALLOW_THREADS
1093 if (PyErr_CheckSignals()) {
1094 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001095 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001096 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001097 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001098 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001099 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001100 } else {
1101 sockstate = SOCKET_OPERATION_OK;
1102 }
1103 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1104 PyErr_SetString(PySSLErrorObject,
1105 "The write operation timed out");
1106 goto error;
1107 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1108 PyErr_SetString(PySSLErrorObject,
1109 "Underlying socket has been closed.");
1110 goto error;
1111 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1112 break;
1113 }
1114 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001115
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001116 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001117 PyBuffer_Release(&buf);
1118 if (len > 0)
1119 return PyLong_FromLong(len);
1120 else
1121 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001122
1123error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001124 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001125 PyBuffer_Release(&buf);
1126 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001127}
1128
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001129PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001130"write(s) -> len\n\
1131\n\
1132Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001133of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001134
Antoine Pitrou152efa22010-05-16 18:19:27 +00001135static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001136{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001137 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001138
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001139 PySSL_BEGIN_ALLOW_THREADS
1140 count = SSL_pending(self->ssl);
1141 PySSL_END_ALLOW_THREADS
1142 if (count < 0)
1143 return PySSL_SetError(self, count, __FILE__, __LINE__);
1144 else
1145 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001146}
1147
1148PyDoc_STRVAR(PySSL_SSLpending_doc,
1149"pending() -> count\n\
1150\n\
1151Returns the number of already decrypted bytes available for read,\n\
1152pending on the connection.\n");
1153
Antoine Pitrou152efa22010-05-16 18:19:27 +00001154static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001155{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001156 PyObject *dest = NULL;
1157 Py_buffer buf;
1158 int buf_passed = 0;
1159 int count = -1;
1160 char *mem;
1161 /* XXX this should use Py_ssize_t */
1162 int len = 1024;
1163 int sockstate;
1164 int err;
1165 int nonblocking;
1166 PySocketSockObject *sock
1167 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001168
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001169 if (((PyObject*)sock) == Py_None) {
1170 _setSSLError("Underlying socket connection gone",
1171 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1172 return NULL;
1173 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001174 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001175
1176 if (!PyArg_ParseTuple(args, "|Oi:read", &dest, &count))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001177 goto error;
1178
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001179 if ((dest == NULL) || (dest == Py_None)) {
1180 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001181 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001182 mem = PyByteArray_AS_STRING(dest);
1183 } else if (PyLong_Check(dest)) {
1184 len = PyLong_AS_LONG(dest);
1185 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001186 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001187 mem = PyByteArray_AS_STRING(dest);
1188 } else {
1189 if (PyObject_GetBuffer(dest, &buf, PyBUF_CONTIG) < 0)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001190 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001191 mem = buf.buf;
1192 len = buf.len;
1193 if ((count > 0) && (count <= len))
1194 len = count;
1195 buf_passed = 1;
1196 }
1197
1198 /* just in case the blocking state of the socket has been changed */
1199 nonblocking = (sock->sock_timeout >= 0.0);
1200 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1201 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1202
1203 /* first check if there are bytes ready to be read */
1204 PySSL_BEGIN_ALLOW_THREADS
1205 count = SSL_pending(self->ssl);
1206 PySSL_END_ALLOW_THREADS
1207
1208 if (!count) {
1209 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1210 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1211 PyErr_SetString(PySSLErrorObject,
1212 "The read operation timed out");
1213 goto error;
1214 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1215 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001216 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001217 goto error;
1218 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1219 count = 0;
1220 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001221 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001222 }
1223 do {
1224 err = 0;
1225 PySSL_BEGIN_ALLOW_THREADS
1226 count = SSL_read(self->ssl, mem, len);
1227 err = SSL_get_error(self->ssl, count);
1228 PySSL_END_ALLOW_THREADS
1229 if (PyErr_CheckSignals())
1230 goto error;
1231 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001232 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001233 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001234 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001235 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1236 (SSL_get_shutdown(self->ssl) ==
1237 SSL_RECEIVED_SHUTDOWN))
1238 {
1239 count = 0;
1240 goto done;
1241 } else {
1242 sockstate = SOCKET_OPERATION_OK;
1243 }
1244 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1245 PyErr_SetString(PySSLErrorObject,
1246 "The read operation timed out");
1247 goto error;
1248 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1249 break;
1250 }
1251 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1252 if (count <= 0) {
1253 PySSL_SetError(self, count, __FILE__, __LINE__);
1254 goto error;
1255 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001256 done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001257 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001258 if (!buf_passed) {
1259 PyObject *res = PyBytes_FromStringAndSize(mem, count);
1260 Py_DECREF(dest);
1261 return res;
1262 } else {
1263 PyBuffer_Release(&buf);
1264 return PyLong_FromLong(count);
1265 }
Benjamin Peterson56420b42009-02-28 19:06:54 +00001266 error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001267 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001268 if (!buf_passed) {
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001269 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001270 } else {
1271 PyBuffer_Release(&buf);
1272 }
1273 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001274}
1275
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001276PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001277"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001278\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001279Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001280
Antoine Pitrou152efa22010-05-16 18:19:27 +00001281static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001282{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001283 int err, ssl_err, sockstate, nonblocking;
1284 int zeros = 0;
1285 PySocketSockObject *sock
1286 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001287
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001288 /* Guard against closed socket */
1289 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1290 _setSSLError("Underlying socket connection gone",
1291 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1292 return NULL;
1293 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001294 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001295
1296 /* Just in case the blocking state of the socket has been changed */
1297 nonblocking = (sock->sock_timeout >= 0.0);
1298 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1299 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1300
1301 while (1) {
1302 PySSL_BEGIN_ALLOW_THREADS
1303 /* Disable read-ahead so that unwrap can work correctly.
1304 * Otherwise OpenSSL might read in too much data,
1305 * eating clear text data that happens to be
1306 * transmitted after the SSL shutdown.
1307 * Should be safe to call repeatedly everytime this
1308 * function is used and the shutdown_seen_zero != 0
1309 * condition is met.
1310 */
1311 if (self->shutdown_seen_zero)
1312 SSL_set_read_ahead(self->ssl, 0);
1313 err = SSL_shutdown(self->ssl);
1314 PySSL_END_ALLOW_THREADS
1315 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1316 if (err > 0)
1317 break;
1318 if (err == 0) {
1319 /* Don't loop endlessly; instead preserve legacy
1320 behaviour of trying SSL_shutdown() only twice.
1321 This looks necessary for OpenSSL < 0.9.8m */
1322 if (++zeros > 1)
1323 break;
1324 /* Shutdown was sent, now try receiving */
1325 self->shutdown_seen_zero = 1;
1326 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001327 }
1328
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001329 /* Possibly retry shutdown until timeout or failure */
1330 ssl_err = SSL_get_error(self->ssl, err);
1331 if (ssl_err == SSL_ERROR_WANT_READ)
1332 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1333 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1334 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1335 else
1336 break;
1337 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1338 if (ssl_err == SSL_ERROR_WANT_READ)
1339 PyErr_SetString(PySSLErrorObject,
1340 "The read operation timed out");
1341 else
1342 PyErr_SetString(PySSLErrorObject,
1343 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001344 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001345 }
1346 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1347 PyErr_SetString(PySSLErrorObject,
1348 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001349 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001350 }
1351 else if (sockstate != SOCKET_OPERATION_OK)
1352 /* Retain the SSL error code */
1353 break;
1354 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001355
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001356 if (err < 0) {
1357 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001358 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001359 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001360 else
1361 /* It's already INCREF'ed */
1362 return (PyObject *) sock;
1363
1364error:
1365 Py_DECREF(sock);
1366 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001367}
1368
1369PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1370"shutdown(s) -> socket\n\
1371\n\
1372Does the SSL shutdown handshake with the remote end, and returns\n\
1373the underlying socket object.");
1374
1375
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001376static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001377 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1378 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1379 PySSL_SSLwrite_doc},
1380 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1381 PySSL_SSLread_doc},
1382 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1383 PySSL_SSLpending_doc},
1384 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1385 PySSL_peercert_doc},
1386 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1387 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1388 PySSL_SSLshutdown_doc},
1389 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001390};
1391
Antoine Pitrou152efa22010-05-16 18:19:27 +00001392static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001393 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001394 "_ssl._SSLSocket", /*tp_name*/
1395 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001396 0, /*tp_itemsize*/
1397 /* methods */
1398 (destructor)PySSL_dealloc, /*tp_dealloc*/
1399 0, /*tp_print*/
1400 0, /*tp_getattr*/
1401 0, /*tp_setattr*/
1402 0, /*tp_reserved*/
1403 0, /*tp_repr*/
1404 0, /*tp_as_number*/
1405 0, /*tp_as_sequence*/
1406 0, /*tp_as_mapping*/
1407 0, /*tp_hash*/
1408 0, /*tp_call*/
1409 0, /*tp_str*/
1410 0, /*tp_getattro*/
1411 0, /*tp_setattro*/
1412 0, /*tp_as_buffer*/
1413 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1414 0, /*tp_doc*/
1415 0, /*tp_traverse*/
1416 0, /*tp_clear*/
1417 0, /*tp_richcompare*/
1418 0, /*tp_weaklistoffset*/
1419 0, /*tp_iter*/
1420 0, /*tp_iternext*/
1421 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001422};
1423
Antoine Pitrou152efa22010-05-16 18:19:27 +00001424
1425/*
1426 * _SSLContext objects
1427 */
1428
1429static PyObject *
1430context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1431{
1432 char *kwlist[] = {"protocol", NULL};
1433 PySSLContext *self;
1434 int proto_version = PY_SSL_VERSION_SSL23;
1435 SSL_CTX *ctx = NULL;
1436
1437 if (!PyArg_ParseTupleAndKeywords(
1438 args, kwds, "i:_SSLContext", kwlist,
1439 &proto_version))
1440 return NULL;
1441
1442 PySSL_BEGIN_ALLOW_THREADS
1443 if (proto_version == PY_SSL_VERSION_TLS1)
1444 ctx = SSL_CTX_new(TLSv1_method());
1445 else if (proto_version == PY_SSL_VERSION_SSL3)
1446 ctx = SSL_CTX_new(SSLv3_method());
1447 else if (proto_version == PY_SSL_VERSION_SSL2)
1448 ctx = SSL_CTX_new(SSLv2_method());
1449 else if (proto_version == PY_SSL_VERSION_SSL23)
1450 ctx = SSL_CTX_new(SSLv23_method());
1451 else
1452 proto_version = -1;
1453 PySSL_END_ALLOW_THREADS
1454
1455 if (proto_version == -1) {
1456 PyErr_SetString(PyExc_ValueError,
1457 "invalid protocol version");
1458 return NULL;
1459 }
1460 if (ctx == NULL) {
1461 PyErr_SetString(PySSLErrorObject,
1462 "failed to allocate SSL context");
1463 return NULL;
1464 }
1465
1466 assert(type != NULL && type->tp_alloc != NULL);
1467 self = (PySSLContext *) type->tp_alloc(type, 0);
1468 if (self == NULL) {
1469 SSL_CTX_free(ctx);
1470 return NULL;
1471 }
1472 self->ctx = ctx;
1473 /* Defaults */
1474 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
1475 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
1476
1477 return (PyObject *)self;
1478}
1479
1480static void
1481context_dealloc(PySSLContext *self)
1482{
1483 SSL_CTX_free(self->ctx);
1484 Py_TYPE(self)->tp_free(self);
1485}
1486
1487static PyObject *
1488set_ciphers(PySSLContext *self, PyObject *args)
1489{
1490 int ret;
1491 const char *cipherlist;
1492
1493 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1494 return NULL;
1495 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1496 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001497 /* Clearing the error queue is necessary on some OpenSSL versions,
1498 otherwise the error will be reported again when another SSL call
1499 is done. */
1500 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001501 PyErr_SetString(PySSLErrorObject,
1502 "No cipher can be selected.");
1503 return NULL;
1504 }
1505 Py_RETURN_NONE;
1506}
1507
1508static PyObject *
1509get_verify_mode(PySSLContext *self, void *c)
1510{
1511 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1512 case SSL_VERIFY_NONE:
1513 return PyLong_FromLong(PY_SSL_CERT_NONE);
1514 case SSL_VERIFY_PEER:
1515 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1516 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1517 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1518 }
1519 PyErr_SetString(PySSLErrorObject,
1520 "invalid return value from SSL_CTX_get_verify_mode");
1521 return NULL;
1522}
1523
1524static int
1525set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1526{
1527 int n, mode;
1528 if (!PyArg_Parse(arg, "i", &n))
1529 return -1;
1530 if (n == PY_SSL_CERT_NONE)
1531 mode = SSL_VERIFY_NONE;
1532 else if (n == PY_SSL_CERT_OPTIONAL)
1533 mode = SSL_VERIFY_PEER;
1534 else if (n == PY_SSL_CERT_REQUIRED)
1535 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1536 else {
1537 PyErr_SetString(PyExc_ValueError,
1538 "invalid value for verify_mode");
1539 return -1;
1540 }
1541 SSL_CTX_set_verify(self->ctx, mode, NULL);
1542 return 0;
1543}
1544
1545static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001546get_options(PySSLContext *self, void *c)
1547{
1548 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1549}
1550
1551static int
1552set_options(PySSLContext *self, PyObject *arg, void *c)
1553{
1554 long new_opts, opts, set, clear;
1555 if (!PyArg_Parse(arg, "l", &new_opts))
1556 return -1;
1557 opts = SSL_CTX_get_options(self->ctx);
1558 clear = opts & ~new_opts;
1559 set = ~opts & new_opts;
1560 if (clear) {
1561#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1562 SSL_CTX_clear_options(self->ctx, clear);
1563#else
1564 PyErr_SetString(PyExc_ValueError,
1565 "can't clear options before OpenSSL 0.9.8m");
1566 return -1;
1567#endif
1568 }
1569 if (set)
1570 SSL_CTX_set_options(self->ctx, set);
1571 return 0;
1572}
1573
1574static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001575load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
1576{
1577 char *kwlist[] = {"certfile", "keyfile", NULL};
1578 PyObject *certfile, *keyfile = NULL;
1579 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
1580 int r;
1581
1582 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1583 "O|O:load_cert_chain", kwlist,
1584 &certfile, &keyfile))
1585 return NULL;
1586 if (keyfile == Py_None)
1587 keyfile = NULL;
1588 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
1589 PyErr_SetString(PyExc_TypeError,
1590 "certfile should be a valid filesystem path");
1591 return NULL;
1592 }
1593 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
1594 PyErr_SetString(PyExc_TypeError,
1595 "keyfile should be a valid filesystem path");
1596 goto error;
1597 }
1598 PySSL_BEGIN_ALLOW_THREADS
1599 r = SSL_CTX_use_certificate_chain_file(self->ctx,
1600 PyBytes_AS_STRING(certfile_bytes));
1601 PySSL_END_ALLOW_THREADS
1602 if (r != 1) {
1603 _setSSLError(NULL, 0, __FILE__, __LINE__);
1604 goto error;
1605 }
1606 PySSL_BEGIN_ALLOW_THREADS
1607 r = SSL_CTX_use_RSAPrivateKey_file(self->ctx,
1608 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
1609 SSL_FILETYPE_PEM);
1610 PySSL_END_ALLOW_THREADS
1611 Py_XDECREF(keyfile_bytes);
1612 Py_XDECREF(certfile_bytes);
1613 if (r != 1) {
1614 _setSSLError(NULL, 0, __FILE__, __LINE__);
1615 return NULL;
1616 }
1617 PySSL_BEGIN_ALLOW_THREADS
1618 r = SSL_CTX_check_private_key(self->ctx);
1619 PySSL_END_ALLOW_THREADS
1620 if (r != 1) {
1621 _setSSLError(NULL, 0, __FILE__, __LINE__);
1622 return NULL;
1623 }
1624 Py_RETURN_NONE;
1625
1626error:
1627 Py_XDECREF(keyfile_bytes);
1628 Py_XDECREF(certfile_bytes);
1629 return NULL;
1630}
1631
1632static PyObject *
1633load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
1634{
1635 char *kwlist[] = {"cafile", "capath", NULL};
1636 PyObject *cafile = NULL, *capath = NULL;
1637 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
1638 const char *cafile_buf = NULL, *capath_buf = NULL;
1639 int r;
1640
1641 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1642 "|OO:load_verify_locations", kwlist,
1643 &cafile, &capath))
1644 return NULL;
1645 if (cafile == Py_None)
1646 cafile = NULL;
1647 if (capath == Py_None)
1648 capath = NULL;
1649 if (cafile == NULL && capath == NULL) {
1650 PyErr_SetString(PyExc_TypeError,
1651 "cafile and capath cannot be both omitted");
1652 return NULL;
1653 }
1654 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
1655 PyErr_SetString(PyExc_TypeError,
1656 "cafile should be a valid filesystem path");
1657 return NULL;
1658 }
1659 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
1660 Py_DECREF(cafile_bytes);
1661 PyErr_SetString(PyExc_TypeError,
1662 "capath should be a valid filesystem path");
1663 return NULL;
1664 }
1665 if (cafile)
1666 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
1667 if (capath)
1668 capath_buf = PyBytes_AS_STRING(capath_bytes);
1669 PySSL_BEGIN_ALLOW_THREADS
1670 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
1671 PySSL_END_ALLOW_THREADS
1672 Py_XDECREF(cafile_bytes);
1673 Py_XDECREF(capath_bytes);
1674 if (r != 1) {
1675 _setSSLError(NULL, 0, __FILE__, __LINE__);
1676 return NULL;
1677 }
1678 Py_RETURN_NONE;
1679}
1680
1681static PyObject *
1682context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
1683{
1684 char *kwlist[] = {"sock", "server_side", NULL};
1685 PySocketSockObject *sock;
1686 int server_side = 0;
1687
1688 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i:_wrap_socket", kwlist,
1689 PySocketModule.Sock_Type,
1690 &sock, &server_side))
1691 return NULL;
1692
1693 return (PyObject *) newPySSLSocket(self->ctx, sock, server_side);
1694}
1695
1696static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00001697 {"options", (getter) get_options,
1698 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00001699 {"verify_mode", (getter) get_verify_mode,
1700 (setter) set_verify_mode, NULL},
1701 {NULL}, /* sentinel */
1702};
1703
1704static struct PyMethodDef context_methods[] = {
1705 {"_wrap_socket", (PyCFunction) context_wrap_socket,
1706 METH_VARARGS | METH_KEYWORDS, NULL},
1707 {"set_ciphers", (PyCFunction) set_ciphers,
1708 METH_VARARGS, NULL},
1709 {"load_cert_chain", (PyCFunction) load_cert_chain,
1710 METH_VARARGS | METH_KEYWORDS, NULL},
1711 {"load_verify_locations", (PyCFunction) load_verify_locations,
1712 METH_VARARGS | METH_KEYWORDS, NULL},
1713 {NULL, NULL} /* sentinel */
1714};
1715
1716static PyTypeObject PySSLContext_Type = {
1717 PyVarObject_HEAD_INIT(NULL, 0)
1718 "_ssl._SSLContext", /*tp_name*/
1719 sizeof(PySSLContext), /*tp_basicsize*/
1720 0, /*tp_itemsize*/
1721 (destructor)context_dealloc, /*tp_dealloc*/
1722 0, /*tp_print*/
1723 0, /*tp_getattr*/
1724 0, /*tp_setattr*/
1725 0, /*tp_reserved*/
1726 0, /*tp_repr*/
1727 0, /*tp_as_number*/
1728 0, /*tp_as_sequence*/
1729 0, /*tp_as_mapping*/
1730 0, /*tp_hash*/
1731 0, /*tp_call*/
1732 0, /*tp_str*/
1733 0, /*tp_getattro*/
1734 0, /*tp_setattro*/
1735 0, /*tp_as_buffer*/
1736 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
1737 0, /*tp_doc*/
1738 0, /*tp_traverse*/
1739 0, /*tp_clear*/
1740 0, /*tp_richcompare*/
1741 0, /*tp_weaklistoffset*/
1742 0, /*tp_iter*/
1743 0, /*tp_iternext*/
1744 context_methods, /*tp_methods*/
1745 0, /*tp_members*/
1746 context_getsetlist, /*tp_getset*/
1747 0, /*tp_base*/
1748 0, /*tp_dict*/
1749 0, /*tp_descr_get*/
1750 0, /*tp_descr_set*/
1751 0, /*tp_dictoffset*/
1752 0, /*tp_init*/
1753 0, /*tp_alloc*/
1754 context_new, /*tp_new*/
1755};
1756
1757
1758
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001759#ifdef HAVE_OPENSSL_RAND
1760
1761/* helper routines for seeding the SSL PRNG */
1762static PyObject *
1763PySSL_RAND_add(PyObject *self, PyObject *args)
1764{
1765 char *buf;
1766 int len;
1767 double entropy;
1768
1769 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00001770 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001771 RAND_add(buf, len, entropy);
1772 Py_INCREF(Py_None);
1773 return Py_None;
1774}
1775
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001776PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001777"RAND_add(string, entropy)\n\
1778\n\
1779Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001780bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001781
1782static PyObject *
1783PySSL_RAND_status(PyObject *self)
1784{
Christian Heimes217cfd12007-12-02 14:31:20 +00001785 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001786}
1787
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001788PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001789"RAND_status() -> 0 or 1\n\
1790\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001791Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1792It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1793using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001794
1795static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001796PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001797{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001798 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001799 int bytes;
1800
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001801 if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
1802 PyUnicode_FSConverter, &path))
1803 return NULL;
1804
1805 bytes = RAND_egd(PyBytes_AsString(path));
1806 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001807 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001808 PyErr_SetString(PySSLErrorObject,
1809 "EGD connection failed or EGD did not return "
1810 "enough data to seed the PRNG");
1811 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001812 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001813 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001814}
1815
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001816PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001817"RAND_egd(path) -> bytes\n\
1818\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001819Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1820Returns number of bytes read. Raises SSLError if connection to EGD\n\
1821fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001822
1823#endif
1824
Bill Janssen40a0f662008-08-12 16:56:25 +00001825
1826
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001827/* List of functions exported by this module. */
1828
1829static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001830 {"_test_decode_cert", PySSL_test_decode_certificate,
1831 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001832#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001833 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1834 PySSL_RAND_add_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001835 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001836 PySSL_RAND_egd_doc},
1837 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1838 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001839#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001840 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001841};
1842
1843
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001844#ifdef WITH_THREAD
1845
1846/* an implementation of OpenSSL threading operations in terms
1847 of the Python C thread library */
1848
1849static PyThread_type_lock *_ssl_locks = NULL;
1850
1851static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001852 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001853}
1854
Bill Janssen6e027db2007-11-15 22:23:56 +00001855static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001856 (int mode, int n, const char *file, int line) {
1857 /* this function is needed to perform locking on shared data
1858 structures. (Note that OpenSSL uses a number of global data
1859 structures that will be implicitly shared whenever multiple
1860 threads use OpenSSL.) Multi-threaded applications will
1861 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001862
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001863 locking_function() must be able to handle up to
1864 CRYPTO_num_locks() different mutex locks. It sets the n-th
1865 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001866
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001867 file and line are the file number of the function setting the
1868 lock. They can be useful for debugging.
1869 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001870
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001871 if ((_ssl_locks == NULL) ||
1872 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1873 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001874
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001875 if (mode & CRYPTO_LOCK) {
1876 PyThread_acquire_lock(_ssl_locks[n], 1);
1877 } else {
1878 PyThread_release_lock(_ssl_locks[n]);
1879 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001880}
1881
1882static int _setup_ssl_threads(void) {
1883
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001884 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001885
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001886 if (_ssl_locks == NULL) {
1887 _ssl_locks_count = CRYPTO_num_locks();
1888 _ssl_locks = (PyThread_type_lock *)
1889 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1890 if (_ssl_locks == NULL)
1891 return 0;
1892 memset(_ssl_locks, 0,
1893 sizeof(PyThread_type_lock) * _ssl_locks_count);
1894 for (i = 0; i < _ssl_locks_count; i++) {
1895 _ssl_locks[i] = PyThread_allocate_lock();
1896 if (_ssl_locks[i] == NULL) {
1897 unsigned int j;
1898 for (j = 0; j < i; j++) {
1899 PyThread_free_lock(_ssl_locks[j]);
1900 }
1901 free(_ssl_locks);
1902 return 0;
1903 }
1904 }
1905 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1906 CRYPTO_set_id_callback(_ssl_thread_id_function);
1907 }
1908 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001909}
1910
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001911#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001912
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001913PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001914"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001915for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001916
Martin v. Löwis1a214512008-06-11 05:26:20 +00001917
1918static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001919 PyModuleDef_HEAD_INIT,
1920 "_ssl",
1921 module_doc,
1922 -1,
1923 PySSL_methods,
1924 NULL,
1925 NULL,
1926 NULL,
1927 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001928};
1929
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001930PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001931PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001932{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001933 PyObject *m, *d, *r;
1934 unsigned long libver;
1935 unsigned int major, minor, fix, patch, status;
1936 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001937
Antoine Pitrou152efa22010-05-16 18:19:27 +00001938 if (PyType_Ready(&PySSLContext_Type) < 0)
1939 return NULL;
1940 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001941 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001942
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001943 m = PyModule_Create(&_sslmodule);
1944 if (m == NULL)
1945 return NULL;
1946 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001947
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001948 /* Load _socket module and its C API */
1949 socket_api = PySocketModule_ImportModuleAndAPI();
1950 if (!socket_api)
1951 return NULL;
1952 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001953
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001954 /* Init OpenSSL */
1955 SSL_load_error_strings();
1956 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001957#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001958 /* note that this will start threading if not already started */
1959 if (!_setup_ssl_threads()) {
1960 return NULL;
1961 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001962#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001963 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001964
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001965 /* Add symbols to module dict */
1966 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
1967 PySocketModule.error,
1968 NULL);
1969 if (PySSLErrorObject == NULL)
1970 return NULL;
1971 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
1972 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001973 if (PyDict_SetItemString(d, "_SSLContext",
1974 (PyObject *)&PySSLContext_Type) != 0)
1975 return NULL;
1976 if (PyDict_SetItemString(d, "_SSLSocket",
1977 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001978 return NULL;
1979 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
1980 PY_SSL_ERROR_ZERO_RETURN);
1981 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
1982 PY_SSL_ERROR_WANT_READ);
1983 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
1984 PY_SSL_ERROR_WANT_WRITE);
1985 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
1986 PY_SSL_ERROR_WANT_X509_LOOKUP);
1987 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
1988 PY_SSL_ERROR_SYSCALL);
1989 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
1990 PY_SSL_ERROR_SSL);
1991 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1992 PY_SSL_ERROR_WANT_CONNECT);
1993 /* non ssl.h errorcodes */
1994 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1995 PY_SSL_ERROR_EOF);
1996 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1997 PY_SSL_ERROR_INVALID_ERROR_CODE);
1998 /* cert requirements */
1999 PyModule_AddIntConstant(m, "CERT_NONE",
2000 PY_SSL_CERT_NONE);
2001 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2002 PY_SSL_CERT_OPTIONAL);
2003 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2004 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002005
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002006 /* protocol versions */
2007 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2008 PY_SSL_VERSION_SSL2);
2009 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2010 PY_SSL_VERSION_SSL3);
2011 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2012 PY_SSL_VERSION_SSL23);
2013 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2014 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002015
Antoine Pitroub5218772010-05-21 09:56:06 +00002016 /* protocol options */
2017 PyModule_AddIntConstant(m, "OP_ALL", SSL_OP_ALL);
2018 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2019 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2020 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
2021
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002022 /* OpenSSL version */
2023 /* SSLeay() gives us the version of the library linked against,
2024 which could be different from the headers version.
2025 */
2026 libver = SSLeay();
2027 r = PyLong_FromUnsignedLong(libver);
2028 if (r == NULL)
2029 return NULL;
2030 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2031 return NULL;
2032 status = libver & 0xF;
2033 libver >>= 4;
2034 patch = libver & 0xFF;
2035 libver >>= 8;
2036 fix = libver & 0xFF;
2037 libver >>= 8;
2038 minor = libver & 0xFF;
2039 libver >>= 8;
2040 major = libver & 0xFF;
2041 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2042 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2043 return NULL;
2044 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2045 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2046 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002047
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002048 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002049}