blob: 6ed1a9fd47fbac65c2f996de77e2ccb75cd5d0fc [file] [log] [blame]
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +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.
Bill Janssen98d19da2007-09-10 21:51:02 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen934b16d2008-06-28 22:19:33 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Bill Janssen98d19da2007-09-10 21:51:02 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Bill Janssen98d19da2007-09-10 21:51:02 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou07072162010-04-23 21:07:58 +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"
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000018
Bill Janssen98d19da2007-09-10 21:51:02 +000019#ifdef WITH_THREAD
20#include "pythread.h"
21#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitrou7fd622a2010-05-05 15:59:19 +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 }
Bill Janssen98d19da2007-09-10 21:51:02 +000028
Antoine Pitrou7fd622a2010-05-05 15:59:19 +000029#else /* no WITH_THREAD */
Bill Janssen98d19da2007-09-10 21:51:02 +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 Pitrou7fd622a2010-05-05 15:59:19 +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_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000051};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000052
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000053enum py_ssl_server_or_client {
Antoine Pitrou7fd622a2010-05-05 15:59:19 +000054 PY_SSL_CLIENT,
55 PY_SSL_SERVER
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000056};
57
58enum py_ssl_cert_requirements {
Antoine Pitrou7fd622a2010-05-05 15:59:19 +000059 PY_SSL_CERT_NONE,
60 PY_SSL_CERT_OPTIONAL,
61 PY_SSL_CERT_REQUIRED
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000062};
63
64enum py_ssl_version {
Antoine Pitrou7fd622a2010-05-05 15:59:19 +000065 PY_SSL_VERSION_SSL2,
66 PY_SSL_VERSION_SSL3,
67 PY_SSL_VERSION_SSL23,
68 PY_SSL_VERSION_TLS1
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000069};
70
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000071/* Include symbols from _socket module */
72#include "socketmodule.h"
73
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000074#if defined(HAVE_POLL_H)
Anthony Baxter93ab5fa2006-07-11 02:04:09 +000075#include <poll.h>
76#elif defined(HAVE_SYS_POLL_H)
77#include <sys/poll.h>
78#endif
79
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000080/* Include OpenSSL header files */
81#include "openssl/rsa.h"
82#include "openssl/crypto.h"
83#include "openssl/x509.h"
Bill Janssen98d19da2007-09-10 21:51:02 +000084#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000085#include "openssl/pem.h"
86#include "openssl/ssl.h"
87#include "openssl/err.h"
88#include "openssl/rand.h"
89
90/* SSL error object */
91static PyObject *PySSLErrorObject;
92
Bill Janssen98d19da2007-09-10 21:51:02 +000093#ifdef WITH_THREAD
94
95/* serves as a flag to see whether we've initialized the SSL thread support. */
96/* 0 means no, greater than 0 means yes */
97
98static unsigned int _ssl_locks_count = 0;
99
100#endif /* def WITH_THREAD */
101
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000102/* SSL socket object */
103
104#define X509_NAME_MAXLEN 256
105
106/* RAND_* APIs got added to OpenSSL in 0.9.5 */
107#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
108# define HAVE_OPENSSL_RAND 1
109#else
110# undef HAVE_OPENSSL_RAND
111#endif
112
113typedef struct {
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000114 PyObject_HEAD
115 PySocketSockObject *Socket; /* Socket on which we're layered */
116 SSL_CTX* ctx;
117 SSL* ssl;
118 X509* peer_cert;
119 char server[X509_NAME_MAXLEN];
120 char issuer[X509_NAME_MAXLEN];
121 int shutdown_seen_zero;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000122
123} PySSLObject;
124
Jeremy Hylton938ace62002-07-17 16:30:39 +0000125static PyTypeObject PySSL_Type;
126static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args);
127static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000128static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000129 int writing);
Bill Janssen98d19da2007-09-10 21:51:02 +0000130static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args);
131static PyObject *PySSL_cipher(PySSLObject *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000132
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000133#define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000134
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000135typedef enum {
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000136 SOCKET_IS_NONBLOCKING,
137 SOCKET_IS_BLOCKING,
138 SOCKET_HAS_TIMED_OUT,
139 SOCKET_HAS_BEEN_CLOSED,
140 SOCKET_TOO_LARGE_FOR_SELECT,
141 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000142} timeout_state;
143
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000144/* Wrap error strings with filename and line # */
145#define STRINGIFY1(x) #x
146#define STRINGIFY2(x) STRINGIFY1(x)
147#define ERRSTR1(x,y,z) (x ":" y ": " z)
148#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
149
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000150/* XXX It might be helpful to augment the error message generated
151 below with the name of the SSL function that generated the error.
152 I expect it's obvious most of the time.
153*/
154
155static PyObject *
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000156PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000157{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000158 PyObject *v;
159 char buf[2048];
160 char *errstr;
161 int err;
162 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000163
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000164 assert(ret <= 0);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000165
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000166 if (obj->ssl != NULL) {
167 err = SSL_get_error(obj->ssl, ret);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000168
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000169 switch (err) {
170 case SSL_ERROR_ZERO_RETURN:
171 errstr = "TLS/SSL connection has been closed";
172 p = PY_SSL_ERROR_ZERO_RETURN;
173 break;
174 case SSL_ERROR_WANT_READ:
175 errstr = "The operation did not complete (read)";
176 p = PY_SSL_ERROR_WANT_READ;
177 break;
178 case SSL_ERROR_WANT_WRITE:
179 p = PY_SSL_ERROR_WANT_WRITE;
180 errstr = "The operation did not complete (write)";
181 break;
182 case SSL_ERROR_WANT_X509_LOOKUP:
183 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou96125cf2010-05-12 14:05:34 +0000184 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000185 break;
186 case SSL_ERROR_WANT_CONNECT:
187 p = PY_SSL_ERROR_WANT_CONNECT;
188 errstr = "The operation did not complete (connect)";
189 break;
190 case SSL_ERROR_SYSCALL:
191 {
192 unsigned long e = ERR_get_error();
193 if (e == 0) {
194 if (ret == 0 || !obj->Socket) {
Antoine Pitrou96125cf2010-05-12 14:05:34 +0000195 p = PY_SSL_ERROR_EOF;
196 errstr = "EOF occurred in violation of protocol";
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000197 } else if (ret == -1) {
Antoine Pitrou96125cf2010-05-12 14:05:34 +0000198 /* underlying BIO reported an I/O error */
Antoine Pitroub6e3e3a2010-05-16 23:14:34 +0000199 ERR_clear_error();
Antoine Pitrou96125cf2010-05-12 14:05:34 +0000200 return obj->Socket->errorhandler();
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000201 } else { /* possible? */
Antoine Pitrou96125cf2010-05-12 14:05:34 +0000202 p = PY_SSL_ERROR_SYSCALL;
203 errstr = "Some I/O error occurred";
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000204 }
205 } else {
206 p = PY_SSL_ERROR_SYSCALL;
207 /* XXX Protected by global interpreter lock */
208 errstr = ERR_error_string(e, NULL);
209 }
210 break;
211 }
212 case SSL_ERROR_SSL:
213 {
214 unsigned long e = ERR_get_error();
215 p = PY_SSL_ERROR_SSL;
216 if (e != 0)
217 /* XXX Protected by global interpreter lock */
218 errstr = ERR_error_string(e, NULL);
219 else { /* possible? */
Antoine Pitrou96125cf2010-05-12 14:05:34 +0000220 errstr = "A failure in the SSL library occurred";
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000221 }
222 break;
223 }
224 default:
225 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
226 errstr = "Invalid error code";
227 }
228 } else {
229 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
230 }
231 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitroub6e3e3a2010-05-16 23:14:34 +0000232 ERR_clear_error();
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000233 v = Py_BuildValue("(is)", p, buf);
234 if (v != NULL) {
235 PyErr_SetObject(PySSLErrorObject, v);
236 Py_DECREF(v);
237 }
238 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000239}
240
Bill Janssen98d19da2007-09-10 21:51:02 +0000241static PyObject *
242_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
243
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000244 char buf[2048];
245 PyObject *v;
Bill Janssen98d19da2007-09-10 21:51:02 +0000246
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000247 if (errstr == NULL) {
248 errcode = ERR_peek_last_error();
249 errstr = ERR_error_string(errcode, NULL);
250 }
251 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitroub6e3e3a2010-05-16 23:14:34 +0000252 ERR_clear_error();
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000253 v = Py_BuildValue("(is)", errcode, buf);
254 if (v != NULL) {
255 PyErr_SetObject(PySSLErrorObject, v);
256 Py_DECREF(v);
257 }
258 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000259}
260
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000261static PySSLObject *
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000262newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file,
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000263 enum py_ssl_server_or_client socket_type,
264 enum py_ssl_cert_requirements certreq,
265 enum py_ssl_version proto_version,
266 char *cacerts_file)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000267{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000268 PySSLObject *self;
269 char *errstr = NULL;
270 int ret;
271 int verification_mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000272
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000273 self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */
274 if (self == NULL)
275 return NULL;
276 memset(self->server, '\0', sizeof(char) * X509_NAME_MAXLEN);
277 memset(self->issuer, '\0', sizeof(char) * X509_NAME_MAXLEN);
278 self->peer_cert = NULL;
279 self->ssl = NULL;
280 self->ctx = NULL;
281 self->Socket = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000282
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000283 /* Make sure the SSL error state is initialized */
284 (void) ERR_get_state();
285 ERR_clear_error();
Bill Janssen98d19da2007-09-10 21:51:02 +0000286
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000287 if ((key_file && !cert_file) || (!key_file && cert_file)) {
288 errstr = ERRSTR("Both the key & certificate files "
289 "must be specified");
290 goto fail;
291 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000292
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000293 if ((socket_type == PY_SSL_SERVER) &&
294 ((key_file == NULL) || (cert_file == NULL))) {
295 errstr = ERRSTR("Both the key & certificate files "
296 "must be specified for server-side operation");
297 goto fail;
298 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000299
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000300 PySSL_BEGIN_ALLOW_THREADS
301 if (proto_version == PY_SSL_VERSION_TLS1)
302 self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */
303 else if (proto_version == PY_SSL_VERSION_SSL3)
304 self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */
305 else if (proto_version == PY_SSL_VERSION_SSL2)
306 self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */
307 else if (proto_version == PY_SSL_VERSION_SSL23)
308 self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
309 PySSL_END_ALLOW_THREADS
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000310
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000311 if (self->ctx == NULL) {
312 errstr = ERRSTR("Invalid SSL protocol variant specified.");
313 goto fail;
314 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000315
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000316 if (certreq != PY_SSL_CERT_NONE) {
317 if (cacerts_file == NULL) {
318 errstr = ERRSTR("No root certificates specified for "
Antoine Pitrou96125cf2010-05-12 14:05:34 +0000319 "verification of other-side certificates.");
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000320 goto fail;
321 } else {
322 PySSL_BEGIN_ALLOW_THREADS
323 ret = SSL_CTX_load_verify_locations(self->ctx,
324 cacerts_file,
325 NULL);
326 PySSL_END_ALLOW_THREADS
327 if (ret != 1) {
328 _setSSLError(NULL, 0, __FILE__, __LINE__);
329 goto fail;
330 }
331 }
332 }
333 if (key_file) {
334 PySSL_BEGIN_ALLOW_THREADS
335 ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
336 SSL_FILETYPE_PEM);
337 PySSL_END_ALLOW_THREADS
338 if (ret != 1) {
339 _setSSLError(NULL, ret, __FILE__, __LINE__);
340 goto fail;
341 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000342
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000343 PySSL_BEGIN_ALLOW_THREADS
344 ret = SSL_CTX_use_certificate_chain_file(self->ctx,
345 cert_file);
346 PySSL_END_ALLOW_THREADS
347 if (ret != 1) {
348 /*
349 fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
350 ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
351 */
352 if (ERR_peek_last_error() != 0) {
353 _setSSLError(NULL, ret, __FILE__, __LINE__);
354 goto fail;
355 }
356 }
357 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000358
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000359 /* ssl compatibility */
360 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
Bill Janssen98d19da2007-09-10 21:51:02 +0000361
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000362 verification_mode = SSL_VERIFY_NONE;
363 if (certreq == PY_SSL_CERT_OPTIONAL)
364 verification_mode = SSL_VERIFY_PEER;
365 else if (certreq == PY_SSL_CERT_REQUIRED)
366 verification_mode = (SSL_VERIFY_PEER |
367 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
368 SSL_CTX_set_verify(self->ctx, verification_mode,
369 NULL); /* set verify lvl */
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000370
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000371 PySSL_BEGIN_ALLOW_THREADS
372 self->ssl = SSL_new(self->ctx); /* New ssl struct */
373 PySSL_END_ALLOW_THREADS
374 SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */
Antoine Pitrou206685b2010-04-09 20:44:09 +0000375#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000376 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou206685b2010-04-09 20:44:09 +0000377#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000378
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000379 /* If the socket is in non-blocking mode or timeout mode, set the BIO
380 * to non-blocking mode (blocking is the default)
381 */
382 if (Sock->sock_timeout >= 0.0) {
383 /* Set both the read and write BIO's to non-blocking mode */
384 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
385 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
386 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000387
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000388 PySSL_BEGIN_ALLOW_THREADS
389 if (socket_type == PY_SSL_CLIENT)
390 SSL_set_connect_state(self->ssl);
391 else
392 SSL_set_accept_state(self->ssl);
393 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000394
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000395 self->Socket = Sock;
396 Py_INCREF(self->Socket);
397 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000398 fail:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000399 if (errstr)
400 PyErr_SetString(PySSLErrorObject, errstr);
401 Py_DECREF(self);
402 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000403}
404
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000405static PyObject *
Guido van Rossum780b80d2007-08-27 18:42:23 +0000406PySSL_sslwrap(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000407{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000408 PySocketSockObject *Sock;
409 int server_side = 0;
410 int verification_mode = PY_SSL_CERT_NONE;
411 int protocol = PY_SSL_VERSION_SSL23;
412 char *key_file = NULL;
413 char *cert_file = NULL;
414 char *cacerts_file = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000415
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000416 if (!PyArg_ParseTuple(args, "O!i|zziiz:sslwrap",
417 PySocketModule.Sock_Type,
418 &Sock,
419 &server_side,
420 &key_file, &cert_file,
421 &verification_mode, &protocol,
422 &cacerts_file))
423 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000424
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000425 /*
426 fprintf(stderr,
427 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
428 "protocol %d, certs %p\n",
429 server_side, key_file, cert_file, verification_mode,
430 protocol, cacerts_file);
431 */
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000432
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000433 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
434 server_side, verification_mode,
435 protocol, cacerts_file);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000436}
437
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000438PyDoc_STRVAR(ssl_doc,
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000439"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
440" cacertsfile]) -> sslobject");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000441
442/* SSL object methods */
443
Bill Janssen934b16d2008-06-28 22:19:33 +0000444static PyObject *PySSL_SSLdo_handshake(PySSLObject *self)
445{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000446 int ret;
447 int err;
448 int sockstate, nonblocking;
Antoine Pitrouc689d962010-04-24 20:13:37 +0000449
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000450 /* just in case the blocking state of the socket has been changed */
451 nonblocking = (self->Socket->sock_timeout >= 0.0);
452 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
453 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +0000454
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000455 /* Actually negotiate SSL connection */
456 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
457 sockstate = 0;
458 do {
459 PySSL_BEGIN_ALLOW_THREADS
460 ret = SSL_do_handshake(self->ssl);
461 err = SSL_get_error(self->ssl, ret);
462 PySSL_END_ALLOW_THREADS
463 if(PyErr_CheckSignals()) {
464 return NULL;
465 }
466 if (err == SSL_ERROR_WANT_READ) {
467 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
468 } else if (err == SSL_ERROR_WANT_WRITE) {
469 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
470 } else {
471 sockstate = SOCKET_OPERATION_OK;
472 }
473 if (sockstate == SOCKET_HAS_TIMED_OUT) {
474 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou96125cf2010-05-12 14:05:34 +0000475 ERRSTR("The handshake operation timed out"));
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000476 return NULL;
477 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
478 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou96125cf2010-05-12 14:05:34 +0000479 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000480 return NULL;
481 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
482 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou96125cf2010-05-12 14:05:34 +0000483 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000484 return NULL;
485 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
486 break;
487 }
488 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
489 if (ret < 1)
490 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen934b16d2008-06-28 22:19:33 +0000491
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000492 if (self->peer_cert)
493 X509_free (self->peer_cert);
494 PySSL_BEGIN_ALLOW_THREADS
495 if ((self->peer_cert = SSL_get_peer_certificate(self->ssl))) {
496 X509_NAME_oneline(X509_get_subject_name(self->peer_cert),
497 self->server, X509_NAME_MAXLEN);
498 X509_NAME_oneline(X509_get_issuer_name(self->peer_cert),
499 self->issuer, X509_NAME_MAXLEN);
500 }
501 PySSL_END_ALLOW_THREADS
Bill Janssen934b16d2008-06-28 22:19:33 +0000502
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000503 Py_INCREF(Py_None);
504 return Py_None;
Bill Janssen934b16d2008-06-28 22:19:33 +0000505}
506
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000507static PyObject *
508PySSL_server(PySSLObject *self)
509{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000510 return PyString_FromString(self->server);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000511}
512
513static PyObject *
514PySSL_issuer(PySSLObject *self)
515{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000516 return PyString_FromString(self->issuer);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000517}
518
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000519static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000520_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000521
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000522 char namebuf[X509_NAME_MAXLEN];
523 int buflen;
524 PyObject *name_obj;
525 PyObject *value_obj;
526 PyObject *attr;
527 unsigned char *valuebuf = NULL;
Guido van Rossum780b80d2007-08-27 18:42:23 +0000528
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000529 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
530 if (buflen < 0) {
531 _setSSLError(NULL, 0, __FILE__, __LINE__);
532 goto fail;
533 }
534 name_obj = PyString_FromStringAndSize(namebuf, buflen);
535 if (name_obj == NULL)
536 goto fail;
537
538 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
539 if (buflen < 0) {
540 _setSSLError(NULL, 0, __FILE__, __LINE__);
541 Py_DECREF(name_obj);
542 goto fail;
543 }
544 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou96125cf2010-05-12 14:05:34 +0000545 buflen, "strict");
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000546 OPENSSL_free(valuebuf);
547 if (value_obj == NULL) {
548 Py_DECREF(name_obj);
549 goto fail;
550 }
551 attr = PyTuple_New(2);
552 if (attr == NULL) {
553 Py_DECREF(name_obj);
554 Py_DECREF(value_obj);
555 goto fail;
556 }
557 PyTuple_SET_ITEM(attr, 0, name_obj);
558 PyTuple_SET_ITEM(attr, 1, value_obj);
559 return attr;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000560
Bill Janssen98d19da2007-09-10 21:51:02 +0000561 fail:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000562 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000563}
564
565static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000566_create_tuple_for_X509_NAME (X509_NAME *xname)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000567{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000568 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
569 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
570 PyObject *rdnt;
571 PyObject *attr = NULL; /* tuple to hold an attribute */
572 int entry_count = X509_NAME_entry_count(xname);
573 X509_NAME_ENTRY *entry;
574 ASN1_OBJECT *name;
575 ASN1_STRING *value;
576 int index_counter;
577 int rdn_level = -1;
578 int retcode;
Bill Janssen98d19da2007-09-10 21:51:02 +0000579
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000580 dn = PyList_New(0);
581 if (dn == NULL)
582 return NULL;
583 /* now create another tuple to hold the top-level RDN */
584 rdn = PyList_New(0);
585 if (rdn == NULL)
586 goto fail0;
Bill Janssen98d19da2007-09-10 21:51:02 +0000587
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000588 for (index_counter = 0;
589 index_counter < entry_count;
590 index_counter++)
591 {
592 entry = X509_NAME_get_entry(xname, index_counter);
Bill Janssen98d19da2007-09-10 21:51:02 +0000593
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000594 /* check to see if we've gotten to a new RDN */
595 if (rdn_level >= 0) {
596 if (rdn_level != entry->set) {
597 /* yes, new RDN */
598 /* add old RDN to DN */
599 rdnt = PyList_AsTuple(rdn);
600 Py_DECREF(rdn);
601 if (rdnt == NULL)
602 goto fail0;
603 retcode = PyList_Append(dn, rdnt);
604 Py_DECREF(rdnt);
605 if (retcode < 0)
606 goto fail0;
607 /* create new RDN */
608 rdn = PyList_New(0);
609 if (rdn == NULL)
610 goto fail0;
611 }
612 }
613 rdn_level = entry->set;
Bill Janssen98d19da2007-09-10 21:51:02 +0000614
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000615 /* now add this attribute to the current RDN */
616 name = X509_NAME_ENTRY_get_object(entry);
617 value = X509_NAME_ENTRY_get_data(entry);
618 attr = _create_tuple_for_attribute(name, value);
619 /*
620 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
621 entry->set,
622 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
623 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
624 */
625 if (attr == NULL)
626 goto fail1;
627 retcode = PyList_Append(rdn, attr);
628 Py_DECREF(attr);
629 if (retcode < 0)
630 goto fail1;
631 }
632 /* now, there's typically a dangling RDN */
633 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
634 rdnt = PyList_AsTuple(rdn);
635 Py_DECREF(rdn);
636 if (rdnt == NULL)
637 goto fail0;
638 retcode = PyList_Append(dn, rdnt);
639 Py_DECREF(rdnt);
640 if (retcode < 0)
641 goto fail0;
642 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000643
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000644 /* convert list to tuple */
645 rdnt = PyList_AsTuple(dn);
646 Py_DECREF(dn);
647 if (rdnt == NULL)
648 return NULL;
649 return rdnt;
Bill Janssen98d19da2007-09-10 21:51:02 +0000650
651 fail1:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000652 Py_XDECREF(rdn);
Bill Janssen98d19da2007-09-10 21:51:02 +0000653
654 fail0:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000655 Py_XDECREF(dn);
656 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000657}
658
659static PyObject *
660_get_peer_alt_names (X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000661
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000662 /* this code follows the procedure outlined in
663 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
664 function to extract the STACK_OF(GENERAL_NAME),
665 then iterates through the stack to add the
666 names. */
Bill Janssen98d19da2007-09-10 21:51:02 +0000667
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000668 int i, j;
669 PyObject *peer_alt_names = Py_None;
670 PyObject *v, *t;
671 X509_EXTENSION *ext = NULL;
672 GENERAL_NAMES *names = NULL;
673 GENERAL_NAME *name;
674 X509V3_EXT_METHOD *method;
675 BIO *biobuf = NULL;
676 char buf[2048];
677 char *vptr;
678 int len;
679 const unsigned char *p;
Bill Janssen98d19da2007-09-10 21:51:02 +0000680
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000681 if (certificate == NULL)
682 return peer_alt_names;
Bill Janssen98d19da2007-09-10 21:51:02 +0000683
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000684 /* get a memory buffer */
685 biobuf = BIO_new(BIO_s_mem());
Bill Janssen98d19da2007-09-10 21:51:02 +0000686
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000687 i = 0;
688 while ((i = X509_get_ext_by_NID(
689 certificate, NID_subject_alt_name, i)) >= 0) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000690
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000691 if (peer_alt_names == Py_None) {
692 peer_alt_names = PyList_New(0);
693 if (peer_alt_names == NULL)
694 goto fail;
695 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000696
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000697 /* now decode the altName */
698 ext = X509_get_ext(certificate, i);
699 if(!(method = X509V3_EXT_get(ext))) {
700 PyErr_SetString(PySSLErrorObject,
701 ERRSTR("No method for internalizing subjectAltName!"));
702 goto fail;
703 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000704
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000705 p = ext->value->data;
706 if (method->it)
707 names = (GENERAL_NAMES*) (ASN1_item_d2i(NULL,
708 &p,
709 ext->value->length,
710 ASN1_ITEM_ptr(method->it)));
711 else
712 names = (GENERAL_NAMES*) (method->d2i(NULL,
713 &p,
714 ext->value->length));
Bill Janssen98d19da2007-09-10 21:51:02 +0000715
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000716 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000717
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000718 /* get a rendering of each name in the set of names */
Bill Janssen98d19da2007-09-10 21:51:02 +0000719
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000720 name = sk_GENERAL_NAME_value(names, j);
721 if (name->type == GEN_DIRNAME) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000722
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000723 /* we special-case DirName as a tuple of tuples of attributes */
Bill Janssen98d19da2007-09-10 21:51:02 +0000724
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000725 t = PyTuple_New(2);
726 if (t == NULL) {
727 goto fail;
728 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000729
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000730 v = PyString_FromString("DirName");
731 if (v == NULL) {
732 Py_DECREF(t);
733 goto fail;
734 }
735 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen98d19da2007-09-10 21:51:02 +0000736
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000737 v = _create_tuple_for_X509_NAME (name->d.dirn);
738 if (v == NULL) {
739 Py_DECREF(t);
740 goto fail;
741 }
742 PyTuple_SET_ITEM(t, 1, v);
Bill Janssen98d19da2007-09-10 21:51:02 +0000743
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000744 } else {
Bill Janssen98d19da2007-09-10 21:51:02 +0000745
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000746 /* for everything else, we use the OpenSSL print form */
747
748 (void) BIO_reset(biobuf);
749 GENERAL_NAME_print(biobuf, name);
750 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
751 if (len < 0) {
752 _setSSLError(NULL, 0, __FILE__, __LINE__);
753 goto fail;
754 }
755 vptr = strchr(buf, ':');
756 if (vptr == NULL)
757 goto fail;
758 t = PyTuple_New(2);
759 if (t == NULL)
760 goto fail;
761 v = PyString_FromStringAndSize(buf, (vptr - buf));
762 if (v == NULL) {
763 Py_DECREF(t);
764 goto fail;
765 }
766 PyTuple_SET_ITEM(t, 0, v);
767 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
768 if (v == NULL) {
769 Py_DECREF(t);
770 goto fail;
771 }
772 PyTuple_SET_ITEM(t, 1, v);
773 }
774
775 /* and add that rendering to the list */
776
777 if (PyList_Append(peer_alt_names, t) < 0) {
778 Py_DECREF(t);
779 goto fail;
780 }
781 Py_DECREF(t);
782 }
783 }
784 BIO_free(biobuf);
785 if (peer_alt_names != Py_None) {
786 v = PyList_AsTuple(peer_alt_names);
787 Py_DECREF(peer_alt_names);
788 return v;
789 } else {
790 return peer_alt_names;
791 }
792
Bill Janssen98d19da2007-09-10 21:51:02 +0000793
794 fail:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000795 if (biobuf != NULL)
796 BIO_free(biobuf);
Bill Janssen98d19da2007-09-10 21:51:02 +0000797
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000798 if (peer_alt_names != Py_None) {
799 Py_XDECREF(peer_alt_names);
800 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000801
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000802 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000803}
804
805static PyObject *
806_decode_certificate (X509 *certificate, int verbose) {
807
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000808 PyObject *retval = NULL;
809 BIO *biobuf = NULL;
810 PyObject *peer;
811 PyObject *peer_alt_names = NULL;
812 PyObject *issuer;
813 PyObject *version;
814 PyObject *sn_obj;
815 ASN1_INTEGER *serialNumber;
816 char buf[2048];
817 int len;
818 ASN1_TIME *notBefore, *notAfter;
819 PyObject *pnotBefore, *pnotAfter;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000820
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000821 retval = PyDict_New();
822 if (retval == NULL)
823 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000824
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000825 peer = _create_tuple_for_X509_NAME(
826 X509_get_subject_name(certificate));
827 if (peer == NULL)
828 goto fail0;
829 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
830 Py_DECREF(peer);
831 goto fail0;
832 }
833 Py_DECREF(peer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000834
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000835 if (verbose) {
836 issuer = _create_tuple_for_X509_NAME(
837 X509_get_issuer_name(certificate));
838 if (issuer == NULL)
839 goto fail0;
840 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
841 Py_DECREF(issuer);
842 goto fail0;
843 }
844 Py_DECREF(issuer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000845
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000846 version = PyInt_FromLong(X509_get_version(certificate) + 1);
847 if (PyDict_SetItemString(retval, "version", version) < 0) {
848 Py_DECREF(version);
849 goto fail0;
850 }
851 Py_DECREF(version);
852 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000853
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000854 /* get a memory buffer */
855 biobuf = BIO_new(BIO_s_mem());
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000856
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000857 if (verbose) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000858
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000859 (void) BIO_reset(biobuf);
860 serialNumber = X509_get_serialNumber(certificate);
861 /* should not exceed 20 octets, 160 bits, so buf is big enough */
862 i2a_ASN1_INTEGER(biobuf, serialNumber);
863 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
864 if (len < 0) {
865 _setSSLError(NULL, 0, __FILE__, __LINE__);
866 goto fail1;
867 }
868 sn_obj = PyString_FromStringAndSize(buf, len);
869 if (sn_obj == NULL)
870 goto fail1;
871 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
872 Py_DECREF(sn_obj);
873 goto fail1;
874 }
875 Py_DECREF(sn_obj);
Bill Janssen98d19da2007-09-10 21:51:02 +0000876
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000877 (void) BIO_reset(biobuf);
878 notBefore = X509_get_notBefore(certificate);
879 ASN1_TIME_print(biobuf, notBefore);
880 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
881 if (len < 0) {
882 _setSSLError(NULL, 0, __FILE__, __LINE__);
883 goto fail1;
884 }
885 pnotBefore = PyString_FromStringAndSize(buf, len);
886 if (pnotBefore == NULL)
887 goto fail1;
888 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
889 Py_DECREF(pnotBefore);
890 goto fail1;
891 }
892 Py_DECREF(pnotBefore);
893 }
894
895 (void) BIO_reset(biobuf);
896 notAfter = X509_get_notAfter(certificate);
897 ASN1_TIME_print(biobuf, notAfter);
898 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
899 if (len < 0) {
900 _setSSLError(NULL, 0, __FILE__, __LINE__);
901 goto fail1;
902 }
903 pnotAfter = PyString_FromStringAndSize(buf, len);
904 if (pnotAfter == NULL)
905 goto fail1;
906 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
907 Py_DECREF(pnotAfter);
908 goto fail1;
909 }
910 Py_DECREF(pnotAfter);
911
912 /* Now look for subjectAltName */
913
914 peer_alt_names = _get_peer_alt_names(certificate);
915 if (peer_alt_names == NULL)
916 goto fail1;
917 else if (peer_alt_names != Py_None) {
918 if (PyDict_SetItemString(retval, "subjectAltName",
919 peer_alt_names) < 0) {
920 Py_DECREF(peer_alt_names);
921 goto fail1;
922 }
923 Py_DECREF(peer_alt_names);
924 }
925
926 BIO_free(biobuf);
927 return retval;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000928
929 fail1:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000930 if (biobuf != NULL)
931 BIO_free(biobuf);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000932 fail0:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000933 Py_XDECREF(retval);
934 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000935}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000936
Bill Janssen98d19da2007-09-10 21:51:02 +0000937
938static PyObject *
939PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
940
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000941 PyObject *retval = NULL;
942 char *filename = NULL;
943 X509 *x=NULL;
944 BIO *cert;
945 int verbose = 1;
Bill Janssen98d19da2007-09-10 21:51:02 +0000946
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000947 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", &filename, &verbose))
948 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000949
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000950 if ((cert=BIO_new(BIO_s_file())) == NULL) {
951 PyErr_SetString(PySSLErrorObject, "Can't malloc memory to read file");
952 goto fail0;
953 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000954
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000955 if (BIO_read_filename(cert,filename) <= 0) {
956 PyErr_SetString(PySSLErrorObject, "Can't open file");
957 goto fail0;
958 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000959
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000960 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
961 if (x == NULL) {
962 PyErr_SetString(PySSLErrorObject, "Error decoding PEM-encoded file");
963 goto fail0;
964 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000965
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000966 retval = _decode_certificate(x, verbose);
Bill Janssen98d19da2007-09-10 21:51:02 +0000967
968 fail0:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000969
970 if (cert != NULL) BIO_free(cert);
971 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +0000972}
973
974
975static PyObject *
976PySSL_peercert(PySSLObject *self, PyObject *args)
977{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000978 PyObject *retval = NULL;
979 int len;
980 int verification;
981 PyObject *binary_mode = Py_None;
Bill Janssen98d19da2007-09-10 21:51:02 +0000982
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000983 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
984 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000985
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000986 if (!self->peer_cert)
987 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +0000988
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000989 if (PyObject_IsTrue(binary_mode)) {
990 /* return cert in DER-encoded format */
Bill Janssen98d19da2007-09-10 21:51:02 +0000991
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000992 unsigned char *bytes_buf = NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000993
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000994 bytes_buf = NULL;
995 len = i2d_X509(self->peer_cert, &bytes_buf);
996 if (len < 0) {
997 PySSL_SetError(self, len, __FILE__, __LINE__);
998 return NULL;
999 }
1000 retval = PyString_FromStringAndSize((const char *) bytes_buf, len);
1001 OPENSSL_free(bytes_buf);
1002 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +00001003
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001004 } else {
Bill Janssen98d19da2007-09-10 21:51:02 +00001005
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001006 verification = SSL_CTX_get_verify_mode(self->ctx);
1007 if ((verification & SSL_VERIFY_PEER) == 0)
1008 return PyDict_New();
1009 else
1010 return _decode_certificate (self->peer_cert, 0);
1011 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001012}
1013
1014PyDoc_STRVAR(PySSL_peercert_doc,
1015"peer_certificate([der=False]) -> certificate\n\
1016\n\
1017Returns the certificate for the peer. If no certificate was provided,\n\
1018returns None. If a certificate was provided, but not validated, returns\n\
1019an empty dictionary. Otherwise returns a dict containing information\n\
1020about the peer certificate.\n\
1021\n\
1022If the optional argument is True, returns a DER-encoded copy of the\n\
1023peer certificate, or None if no certificate was provided. This will\n\
1024return the certificate even if it wasn't validated.");
1025
1026static PyObject *PySSL_cipher (PySSLObject *self) {
1027
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001028 PyObject *retval, *v;
1029 SSL_CIPHER *current;
1030 char *cipher_name;
1031 char *cipher_protocol;
Bill Janssen98d19da2007-09-10 21:51:02 +00001032
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001033 if (self->ssl == NULL)
1034 return Py_None;
1035 current = SSL_get_current_cipher(self->ssl);
1036 if (current == NULL)
1037 return Py_None;
Bill Janssen98d19da2007-09-10 21:51:02 +00001038
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001039 retval = PyTuple_New(3);
1040 if (retval == NULL)
1041 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001042
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001043 cipher_name = (char *) SSL_CIPHER_get_name(current);
1044 if (cipher_name == NULL) {
1045 PyTuple_SET_ITEM(retval, 0, Py_None);
1046 } else {
1047 v = PyString_FromString(cipher_name);
1048 if (v == NULL)
1049 goto fail0;
1050 PyTuple_SET_ITEM(retval, 0, v);
1051 }
1052 cipher_protocol = SSL_CIPHER_get_version(current);
1053 if (cipher_protocol == NULL) {
1054 PyTuple_SET_ITEM(retval, 1, Py_None);
1055 } else {
1056 v = PyString_FromString(cipher_protocol);
1057 if (v == NULL)
1058 goto fail0;
1059 PyTuple_SET_ITEM(retval, 1, v);
1060 }
1061 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1062 if (v == NULL)
1063 goto fail0;
1064 PyTuple_SET_ITEM(retval, 2, v);
1065 return retval;
1066
Bill Janssen98d19da2007-09-10 21:51:02 +00001067 fail0:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001068 Py_DECREF(retval);
1069 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001070}
1071
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001072static void PySSL_dealloc(PySSLObject *self)
1073{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001074 if (self->peer_cert) /* Possible not to have one? */
1075 X509_free (self->peer_cert);
1076 if (self->ssl)
1077 SSL_free(self->ssl);
1078 if (self->ctx)
1079 SSL_CTX_free(self->ctx);
1080 Py_XDECREF(self->Socket);
1081 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001082}
1083
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001084/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001085 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001086 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001087 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001088
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001089static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001090check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001091{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001092 fd_set fds;
1093 struct timeval tv;
1094 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001095
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001096 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1097 if (s->sock_timeout < 0.0)
1098 return SOCKET_IS_BLOCKING;
1099 else if (s->sock_timeout == 0.0)
1100 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001101
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001102 /* Guard against closed socket */
1103 if (s->sock_fd < 0)
1104 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001105
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001106 /* Prefer poll, if available, since you can poll() any fd
1107 * which can't be done with select(). */
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001108#ifdef HAVE_POLL
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001109 {
1110 struct pollfd pollfd;
1111 int timeout;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001112
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001113 pollfd.fd = s->sock_fd;
1114 pollfd.events = writing ? POLLOUT : POLLIN;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001115
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001116 /* s->sock_timeout is in seconds, timeout in ms */
1117 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1118 PySSL_BEGIN_ALLOW_THREADS
1119 rc = poll(&pollfd, 1, timeout);
1120 PySSL_END_ALLOW_THREADS
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001121
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001122 goto normal_return;
1123 }
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001124#endif
1125
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001126 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001127#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001128 if (s->sock_fd >= FD_SETSIZE)
1129 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001130#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001131
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001132 /* Construct the arguments to select */
1133 tv.tv_sec = (int)s->sock_timeout;
1134 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1135 FD_ZERO(&fds);
1136 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001137
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001138 /* See if the socket is ready */
1139 PySSL_BEGIN_ALLOW_THREADS
1140 if (writing)
1141 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1142 else
1143 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1144 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001145
Bill Janssen934b16d2008-06-28 22:19:33 +00001146#ifdef HAVE_POLL
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001147normal_return:
Bill Janssen934b16d2008-06-28 22:19:33 +00001148#endif
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001149 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1150 (when we are able to write or when there's something to read) */
1151 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001152}
1153
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001154static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1155{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001156 char *data;
1157 int len;
1158 int count;
1159 int sockstate;
1160 int err;
1161 int nonblocking;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001162
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001163 if (!PyArg_ParseTuple(args, "s#:write", &data, &count))
1164 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001165
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001166 /* just in case the blocking state of the socket has been changed */
1167 nonblocking = (self->Socket->sock_timeout >= 0.0);
1168 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1169 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001170
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001171 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1172 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1173 PyErr_SetString(PySSLErrorObject,
1174 "The write operation timed out");
1175 return NULL;
1176 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1177 PyErr_SetString(PySSLErrorObject,
1178 "Underlying socket has been closed.");
1179 return NULL;
1180 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1181 PyErr_SetString(PySSLErrorObject,
1182 "Underlying socket too large for select().");
1183 return NULL;
1184 }
1185 do {
1186 err = 0;
1187 PySSL_BEGIN_ALLOW_THREADS
1188 len = SSL_write(self->ssl, data, count);
1189 err = SSL_get_error(self->ssl, len);
1190 PySSL_END_ALLOW_THREADS
1191 if(PyErr_CheckSignals()) {
1192 return NULL;
1193 }
1194 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001195 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001196 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001197 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001198 } else {
1199 sockstate = SOCKET_OPERATION_OK;
1200 }
1201 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1202 PyErr_SetString(PySSLErrorObject,
1203 "The write operation timed out");
1204 return NULL;
1205 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1206 PyErr_SetString(PySSLErrorObject,
1207 "Underlying socket has been closed.");
1208 return NULL;
1209 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1210 break;
1211 }
1212 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1213 if (len > 0)
1214 return PyInt_FromLong(len);
1215 else
1216 return PySSL_SetError(self, len, __FILE__, __LINE__);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001217}
1218
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001219PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001220"write(s) -> len\n\
1221\n\
1222Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001223of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001224
Bill Janssen934b16d2008-06-28 22:19:33 +00001225static PyObject *PySSL_SSLpending(PySSLObject *self)
1226{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001227 int count = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001228
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001229 PySSL_BEGIN_ALLOW_THREADS
1230 count = SSL_pending(self->ssl);
1231 PySSL_END_ALLOW_THREADS
1232 if (count < 0)
1233 return PySSL_SetError(self, count, __FILE__, __LINE__);
1234 else
1235 return PyInt_FromLong(count);
Bill Janssen934b16d2008-06-28 22:19:33 +00001236}
1237
1238PyDoc_STRVAR(PySSL_SSLpending_doc,
1239"pending() -> count\n\
1240\n\
1241Returns the number of already decrypted bytes available for read,\n\
1242pending on the connection.\n");
1243
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001244static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1245{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001246 PyObject *buf;
1247 int count = 0;
1248 int len = 1024;
1249 int sockstate;
1250 int err;
1251 int nonblocking;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001252
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001253 if (!PyArg_ParseTuple(args, "|i:read", &len))
1254 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001255
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001256 if (!(buf = PyString_FromStringAndSize((char *) 0, len)))
1257 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001258
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001259 /* just in case the blocking state of the socket has been changed */
1260 nonblocking = (self->Socket->sock_timeout >= 0.0);
1261 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1262 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001263
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001264 /* first check if there are bytes ready to be read */
1265 PySSL_BEGIN_ALLOW_THREADS
1266 count = SSL_pending(self->ssl);
1267 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001268
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001269 if (!count) {
1270 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1271 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1272 PyErr_SetString(PySSLErrorObject,
1273 "The read operation timed out");
1274 Py_DECREF(buf);
1275 return NULL;
1276 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1277 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001278 "Underlying socket too large for select().");
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001279 Py_DECREF(buf);
1280 return NULL;
1281 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1282 if (SSL_get_shutdown(self->ssl) !=
1283 SSL_RECEIVED_SHUTDOWN)
1284 {
1285 Py_DECREF(buf);
1286 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001287 "Socket closed without SSL shutdown handshake");
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001288 return NULL;
1289 } else {
1290 /* should contain a zero-length string */
1291 _PyString_Resize(&buf, 0);
1292 return buf;
1293 }
1294 }
1295 }
1296 do {
1297 err = 0;
1298 PySSL_BEGIN_ALLOW_THREADS
1299 count = SSL_read(self->ssl, PyString_AsString(buf), len);
1300 err = SSL_get_error(self->ssl, count);
1301 PySSL_END_ALLOW_THREADS
1302 if(PyErr_CheckSignals()) {
1303 Py_DECREF(buf);
1304 return NULL;
1305 }
1306 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001307 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001308 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001309 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001310 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1311 (SSL_get_shutdown(self->ssl) ==
1312 SSL_RECEIVED_SHUTDOWN))
1313 {
1314 _PyString_Resize(&buf, 0);
1315 return buf;
1316 } else {
1317 sockstate = SOCKET_OPERATION_OK;
1318 }
1319 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1320 PyErr_SetString(PySSLErrorObject,
1321 "The read operation timed out");
1322 Py_DECREF(buf);
1323 return NULL;
1324 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1325 break;
1326 }
1327 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1328 if (count <= 0) {
1329 Py_DECREF(buf);
1330 return PySSL_SetError(self, count, __FILE__, __LINE__);
1331 }
1332 if (count != len)
1333 _PyString_Resize(&buf, count);
1334 return buf;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001335}
1336
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001337PyDoc_STRVAR(PySSL_SSLread_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001338"read([len]) -> string\n\
1339\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001340Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001341
Bill Janssen934b16d2008-06-28 22:19:33 +00001342static PyObject *PySSL_SSLshutdown(PySSLObject *self)
1343{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001344 int err, ssl_err, sockstate, nonblocking;
1345 int zeros = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001346
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001347 /* Guard against closed socket */
1348 if (self->Socket->sock_fd < 0) {
1349 PyErr_SetString(PySSLErrorObject,
1350 "Underlying socket has been closed.");
1351 return NULL;
1352 }
Bill Janssen934b16d2008-06-28 22:19:33 +00001353
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001354 /* Just in case the blocking state of the socket has been changed */
1355 nonblocking = (self->Socket->sock_timeout >= 0.0);
1356 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1357 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitrou07072162010-04-23 21:07:58 +00001358
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001359 while (1) {
1360 PySSL_BEGIN_ALLOW_THREADS
1361 /* Disable read-ahead so that unwrap can work correctly.
1362 * Otherwise OpenSSL might read in too much data,
1363 * eating clear text data that happens to be
1364 * transmitted after the SSL shutdown.
1365 * Should be safe to call repeatedly everytime this
1366 * function is used and the shutdown_seen_zero != 0
1367 * condition is met.
1368 */
1369 if (self->shutdown_seen_zero)
1370 SSL_set_read_ahead(self->ssl, 0);
1371 err = SSL_shutdown(self->ssl);
1372 PySSL_END_ALLOW_THREADS
1373 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1374 if (err > 0)
1375 break;
1376 if (err == 0) {
1377 /* Don't loop endlessly; instead preserve legacy
1378 behaviour of trying SSL_shutdown() only twice.
1379 This looks necessary for OpenSSL < 0.9.8m */
1380 if (++zeros > 1)
1381 break;
1382 /* Shutdown was sent, now try receiving */
1383 self->shutdown_seen_zero = 1;
1384 continue;
1385 }
Antoine Pitrou07072162010-04-23 21:07:58 +00001386
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001387 /* Possibly retry shutdown until timeout or failure */
1388 ssl_err = SSL_get_error(self->ssl, err);
1389 if (ssl_err == SSL_ERROR_WANT_READ)
1390 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1391 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1392 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1393 else
1394 break;
1395 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1396 if (ssl_err == SSL_ERROR_WANT_READ)
1397 PyErr_SetString(PySSLErrorObject,
1398 "The read operation timed out");
1399 else
1400 PyErr_SetString(PySSLErrorObject,
1401 "The write operation timed out");
1402 return NULL;
1403 }
1404 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1405 PyErr_SetString(PySSLErrorObject,
1406 "Underlying socket too large for select().");
1407 return NULL;
1408 }
1409 else if (sockstate != SOCKET_OPERATION_OK)
1410 /* Retain the SSL error code */
1411 break;
1412 }
Bill Janssen934b16d2008-06-28 22:19:33 +00001413
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001414 if (err < 0)
1415 return PySSL_SetError(self, err, __FILE__, __LINE__);
1416 else {
1417 Py_INCREF(self->Socket);
1418 return (PyObject *) (self->Socket);
1419 }
Bill Janssen934b16d2008-06-28 22:19:33 +00001420}
1421
1422PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1423"shutdown(s) -> socket\n\
1424\n\
1425Does the SSL shutdown handshake with the remote end, and returns\n\
1426the underlying socket object.");
1427
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001428static PyMethodDef PySSLMethods[] = {
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001429 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1430 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1431 PySSL_SSLwrite_doc},
1432 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1433 PySSL_SSLread_doc},
1434 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1435 PySSL_SSLpending_doc},
1436 {"server", (PyCFunction)PySSL_server, METH_NOARGS},
1437 {"issuer", (PyCFunction)PySSL_issuer, METH_NOARGS},
1438 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1439 PySSL_peercert_doc},
1440 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1441 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1442 PySSL_SSLshutdown_doc},
1443 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001444};
1445
1446static PyObject *PySSL_getattr(PySSLObject *self, char *name)
1447{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001448 return Py_FindMethod(PySSLMethods, (PyObject *)self, name);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001449}
1450
Jeremy Hylton938ace62002-07-17 16:30:39 +00001451static PyTypeObject PySSL_Type = {
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001452 PyVarObject_HEAD_INIT(NULL, 0)
1453 "ssl.SSLContext", /*tp_name*/
1454 sizeof(PySSLObject), /*tp_basicsize*/
1455 0, /*tp_itemsize*/
1456 /* methods */
1457 (destructor)PySSL_dealloc, /*tp_dealloc*/
1458 0, /*tp_print*/
1459 (getattrfunc)PySSL_getattr, /*tp_getattr*/
1460 0, /*tp_setattr*/
1461 0, /*tp_compare*/
1462 0, /*tp_repr*/
1463 0, /*tp_as_number*/
1464 0, /*tp_as_sequence*/
1465 0, /*tp_as_mapping*/
1466 0, /*tp_hash*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001467};
1468
1469#ifdef HAVE_OPENSSL_RAND
1470
1471/* helper routines for seeding the SSL PRNG */
1472static PyObject *
1473PySSL_RAND_add(PyObject *self, PyObject *args)
1474{
1475 char *buf;
1476 int len;
1477 double entropy;
1478
1479 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001480 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001481 RAND_add(buf, len, entropy);
1482 Py_INCREF(Py_None);
1483 return Py_None;
1484}
1485
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001486PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001487"RAND_add(string, entropy)\n\
1488\n\
1489Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00001490bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001491
1492static PyObject *
1493PySSL_RAND_status(PyObject *self)
1494{
1495 return PyInt_FromLong(RAND_status());
1496}
1497
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001498PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001499"RAND_status() -> 0 or 1\n\
1500\n\
1501Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1502It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001503using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001504
1505static PyObject *
1506PySSL_RAND_egd(PyObject *self, PyObject *arg)
1507{
1508 int bytes;
1509
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001510 if (!PyString_Check(arg))
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001511 return PyErr_Format(PyExc_TypeError,
1512 "RAND_egd() expected string, found %s",
1513 Py_TYPE(arg)->tp_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001514 bytes = RAND_egd(PyString_AS_STRING(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001515 if (bytes == -1) {
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001516 PyErr_SetString(PySSLErrorObject,
1517 "EGD connection failed or EGD did not return "
1518 "enough data to seed the PRNG");
1519 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001520 }
1521 return PyInt_FromLong(bytes);
1522}
1523
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001524PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001525"RAND_egd(path) -> bytes\n\
1526\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00001527Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1528Returns number of bytes read. Raises SSLError if connection to EGD\n\
1529fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001530
1531#endif
1532
1533/* List of functions exported by this module. */
1534
1535static PyMethodDef PySSL_methods[] = {
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001536 {"sslwrap", PySSL_sslwrap,
1537 METH_VARARGS, ssl_doc},
1538 {"_test_decode_cert", PySSL_test_decode_certificate,
1539 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001540#ifdef HAVE_OPENSSL_RAND
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001541 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1542 PySSL_RAND_add_doc},
1543 {"RAND_egd", PySSL_RAND_egd, METH_O,
1544 PySSL_RAND_egd_doc},
1545 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1546 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001547#endif
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001548 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001549};
1550
1551
Bill Janssen98d19da2007-09-10 21:51:02 +00001552#ifdef WITH_THREAD
1553
1554/* an implementation of OpenSSL threading operations in terms
1555 of the Python C thread library */
1556
1557static PyThread_type_lock *_ssl_locks = NULL;
1558
1559static unsigned long _ssl_thread_id_function (void) {
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001560 return PyThread_get_thread_ident();
Bill Janssen98d19da2007-09-10 21:51:02 +00001561}
1562
1563static void _ssl_thread_locking_function (int mode, int n, const char *file, int line) {
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001564 /* this function is needed to perform locking on shared data
1565 structures. (Note that OpenSSL uses a number of global data
1566 structures that will be implicitly shared whenever multiple threads
1567 use OpenSSL.) Multi-threaded applications will crash at random if
1568 it is not set.
Bill Janssen98d19da2007-09-10 21:51:02 +00001569
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001570 locking_function() must be able to handle up to CRYPTO_num_locks()
1571 different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and
1572 releases it otherwise.
Bill Janssen98d19da2007-09-10 21:51:02 +00001573
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001574 file and line are the file number of the function setting the
1575 lock. They can be useful for debugging.
1576 */
Bill Janssen98d19da2007-09-10 21:51:02 +00001577
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001578 if ((_ssl_locks == NULL) ||
1579 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1580 return;
Bill Janssen98d19da2007-09-10 21:51:02 +00001581
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001582 if (mode & CRYPTO_LOCK) {
1583 PyThread_acquire_lock(_ssl_locks[n], 1);
1584 } else {
1585 PyThread_release_lock(_ssl_locks[n]);
1586 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001587}
1588
1589static int _setup_ssl_threads(void) {
1590
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001591 unsigned int i;
Bill Janssen98d19da2007-09-10 21:51:02 +00001592
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001593 if (_ssl_locks == NULL) {
1594 _ssl_locks_count = CRYPTO_num_locks();
1595 _ssl_locks = (PyThread_type_lock *)
1596 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1597 if (_ssl_locks == NULL)
1598 return 0;
1599 memset(_ssl_locks, 0, sizeof(PyThread_type_lock) * _ssl_locks_count);
1600 for (i = 0; i < _ssl_locks_count; i++) {
1601 _ssl_locks[i] = PyThread_allocate_lock();
1602 if (_ssl_locks[i] == NULL) {
1603 unsigned int j;
1604 for (j = 0; j < i; j++) {
1605 PyThread_free_lock(_ssl_locks[j]);
1606 }
1607 free(_ssl_locks);
1608 return 0;
1609 }
1610 }
1611 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1612 CRYPTO_set_id_callback(_ssl_thread_id_function);
1613 }
1614 return 1;
Bill Janssen98d19da2007-09-10 21:51:02 +00001615}
1616
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001617#endif /* def HAVE_THREAD */
Bill Janssen98d19da2007-09-10 21:51:02 +00001618
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001619PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001620"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001621for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001622
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001623PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001624init_ssl(void)
1625{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001626 PyObject *m, *d;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001627
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001628 Py_TYPE(&PySSL_Type) = &PyType_Type;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001629
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001630 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
1631 if (m == NULL)
1632 return;
1633 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001634
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001635 /* Load _socket module and its C API */
1636 if (PySocketModule_ImportModuleAndAPI())
1637 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001638
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001639 /* Init OpenSSL */
1640 SSL_load_error_strings();
1641 SSL_library_init();
Bill Janssen98d19da2007-09-10 21:51:02 +00001642#ifdef WITH_THREAD
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001643 /* note that this will start threading if not already started */
1644 if (!_setup_ssl_threads()) {
1645 return;
1646 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001647#endif
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001648 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001649
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001650 /* Add symbols to module dict */
1651 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
1652 PySocketModule.error,
1653 NULL);
1654 if (PySSLErrorObject == NULL)
1655 return;
1656 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
1657 return;
1658 if (PyDict_SetItemString(d, "SSLType",
1659 (PyObject *)&PySSL_Type) != 0)
1660 return;
1661 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
1662 PY_SSL_ERROR_ZERO_RETURN);
1663 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
1664 PY_SSL_ERROR_WANT_READ);
1665 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
1666 PY_SSL_ERROR_WANT_WRITE);
1667 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
1668 PY_SSL_ERROR_WANT_X509_LOOKUP);
1669 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
1670 PY_SSL_ERROR_SYSCALL);
1671 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
1672 PY_SSL_ERROR_SSL);
1673 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1674 PY_SSL_ERROR_WANT_CONNECT);
1675 /* non ssl.h errorcodes */
1676 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1677 PY_SSL_ERROR_EOF);
1678 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1679 PY_SSL_ERROR_INVALID_ERROR_CODE);
1680 /* cert requirements */
1681 PyModule_AddIntConstant(m, "CERT_NONE",
1682 PY_SSL_CERT_NONE);
1683 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1684 PY_SSL_CERT_OPTIONAL);
1685 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1686 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001687
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001688 /* protocol versions */
1689 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1690 PY_SSL_VERSION_SSL2);
1691 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1692 PY_SSL_VERSION_SSL3);
1693 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1694 PY_SSL_VERSION_SSL23);
1695 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1696 PY_SSL_VERSION_TLS1);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001697}