blob: ff634d6894bc5be0ddc779414776d4eb1ef53c95 [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 */
199 return obj->Socket->errorhandler();
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000200 } else { /* possible? */
Antoine Pitrou96125cf2010-05-12 14:05:34 +0000201 p = PY_SSL_ERROR_SYSCALL;
202 errstr = "Some I/O error occurred";
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000203 }
204 } else {
205 p = PY_SSL_ERROR_SYSCALL;
206 /* XXX Protected by global interpreter lock */
207 errstr = ERR_error_string(e, NULL);
208 }
209 break;
210 }
211 case SSL_ERROR_SSL:
212 {
213 unsigned long e = ERR_get_error();
214 p = PY_SSL_ERROR_SSL;
215 if (e != 0)
216 /* XXX Protected by global interpreter lock */
217 errstr = ERR_error_string(e, NULL);
218 else { /* possible? */
Antoine Pitrou96125cf2010-05-12 14:05:34 +0000219 errstr = "A failure in the SSL library occurred";
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000220 }
221 break;
222 }
223 default:
224 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
225 errstr = "Invalid error code";
226 }
227 } else {
228 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
229 }
230 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
231 v = Py_BuildValue("(is)", p, buf);
232 if (v != NULL) {
233 PyErr_SetObject(PySSLErrorObject, v);
234 Py_DECREF(v);
235 }
236 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000237}
238
Bill Janssen98d19da2007-09-10 21:51:02 +0000239static PyObject *
240_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
241
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000242 char buf[2048];
243 PyObject *v;
Bill Janssen98d19da2007-09-10 21:51:02 +0000244
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000245 if (errstr == NULL) {
246 errcode = ERR_peek_last_error();
247 errstr = ERR_error_string(errcode, NULL);
248 }
249 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
250 v = Py_BuildValue("(is)", errcode, buf);
251 if (v != NULL) {
252 PyErr_SetObject(PySSLErrorObject, v);
253 Py_DECREF(v);
254 }
255 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000256}
257
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000258static PySSLObject *
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000259newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file,
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000260 enum py_ssl_server_or_client socket_type,
261 enum py_ssl_cert_requirements certreq,
262 enum py_ssl_version proto_version,
263 char *cacerts_file)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000264{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000265 PySSLObject *self;
266 char *errstr = NULL;
267 int ret;
268 int verification_mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000269
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000270 self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */
271 if (self == NULL)
272 return NULL;
273 memset(self->server, '\0', sizeof(char) * X509_NAME_MAXLEN);
274 memset(self->issuer, '\0', sizeof(char) * X509_NAME_MAXLEN);
275 self->peer_cert = NULL;
276 self->ssl = NULL;
277 self->ctx = NULL;
278 self->Socket = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000279
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000280 /* Make sure the SSL error state is initialized */
281 (void) ERR_get_state();
282 ERR_clear_error();
Bill Janssen98d19da2007-09-10 21:51:02 +0000283
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000284 if ((key_file && !cert_file) || (!key_file && cert_file)) {
285 errstr = ERRSTR("Both the key & certificate files "
286 "must be specified");
287 goto fail;
288 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000289
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000290 if ((socket_type == PY_SSL_SERVER) &&
291 ((key_file == NULL) || (cert_file == NULL))) {
292 errstr = ERRSTR("Both the key & certificate files "
293 "must be specified for server-side operation");
294 goto fail;
295 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000296
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000297 PySSL_BEGIN_ALLOW_THREADS
298 if (proto_version == PY_SSL_VERSION_TLS1)
299 self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */
300 else if (proto_version == PY_SSL_VERSION_SSL3)
301 self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */
302 else if (proto_version == PY_SSL_VERSION_SSL2)
303 self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */
304 else if (proto_version == PY_SSL_VERSION_SSL23)
305 self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
306 PySSL_END_ALLOW_THREADS
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000307
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000308 if (self->ctx == NULL) {
309 errstr = ERRSTR("Invalid SSL protocol variant specified.");
310 goto fail;
311 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000312
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000313 if (certreq != PY_SSL_CERT_NONE) {
314 if (cacerts_file == NULL) {
315 errstr = ERRSTR("No root certificates specified for "
Antoine Pitrou96125cf2010-05-12 14:05:34 +0000316 "verification of other-side certificates.");
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000317 goto fail;
318 } else {
319 PySSL_BEGIN_ALLOW_THREADS
320 ret = SSL_CTX_load_verify_locations(self->ctx,
321 cacerts_file,
322 NULL);
323 PySSL_END_ALLOW_THREADS
324 if (ret != 1) {
325 _setSSLError(NULL, 0, __FILE__, __LINE__);
326 goto fail;
327 }
328 }
329 }
330 if (key_file) {
331 PySSL_BEGIN_ALLOW_THREADS
332 ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
333 SSL_FILETYPE_PEM);
334 PySSL_END_ALLOW_THREADS
335 if (ret != 1) {
336 _setSSLError(NULL, ret, __FILE__, __LINE__);
337 goto fail;
338 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000339
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000340 PySSL_BEGIN_ALLOW_THREADS
341 ret = SSL_CTX_use_certificate_chain_file(self->ctx,
342 cert_file);
343 PySSL_END_ALLOW_THREADS
344 if (ret != 1) {
345 /*
346 fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
347 ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
348 */
349 if (ERR_peek_last_error() != 0) {
350 _setSSLError(NULL, ret, __FILE__, __LINE__);
351 goto fail;
352 }
353 }
354 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000355
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000356 /* ssl compatibility */
357 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
Bill Janssen98d19da2007-09-10 21:51:02 +0000358
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000359 verification_mode = SSL_VERIFY_NONE;
360 if (certreq == PY_SSL_CERT_OPTIONAL)
361 verification_mode = SSL_VERIFY_PEER;
362 else if (certreq == PY_SSL_CERT_REQUIRED)
363 verification_mode = (SSL_VERIFY_PEER |
364 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
365 SSL_CTX_set_verify(self->ctx, verification_mode,
366 NULL); /* set verify lvl */
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000367
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000368 PySSL_BEGIN_ALLOW_THREADS
369 self->ssl = SSL_new(self->ctx); /* New ssl struct */
370 PySSL_END_ALLOW_THREADS
371 SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */
Antoine Pitrou206685b2010-04-09 20:44:09 +0000372#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000373 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou206685b2010-04-09 20:44:09 +0000374#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000375
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000376 /* If the socket is in non-blocking mode or timeout mode, set the BIO
377 * to non-blocking mode (blocking is the default)
378 */
379 if (Sock->sock_timeout >= 0.0) {
380 /* Set both the read and write BIO's to non-blocking mode */
381 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
382 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
383 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000384
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000385 PySSL_BEGIN_ALLOW_THREADS
386 if (socket_type == PY_SSL_CLIENT)
387 SSL_set_connect_state(self->ssl);
388 else
389 SSL_set_accept_state(self->ssl);
390 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000391
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000392 self->Socket = Sock;
393 Py_INCREF(self->Socket);
394 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000395 fail:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000396 if (errstr)
397 PyErr_SetString(PySSLErrorObject, errstr);
398 Py_DECREF(self);
399 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000400}
401
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000402static PyObject *
Guido van Rossum780b80d2007-08-27 18:42:23 +0000403PySSL_sslwrap(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000404{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000405 PySocketSockObject *Sock;
406 int server_side = 0;
407 int verification_mode = PY_SSL_CERT_NONE;
408 int protocol = PY_SSL_VERSION_SSL23;
409 char *key_file = NULL;
410 char *cert_file = NULL;
411 char *cacerts_file = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000412
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000413 if (!PyArg_ParseTuple(args, "O!i|zziiz:sslwrap",
414 PySocketModule.Sock_Type,
415 &Sock,
416 &server_side,
417 &key_file, &cert_file,
418 &verification_mode, &protocol,
419 &cacerts_file))
420 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000421
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000422 /*
423 fprintf(stderr,
424 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
425 "protocol %d, certs %p\n",
426 server_side, key_file, cert_file, verification_mode,
427 protocol, cacerts_file);
428 */
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000429
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000430 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
431 server_side, verification_mode,
432 protocol, cacerts_file);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000433}
434
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000435PyDoc_STRVAR(ssl_doc,
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000436"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
437" cacertsfile]) -> sslobject");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000438
439/* SSL object methods */
440
Bill Janssen934b16d2008-06-28 22:19:33 +0000441static PyObject *PySSL_SSLdo_handshake(PySSLObject *self)
442{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000443 int ret;
444 int err;
445 int sockstate, nonblocking;
Antoine Pitrouc689d962010-04-24 20:13:37 +0000446
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000447 /* just in case the blocking state of the socket has been changed */
448 nonblocking = (self->Socket->sock_timeout >= 0.0);
449 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
450 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +0000451
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000452 /* Actually negotiate SSL connection */
453 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
454 sockstate = 0;
455 do {
456 PySSL_BEGIN_ALLOW_THREADS
457 ret = SSL_do_handshake(self->ssl);
458 err = SSL_get_error(self->ssl, ret);
459 PySSL_END_ALLOW_THREADS
460 if(PyErr_CheckSignals()) {
461 return NULL;
462 }
463 if (err == SSL_ERROR_WANT_READ) {
464 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
465 } else if (err == SSL_ERROR_WANT_WRITE) {
466 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
467 } else {
468 sockstate = SOCKET_OPERATION_OK;
469 }
470 if (sockstate == SOCKET_HAS_TIMED_OUT) {
471 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou96125cf2010-05-12 14:05:34 +0000472 ERRSTR("The handshake operation timed out"));
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000473 return NULL;
474 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
475 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou96125cf2010-05-12 14:05:34 +0000476 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000477 return NULL;
478 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
479 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou96125cf2010-05-12 14:05:34 +0000480 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000481 return NULL;
482 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
483 break;
484 }
485 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
486 if (ret < 1)
487 return PySSL_SetError(self, ret, __FILE__, __LINE__);
488 self->ssl->debug = 1;
Bill Janssen934b16d2008-06-28 22:19:33 +0000489
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000490 if (self->peer_cert)
491 X509_free (self->peer_cert);
492 PySSL_BEGIN_ALLOW_THREADS
493 if ((self->peer_cert = SSL_get_peer_certificate(self->ssl))) {
494 X509_NAME_oneline(X509_get_subject_name(self->peer_cert),
495 self->server, X509_NAME_MAXLEN);
496 X509_NAME_oneline(X509_get_issuer_name(self->peer_cert),
497 self->issuer, X509_NAME_MAXLEN);
498 }
499 PySSL_END_ALLOW_THREADS
Bill Janssen934b16d2008-06-28 22:19:33 +0000500
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000501 Py_INCREF(Py_None);
502 return Py_None;
Bill Janssen934b16d2008-06-28 22:19:33 +0000503}
504
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000505static PyObject *
506PySSL_server(PySSLObject *self)
507{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000508 return PyString_FromString(self->server);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000509}
510
511static PyObject *
512PySSL_issuer(PySSLObject *self)
513{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000514 return PyString_FromString(self->issuer);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000515}
516
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000517static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000518_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000519
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000520 char namebuf[X509_NAME_MAXLEN];
521 int buflen;
522 PyObject *name_obj;
523 PyObject *value_obj;
524 PyObject *attr;
525 unsigned char *valuebuf = NULL;
Guido van Rossum780b80d2007-08-27 18:42:23 +0000526
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000527 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
528 if (buflen < 0) {
529 _setSSLError(NULL, 0, __FILE__, __LINE__);
530 goto fail;
531 }
532 name_obj = PyString_FromStringAndSize(namebuf, buflen);
533 if (name_obj == NULL)
534 goto fail;
535
536 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
537 if (buflen < 0) {
538 _setSSLError(NULL, 0, __FILE__, __LINE__);
539 Py_DECREF(name_obj);
540 goto fail;
541 }
542 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou96125cf2010-05-12 14:05:34 +0000543 buflen, "strict");
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000544 OPENSSL_free(valuebuf);
545 if (value_obj == NULL) {
546 Py_DECREF(name_obj);
547 goto fail;
548 }
549 attr = PyTuple_New(2);
550 if (attr == NULL) {
551 Py_DECREF(name_obj);
552 Py_DECREF(value_obj);
553 goto fail;
554 }
555 PyTuple_SET_ITEM(attr, 0, name_obj);
556 PyTuple_SET_ITEM(attr, 1, value_obj);
557 return attr;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000558
Bill Janssen98d19da2007-09-10 21:51:02 +0000559 fail:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000560 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000561}
562
563static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000564_create_tuple_for_X509_NAME (X509_NAME *xname)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000565{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000566 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
567 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
568 PyObject *rdnt;
569 PyObject *attr = NULL; /* tuple to hold an attribute */
570 int entry_count = X509_NAME_entry_count(xname);
571 X509_NAME_ENTRY *entry;
572 ASN1_OBJECT *name;
573 ASN1_STRING *value;
574 int index_counter;
575 int rdn_level = -1;
576 int retcode;
Bill Janssen98d19da2007-09-10 21:51:02 +0000577
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000578 dn = PyList_New(0);
579 if (dn == NULL)
580 return NULL;
581 /* now create another tuple to hold the top-level RDN */
582 rdn = PyList_New(0);
583 if (rdn == NULL)
584 goto fail0;
Bill Janssen98d19da2007-09-10 21:51:02 +0000585
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000586 for (index_counter = 0;
587 index_counter < entry_count;
588 index_counter++)
589 {
590 entry = X509_NAME_get_entry(xname, index_counter);
Bill Janssen98d19da2007-09-10 21:51:02 +0000591
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000592 /* check to see if we've gotten to a new RDN */
593 if (rdn_level >= 0) {
594 if (rdn_level != entry->set) {
595 /* yes, new RDN */
596 /* add old RDN to DN */
597 rdnt = PyList_AsTuple(rdn);
598 Py_DECREF(rdn);
599 if (rdnt == NULL)
600 goto fail0;
601 retcode = PyList_Append(dn, rdnt);
602 Py_DECREF(rdnt);
603 if (retcode < 0)
604 goto fail0;
605 /* create new RDN */
606 rdn = PyList_New(0);
607 if (rdn == NULL)
608 goto fail0;
609 }
610 }
611 rdn_level = entry->set;
Bill Janssen98d19da2007-09-10 21:51:02 +0000612
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000613 /* now add this attribute to the current RDN */
614 name = X509_NAME_ENTRY_get_object(entry);
615 value = X509_NAME_ENTRY_get_data(entry);
616 attr = _create_tuple_for_attribute(name, value);
617 /*
618 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
619 entry->set,
620 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
621 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
622 */
623 if (attr == NULL)
624 goto fail1;
625 retcode = PyList_Append(rdn, attr);
626 Py_DECREF(attr);
627 if (retcode < 0)
628 goto fail1;
629 }
630 /* now, there's typically a dangling RDN */
631 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
632 rdnt = PyList_AsTuple(rdn);
633 Py_DECREF(rdn);
634 if (rdnt == NULL)
635 goto fail0;
636 retcode = PyList_Append(dn, rdnt);
637 Py_DECREF(rdnt);
638 if (retcode < 0)
639 goto fail0;
640 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000641
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000642 /* convert list to tuple */
643 rdnt = PyList_AsTuple(dn);
644 Py_DECREF(dn);
645 if (rdnt == NULL)
646 return NULL;
647 return rdnt;
Bill Janssen98d19da2007-09-10 21:51:02 +0000648
649 fail1:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000650 Py_XDECREF(rdn);
Bill Janssen98d19da2007-09-10 21:51:02 +0000651
652 fail0:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000653 Py_XDECREF(dn);
654 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000655}
656
657static PyObject *
658_get_peer_alt_names (X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000659
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000660 /* this code follows the procedure outlined in
661 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
662 function to extract the STACK_OF(GENERAL_NAME),
663 then iterates through the stack to add the
664 names. */
Bill Janssen98d19da2007-09-10 21:51:02 +0000665
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000666 int i, j;
667 PyObject *peer_alt_names = Py_None;
668 PyObject *v, *t;
669 X509_EXTENSION *ext = NULL;
670 GENERAL_NAMES *names = NULL;
671 GENERAL_NAME *name;
672 X509V3_EXT_METHOD *method;
673 BIO *biobuf = NULL;
674 char buf[2048];
675 char *vptr;
676 int len;
677 const unsigned char *p;
Bill Janssen98d19da2007-09-10 21:51:02 +0000678
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000679 if (certificate == NULL)
680 return peer_alt_names;
Bill Janssen98d19da2007-09-10 21:51:02 +0000681
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000682 /* get a memory buffer */
683 biobuf = BIO_new(BIO_s_mem());
Bill Janssen98d19da2007-09-10 21:51:02 +0000684
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000685 i = 0;
686 while ((i = X509_get_ext_by_NID(
687 certificate, NID_subject_alt_name, i)) >= 0) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000688
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000689 if (peer_alt_names == Py_None) {
690 peer_alt_names = PyList_New(0);
691 if (peer_alt_names == NULL)
692 goto fail;
693 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000694
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000695 /* now decode the altName */
696 ext = X509_get_ext(certificate, i);
697 if(!(method = X509V3_EXT_get(ext))) {
698 PyErr_SetString(PySSLErrorObject,
699 ERRSTR("No method for internalizing subjectAltName!"));
700 goto fail;
701 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000702
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000703 p = ext->value->data;
704 if (method->it)
705 names = (GENERAL_NAMES*) (ASN1_item_d2i(NULL,
706 &p,
707 ext->value->length,
708 ASN1_ITEM_ptr(method->it)));
709 else
710 names = (GENERAL_NAMES*) (method->d2i(NULL,
711 &p,
712 ext->value->length));
Bill Janssen98d19da2007-09-10 21:51:02 +0000713
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000714 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000715
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000716 /* get a rendering of each name in the set of names */
Bill Janssen98d19da2007-09-10 21:51:02 +0000717
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000718 name = sk_GENERAL_NAME_value(names, j);
719 if (name->type == GEN_DIRNAME) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000720
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000721 /* we special-case DirName as a tuple of tuples of attributes */
Bill Janssen98d19da2007-09-10 21:51:02 +0000722
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000723 t = PyTuple_New(2);
724 if (t == NULL) {
725 goto fail;
726 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000727
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000728 v = PyString_FromString("DirName");
729 if (v == NULL) {
730 Py_DECREF(t);
731 goto fail;
732 }
733 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen98d19da2007-09-10 21:51:02 +0000734
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000735 v = _create_tuple_for_X509_NAME (name->d.dirn);
736 if (v == NULL) {
737 Py_DECREF(t);
738 goto fail;
739 }
740 PyTuple_SET_ITEM(t, 1, v);
Bill Janssen98d19da2007-09-10 21:51:02 +0000741
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000742 } else {
Bill Janssen98d19da2007-09-10 21:51:02 +0000743
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000744 /* for everything else, we use the OpenSSL print form */
745
746 (void) BIO_reset(biobuf);
747 GENERAL_NAME_print(biobuf, name);
748 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
749 if (len < 0) {
750 _setSSLError(NULL, 0, __FILE__, __LINE__);
751 goto fail;
752 }
753 vptr = strchr(buf, ':');
754 if (vptr == NULL)
755 goto fail;
756 t = PyTuple_New(2);
757 if (t == NULL)
758 goto fail;
759 v = PyString_FromStringAndSize(buf, (vptr - buf));
760 if (v == NULL) {
761 Py_DECREF(t);
762 goto fail;
763 }
764 PyTuple_SET_ITEM(t, 0, v);
765 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
766 if (v == NULL) {
767 Py_DECREF(t);
768 goto fail;
769 }
770 PyTuple_SET_ITEM(t, 1, v);
771 }
772
773 /* and add that rendering to the list */
774
775 if (PyList_Append(peer_alt_names, t) < 0) {
776 Py_DECREF(t);
777 goto fail;
778 }
779 Py_DECREF(t);
780 }
781 }
782 BIO_free(biobuf);
783 if (peer_alt_names != Py_None) {
784 v = PyList_AsTuple(peer_alt_names);
785 Py_DECREF(peer_alt_names);
786 return v;
787 } else {
788 return peer_alt_names;
789 }
790
Bill Janssen98d19da2007-09-10 21:51:02 +0000791
792 fail:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000793 if (biobuf != NULL)
794 BIO_free(biobuf);
Bill Janssen98d19da2007-09-10 21:51:02 +0000795
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000796 if (peer_alt_names != Py_None) {
797 Py_XDECREF(peer_alt_names);
798 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000799
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000800 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000801}
802
803static PyObject *
804_decode_certificate (X509 *certificate, int verbose) {
805
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000806 PyObject *retval = NULL;
807 BIO *biobuf = NULL;
808 PyObject *peer;
809 PyObject *peer_alt_names = NULL;
810 PyObject *issuer;
811 PyObject *version;
812 PyObject *sn_obj;
813 ASN1_INTEGER *serialNumber;
814 char buf[2048];
815 int len;
816 ASN1_TIME *notBefore, *notAfter;
817 PyObject *pnotBefore, *pnotAfter;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000818
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000819 retval = PyDict_New();
820 if (retval == NULL)
821 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000822
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000823 peer = _create_tuple_for_X509_NAME(
824 X509_get_subject_name(certificate));
825 if (peer == NULL)
826 goto fail0;
827 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
828 Py_DECREF(peer);
829 goto fail0;
830 }
831 Py_DECREF(peer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000832
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000833 if (verbose) {
834 issuer = _create_tuple_for_X509_NAME(
835 X509_get_issuer_name(certificate));
836 if (issuer == NULL)
837 goto fail0;
838 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
839 Py_DECREF(issuer);
840 goto fail0;
841 }
842 Py_DECREF(issuer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000843
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000844 version = PyInt_FromLong(X509_get_version(certificate) + 1);
845 if (PyDict_SetItemString(retval, "version", version) < 0) {
846 Py_DECREF(version);
847 goto fail0;
848 }
849 Py_DECREF(version);
850 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000851
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000852 /* get a memory buffer */
853 biobuf = BIO_new(BIO_s_mem());
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000854
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000855 if (verbose) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000856
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000857 (void) BIO_reset(biobuf);
858 serialNumber = X509_get_serialNumber(certificate);
859 /* should not exceed 20 octets, 160 bits, so buf is big enough */
860 i2a_ASN1_INTEGER(biobuf, serialNumber);
861 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
862 if (len < 0) {
863 _setSSLError(NULL, 0, __FILE__, __LINE__);
864 goto fail1;
865 }
866 sn_obj = PyString_FromStringAndSize(buf, len);
867 if (sn_obj == NULL)
868 goto fail1;
869 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
870 Py_DECREF(sn_obj);
871 goto fail1;
872 }
873 Py_DECREF(sn_obj);
Bill Janssen98d19da2007-09-10 21:51:02 +0000874
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000875 (void) BIO_reset(biobuf);
876 notBefore = X509_get_notBefore(certificate);
877 ASN1_TIME_print(biobuf, notBefore);
878 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
879 if (len < 0) {
880 _setSSLError(NULL, 0, __FILE__, __LINE__);
881 goto fail1;
882 }
883 pnotBefore = PyString_FromStringAndSize(buf, len);
884 if (pnotBefore == NULL)
885 goto fail1;
886 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
887 Py_DECREF(pnotBefore);
888 goto fail1;
889 }
890 Py_DECREF(pnotBefore);
891 }
892
893 (void) BIO_reset(biobuf);
894 notAfter = X509_get_notAfter(certificate);
895 ASN1_TIME_print(biobuf, notAfter);
896 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
897 if (len < 0) {
898 _setSSLError(NULL, 0, __FILE__, __LINE__);
899 goto fail1;
900 }
901 pnotAfter = PyString_FromStringAndSize(buf, len);
902 if (pnotAfter == NULL)
903 goto fail1;
904 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
905 Py_DECREF(pnotAfter);
906 goto fail1;
907 }
908 Py_DECREF(pnotAfter);
909
910 /* Now look for subjectAltName */
911
912 peer_alt_names = _get_peer_alt_names(certificate);
913 if (peer_alt_names == NULL)
914 goto fail1;
915 else if (peer_alt_names != Py_None) {
916 if (PyDict_SetItemString(retval, "subjectAltName",
917 peer_alt_names) < 0) {
918 Py_DECREF(peer_alt_names);
919 goto fail1;
920 }
921 Py_DECREF(peer_alt_names);
922 }
923
924 BIO_free(biobuf);
925 return retval;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000926
927 fail1:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000928 if (biobuf != NULL)
929 BIO_free(biobuf);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000930 fail0:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000931 Py_XDECREF(retval);
932 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000933}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000934
Bill Janssen98d19da2007-09-10 21:51:02 +0000935
936static PyObject *
937PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
938
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000939 PyObject *retval = NULL;
940 char *filename = NULL;
941 X509 *x=NULL;
942 BIO *cert;
943 int verbose = 1;
Bill Janssen98d19da2007-09-10 21:51:02 +0000944
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000945 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", &filename, &verbose))
946 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000947
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000948 if ((cert=BIO_new(BIO_s_file())) == NULL) {
949 PyErr_SetString(PySSLErrorObject, "Can't malloc memory to read file");
950 goto fail0;
951 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000952
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000953 if (BIO_read_filename(cert,filename) <= 0) {
954 PyErr_SetString(PySSLErrorObject, "Can't open file");
955 goto fail0;
956 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000957
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000958 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
959 if (x == NULL) {
960 PyErr_SetString(PySSLErrorObject, "Error decoding PEM-encoded file");
961 goto fail0;
962 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000963
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000964 retval = _decode_certificate(x, verbose);
Bill Janssen98d19da2007-09-10 21:51:02 +0000965
966 fail0:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000967
968 if (cert != NULL) BIO_free(cert);
969 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +0000970}
971
972
973static PyObject *
974PySSL_peercert(PySSLObject *self, PyObject *args)
975{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000976 PyObject *retval = NULL;
977 int len;
978 int verification;
979 PyObject *binary_mode = Py_None;
Bill Janssen98d19da2007-09-10 21:51:02 +0000980
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000981 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
982 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000983
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000984 if (!self->peer_cert)
985 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +0000986
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000987 if (PyObject_IsTrue(binary_mode)) {
988 /* return cert in DER-encoded format */
Bill Janssen98d19da2007-09-10 21:51:02 +0000989
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000990 unsigned char *bytes_buf = NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000991
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000992 bytes_buf = NULL;
993 len = i2d_X509(self->peer_cert, &bytes_buf);
994 if (len < 0) {
995 PySSL_SetError(self, len, __FILE__, __LINE__);
996 return NULL;
997 }
998 retval = PyString_FromStringAndSize((const char *) bytes_buf, len);
999 OPENSSL_free(bytes_buf);
1000 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +00001001
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001002 } else {
Bill Janssen98d19da2007-09-10 21:51:02 +00001003
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001004 verification = SSL_CTX_get_verify_mode(self->ctx);
1005 if ((verification & SSL_VERIFY_PEER) == 0)
1006 return PyDict_New();
1007 else
1008 return _decode_certificate (self->peer_cert, 0);
1009 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001010}
1011
1012PyDoc_STRVAR(PySSL_peercert_doc,
1013"peer_certificate([der=False]) -> certificate\n\
1014\n\
1015Returns the certificate for the peer. If no certificate was provided,\n\
1016returns None. If a certificate was provided, but not validated, returns\n\
1017an empty dictionary. Otherwise returns a dict containing information\n\
1018about the peer certificate.\n\
1019\n\
1020If the optional argument is True, returns a DER-encoded copy of the\n\
1021peer certificate, or None if no certificate was provided. This will\n\
1022return the certificate even if it wasn't validated.");
1023
1024static PyObject *PySSL_cipher (PySSLObject *self) {
1025
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001026 PyObject *retval, *v;
1027 SSL_CIPHER *current;
1028 char *cipher_name;
1029 char *cipher_protocol;
Bill Janssen98d19da2007-09-10 21:51:02 +00001030
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001031 if (self->ssl == NULL)
1032 return Py_None;
1033 current = SSL_get_current_cipher(self->ssl);
1034 if (current == NULL)
1035 return Py_None;
Bill Janssen98d19da2007-09-10 21:51:02 +00001036
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001037 retval = PyTuple_New(3);
1038 if (retval == NULL)
1039 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001040
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001041 cipher_name = (char *) SSL_CIPHER_get_name(current);
1042 if (cipher_name == NULL) {
1043 PyTuple_SET_ITEM(retval, 0, Py_None);
1044 } else {
1045 v = PyString_FromString(cipher_name);
1046 if (v == NULL)
1047 goto fail0;
1048 PyTuple_SET_ITEM(retval, 0, v);
1049 }
1050 cipher_protocol = SSL_CIPHER_get_version(current);
1051 if (cipher_protocol == NULL) {
1052 PyTuple_SET_ITEM(retval, 1, Py_None);
1053 } else {
1054 v = PyString_FromString(cipher_protocol);
1055 if (v == NULL)
1056 goto fail0;
1057 PyTuple_SET_ITEM(retval, 1, v);
1058 }
1059 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1060 if (v == NULL)
1061 goto fail0;
1062 PyTuple_SET_ITEM(retval, 2, v);
1063 return retval;
1064
Bill Janssen98d19da2007-09-10 21:51:02 +00001065 fail0:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001066 Py_DECREF(retval);
1067 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001068}
1069
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001070static void PySSL_dealloc(PySSLObject *self)
1071{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001072 if (self->peer_cert) /* Possible not to have one? */
1073 X509_free (self->peer_cert);
1074 if (self->ssl)
1075 SSL_free(self->ssl);
1076 if (self->ctx)
1077 SSL_CTX_free(self->ctx);
1078 Py_XDECREF(self->Socket);
1079 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001080}
1081
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001082/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001083 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001084 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001085 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001086
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001087static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001088check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001089{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001090 fd_set fds;
1091 struct timeval tv;
1092 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001093
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001094 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1095 if (s->sock_timeout < 0.0)
1096 return SOCKET_IS_BLOCKING;
1097 else if (s->sock_timeout == 0.0)
1098 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001099
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001100 /* Guard against closed socket */
1101 if (s->sock_fd < 0)
1102 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001103
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001104 /* Prefer poll, if available, since you can poll() any fd
1105 * which can't be done with select(). */
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001106#ifdef HAVE_POLL
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001107 {
1108 struct pollfd pollfd;
1109 int timeout;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001110
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001111 pollfd.fd = s->sock_fd;
1112 pollfd.events = writing ? POLLOUT : POLLIN;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001113
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001114 /* s->sock_timeout is in seconds, timeout in ms */
1115 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1116 PySSL_BEGIN_ALLOW_THREADS
1117 rc = poll(&pollfd, 1, timeout);
1118 PySSL_END_ALLOW_THREADS
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001119
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001120 goto normal_return;
1121 }
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001122#endif
1123
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001124 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001125#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001126 if (s->sock_fd >= FD_SETSIZE)
1127 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001128#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001129
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001130 /* Construct the arguments to select */
1131 tv.tv_sec = (int)s->sock_timeout;
1132 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1133 FD_ZERO(&fds);
1134 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001135
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001136 /* See if the socket is ready */
1137 PySSL_BEGIN_ALLOW_THREADS
1138 if (writing)
1139 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1140 else
1141 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1142 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001143
Bill Janssen934b16d2008-06-28 22:19:33 +00001144#ifdef HAVE_POLL
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001145normal_return:
Bill Janssen934b16d2008-06-28 22:19:33 +00001146#endif
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001147 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1148 (when we are able to write or when there's something to read) */
1149 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001150}
1151
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001152static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1153{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001154 char *data;
1155 int len;
1156 int count;
1157 int sockstate;
1158 int err;
1159 int nonblocking;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001160
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001161 if (!PyArg_ParseTuple(args, "s#:write", &data, &count))
1162 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001163
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001164 /* just in case the blocking state of the socket has been changed */
1165 nonblocking = (self->Socket->sock_timeout >= 0.0);
1166 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1167 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001168
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001169 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1170 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1171 PyErr_SetString(PySSLErrorObject,
1172 "The write operation timed out");
1173 return NULL;
1174 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1175 PyErr_SetString(PySSLErrorObject,
1176 "Underlying socket has been closed.");
1177 return NULL;
1178 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1179 PyErr_SetString(PySSLErrorObject,
1180 "Underlying socket too large for select().");
1181 return NULL;
1182 }
1183 do {
1184 err = 0;
1185 PySSL_BEGIN_ALLOW_THREADS
1186 len = SSL_write(self->ssl, data, count);
1187 err = SSL_get_error(self->ssl, len);
1188 PySSL_END_ALLOW_THREADS
1189 if(PyErr_CheckSignals()) {
1190 return NULL;
1191 }
1192 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001193 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001194 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001195 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001196 } else {
1197 sockstate = SOCKET_OPERATION_OK;
1198 }
1199 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1200 PyErr_SetString(PySSLErrorObject,
1201 "The write operation timed out");
1202 return NULL;
1203 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1204 PyErr_SetString(PySSLErrorObject,
1205 "Underlying socket has been closed.");
1206 return NULL;
1207 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1208 break;
1209 }
1210 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1211 if (len > 0)
1212 return PyInt_FromLong(len);
1213 else
1214 return PySSL_SetError(self, len, __FILE__, __LINE__);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001215}
1216
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001217PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001218"write(s) -> len\n\
1219\n\
1220Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001221of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001222
Bill Janssen934b16d2008-06-28 22:19:33 +00001223static PyObject *PySSL_SSLpending(PySSLObject *self)
1224{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001225 int count = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001226
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001227 PySSL_BEGIN_ALLOW_THREADS
1228 count = SSL_pending(self->ssl);
1229 PySSL_END_ALLOW_THREADS
1230 if (count < 0)
1231 return PySSL_SetError(self, count, __FILE__, __LINE__);
1232 else
1233 return PyInt_FromLong(count);
Bill Janssen934b16d2008-06-28 22:19:33 +00001234}
1235
1236PyDoc_STRVAR(PySSL_SSLpending_doc,
1237"pending() -> count\n\
1238\n\
1239Returns the number of already decrypted bytes available for read,\n\
1240pending on the connection.\n");
1241
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001242static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1243{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001244 PyObject *buf;
1245 int count = 0;
1246 int len = 1024;
1247 int sockstate;
1248 int err;
1249 int nonblocking;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001250
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001251 if (!PyArg_ParseTuple(args, "|i:read", &len))
1252 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001253
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001254 if (!(buf = PyString_FromStringAndSize((char *) 0, len)))
1255 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001256
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001257 /* just in case the blocking state of the socket has been changed */
1258 nonblocking = (self->Socket->sock_timeout >= 0.0);
1259 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1260 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001261
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001262 /* first check if there are bytes ready to be read */
1263 PySSL_BEGIN_ALLOW_THREADS
1264 count = SSL_pending(self->ssl);
1265 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001266
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001267 if (!count) {
1268 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1269 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1270 PyErr_SetString(PySSLErrorObject,
1271 "The read operation timed out");
1272 Py_DECREF(buf);
1273 return NULL;
1274 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1275 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001276 "Underlying socket too large for select().");
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001277 Py_DECREF(buf);
1278 return NULL;
1279 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1280 if (SSL_get_shutdown(self->ssl) !=
1281 SSL_RECEIVED_SHUTDOWN)
1282 {
1283 Py_DECREF(buf);
1284 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001285 "Socket closed without SSL shutdown handshake");
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001286 return NULL;
1287 } else {
1288 /* should contain a zero-length string */
1289 _PyString_Resize(&buf, 0);
1290 return buf;
1291 }
1292 }
1293 }
1294 do {
1295 err = 0;
1296 PySSL_BEGIN_ALLOW_THREADS
1297 count = SSL_read(self->ssl, PyString_AsString(buf), len);
1298 err = SSL_get_error(self->ssl, count);
1299 PySSL_END_ALLOW_THREADS
1300 if(PyErr_CheckSignals()) {
1301 Py_DECREF(buf);
1302 return NULL;
1303 }
1304 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001305 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001306 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001307 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001308 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1309 (SSL_get_shutdown(self->ssl) ==
1310 SSL_RECEIVED_SHUTDOWN))
1311 {
1312 _PyString_Resize(&buf, 0);
1313 return buf;
1314 } else {
1315 sockstate = SOCKET_OPERATION_OK;
1316 }
1317 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1318 PyErr_SetString(PySSLErrorObject,
1319 "The read operation timed out");
1320 Py_DECREF(buf);
1321 return NULL;
1322 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1323 break;
1324 }
1325 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1326 if (count <= 0) {
1327 Py_DECREF(buf);
1328 return PySSL_SetError(self, count, __FILE__, __LINE__);
1329 }
1330 if (count != len)
1331 _PyString_Resize(&buf, count);
1332 return buf;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001333}
1334
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001335PyDoc_STRVAR(PySSL_SSLread_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001336"read([len]) -> string\n\
1337\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001338Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001339
Bill Janssen934b16d2008-06-28 22:19:33 +00001340static PyObject *PySSL_SSLshutdown(PySSLObject *self)
1341{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001342 int err, ssl_err, sockstate, nonblocking;
1343 int zeros = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001344
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001345 /* Guard against closed socket */
1346 if (self->Socket->sock_fd < 0) {
1347 PyErr_SetString(PySSLErrorObject,
1348 "Underlying socket has been closed.");
1349 return NULL;
1350 }
Bill Janssen934b16d2008-06-28 22:19:33 +00001351
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001352 /* Just in case the blocking state of the socket has been changed */
1353 nonblocking = (self->Socket->sock_timeout >= 0.0);
1354 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1355 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitrou07072162010-04-23 21:07:58 +00001356
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001357 while (1) {
1358 PySSL_BEGIN_ALLOW_THREADS
1359 /* Disable read-ahead so that unwrap can work correctly.
1360 * Otherwise OpenSSL might read in too much data,
1361 * eating clear text data that happens to be
1362 * transmitted after the SSL shutdown.
1363 * Should be safe to call repeatedly everytime this
1364 * function is used and the shutdown_seen_zero != 0
1365 * condition is met.
1366 */
1367 if (self->shutdown_seen_zero)
1368 SSL_set_read_ahead(self->ssl, 0);
1369 err = SSL_shutdown(self->ssl);
1370 PySSL_END_ALLOW_THREADS
1371 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1372 if (err > 0)
1373 break;
1374 if (err == 0) {
1375 /* Don't loop endlessly; instead preserve legacy
1376 behaviour of trying SSL_shutdown() only twice.
1377 This looks necessary for OpenSSL < 0.9.8m */
1378 if (++zeros > 1)
1379 break;
1380 /* Shutdown was sent, now try receiving */
1381 self->shutdown_seen_zero = 1;
1382 continue;
1383 }
Antoine Pitrou07072162010-04-23 21:07:58 +00001384
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001385 /* Possibly retry shutdown until timeout or failure */
1386 ssl_err = SSL_get_error(self->ssl, err);
1387 if (ssl_err == SSL_ERROR_WANT_READ)
1388 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1389 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1390 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1391 else
1392 break;
1393 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1394 if (ssl_err == SSL_ERROR_WANT_READ)
1395 PyErr_SetString(PySSLErrorObject,
1396 "The read operation timed out");
1397 else
1398 PyErr_SetString(PySSLErrorObject,
1399 "The write operation timed out");
1400 return NULL;
1401 }
1402 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1403 PyErr_SetString(PySSLErrorObject,
1404 "Underlying socket too large for select().");
1405 return NULL;
1406 }
1407 else if (sockstate != SOCKET_OPERATION_OK)
1408 /* Retain the SSL error code */
1409 break;
1410 }
Bill Janssen934b16d2008-06-28 22:19:33 +00001411
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001412 if (err < 0)
1413 return PySSL_SetError(self, err, __FILE__, __LINE__);
1414 else {
1415 Py_INCREF(self->Socket);
1416 return (PyObject *) (self->Socket);
1417 }
Bill Janssen934b16d2008-06-28 22:19:33 +00001418}
1419
1420PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1421"shutdown(s) -> socket\n\
1422\n\
1423Does the SSL shutdown handshake with the remote end, and returns\n\
1424the underlying socket object.");
1425
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001426static PyMethodDef PySSLMethods[] = {
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001427 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1428 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1429 PySSL_SSLwrite_doc},
1430 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1431 PySSL_SSLread_doc},
1432 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1433 PySSL_SSLpending_doc},
1434 {"server", (PyCFunction)PySSL_server, METH_NOARGS},
1435 {"issuer", (PyCFunction)PySSL_issuer, METH_NOARGS},
1436 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1437 PySSL_peercert_doc},
1438 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1439 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1440 PySSL_SSLshutdown_doc},
1441 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001442};
1443
1444static PyObject *PySSL_getattr(PySSLObject *self, char *name)
1445{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001446 return Py_FindMethod(PySSLMethods, (PyObject *)self, name);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001447}
1448
Jeremy Hylton938ace62002-07-17 16:30:39 +00001449static PyTypeObject PySSL_Type = {
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001450 PyVarObject_HEAD_INIT(NULL, 0)
1451 "ssl.SSLContext", /*tp_name*/
1452 sizeof(PySSLObject), /*tp_basicsize*/
1453 0, /*tp_itemsize*/
1454 /* methods */
1455 (destructor)PySSL_dealloc, /*tp_dealloc*/
1456 0, /*tp_print*/
1457 (getattrfunc)PySSL_getattr, /*tp_getattr*/
1458 0, /*tp_setattr*/
1459 0, /*tp_compare*/
1460 0, /*tp_repr*/
1461 0, /*tp_as_number*/
1462 0, /*tp_as_sequence*/
1463 0, /*tp_as_mapping*/
1464 0, /*tp_hash*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001465};
1466
1467#ifdef HAVE_OPENSSL_RAND
1468
1469/* helper routines for seeding the SSL PRNG */
1470static PyObject *
1471PySSL_RAND_add(PyObject *self, PyObject *args)
1472{
1473 char *buf;
1474 int len;
1475 double entropy;
1476
1477 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001478 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001479 RAND_add(buf, len, entropy);
1480 Py_INCREF(Py_None);
1481 return Py_None;
1482}
1483
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001484PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001485"RAND_add(string, entropy)\n\
1486\n\
1487Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00001488bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001489
1490static PyObject *
1491PySSL_RAND_status(PyObject *self)
1492{
1493 return PyInt_FromLong(RAND_status());
1494}
1495
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001496PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001497"RAND_status() -> 0 or 1\n\
1498\n\
1499Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1500It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001501using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001502
1503static PyObject *
1504PySSL_RAND_egd(PyObject *self, PyObject *arg)
1505{
1506 int bytes;
1507
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001508 if (!PyString_Check(arg))
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001509 return PyErr_Format(PyExc_TypeError,
1510 "RAND_egd() expected string, found %s",
1511 Py_TYPE(arg)->tp_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001512 bytes = RAND_egd(PyString_AS_STRING(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001513 if (bytes == -1) {
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001514 PyErr_SetString(PySSLErrorObject,
1515 "EGD connection failed or EGD did not return "
1516 "enough data to seed the PRNG");
1517 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001518 }
1519 return PyInt_FromLong(bytes);
1520}
1521
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001522PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001523"RAND_egd(path) -> bytes\n\
1524\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00001525Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1526Returns number of bytes read. Raises SSLError if connection to EGD\n\
1527fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001528
1529#endif
1530
1531/* List of functions exported by this module. */
1532
1533static PyMethodDef PySSL_methods[] = {
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001534 {"sslwrap", PySSL_sslwrap,
1535 METH_VARARGS, ssl_doc},
1536 {"_test_decode_cert", PySSL_test_decode_certificate,
1537 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001538#ifdef HAVE_OPENSSL_RAND
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001539 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1540 PySSL_RAND_add_doc},
1541 {"RAND_egd", PySSL_RAND_egd, METH_O,
1542 PySSL_RAND_egd_doc},
1543 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1544 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001545#endif
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001546 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001547};
1548
1549
Bill Janssen98d19da2007-09-10 21:51:02 +00001550#ifdef WITH_THREAD
1551
1552/* an implementation of OpenSSL threading operations in terms
1553 of the Python C thread library */
1554
1555static PyThread_type_lock *_ssl_locks = NULL;
1556
1557static unsigned long _ssl_thread_id_function (void) {
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001558 return PyThread_get_thread_ident();
Bill Janssen98d19da2007-09-10 21:51:02 +00001559}
1560
1561static void _ssl_thread_locking_function (int mode, int n, const char *file, int line) {
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001562 /* this function is needed to perform locking on shared data
1563 structures. (Note that OpenSSL uses a number of global data
1564 structures that will be implicitly shared whenever multiple threads
1565 use OpenSSL.) Multi-threaded applications will crash at random if
1566 it is not set.
Bill Janssen98d19da2007-09-10 21:51:02 +00001567
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001568 locking_function() must be able to handle up to CRYPTO_num_locks()
1569 different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and
1570 releases it otherwise.
Bill Janssen98d19da2007-09-10 21:51:02 +00001571
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001572 file and line are the file number of the function setting the
1573 lock. They can be useful for debugging.
1574 */
Bill Janssen98d19da2007-09-10 21:51:02 +00001575
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001576 if ((_ssl_locks == NULL) ||
1577 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1578 return;
Bill Janssen98d19da2007-09-10 21:51:02 +00001579
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001580 if (mode & CRYPTO_LOCK) {
1581 PyThread_acquire_lock(_ssl_locks[n], 1);
1582 } else {
1583 PyThread_release_lock(_ssl_locks[n]);
1584 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001585}
1586
1587static int _setup_ssl_threads(void) {
1588
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001589 unsigned int i;
Bill Janssen98d19da2007-09-10 21:51:02 +00001590
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001591 if (_ssl_locks == NULL) {
1592 _ssl_locks_count = CRYPTO_num_locks();
1593 _ssl_locks = (PyThread_type_lock *)
1594 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1595 if (_ssl_locks == NULL)
1596 return 0;
1597 memset(_ssl_locks, 0, sizeof(PyThread_type_lock) * _ssl_locks_count);
1598 for (i = 0; i < _ssl_locks_count; i++) {
1599 _ssl_locks[i] = PyThread_allocate_lock();
1600 if (_ssl_locks[i] == NULL) {
1601 unsigned int j;
1602 for (j = 0; j < i; j++) {
1603 PyThread_free_lock(_ssl_locks[j]);
1604 }
1605 free(_ssl_locks);
1606 return 0;
1607 }
1608 }
1609 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1610 CRYPTO_set_id_callback(_ssl_thread_id_function);
1611 }
1612 return 1;
Bill Janssen98d19da2007-09-10 21:51:02 +00001613}
1614
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001615#endif /* def HAVE_THREAD */
Bill Janssen98d19da2007-09-10 21:51:02 +00001616
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001617PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001618"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001619for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001620
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001621PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001622init_ssl(void)
1623{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001624 PyObject *m, *d;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001625
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001626 Py_TYPE(&PySSL_Type) = &PyType_Type;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001627
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001628 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
1629 if (m == NULL)
1630 return;
1631 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001632
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001633 /* Load _socket module and its C API */
1634 if (PySocketModule_ImportModuleAndAPI())
1635 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001636
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001637 /* Init OpenSSL */
1638 SSL_load_error_strings();
1639 SSL_library_init();
Bill Janssen98d19da2007-09-10 21:51:02 +00001640#ifdef WITH_THREAD
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001641 /* note that this will start threading if not already started */
1642 if (!_setup_ssl_threads()) {
1643 return;
1644 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001645#endif
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001646 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001647
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001648 /* Add symbols to module dict */
1649 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
1650 PySocketModule.error,
1651 NULL);
1652 if (PySSLErrorObject == NULL)
1653 return;
1654 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
1655 return;
1656 if (PyDict_SetItemString(d, "SSLType",
1657 (PyObject *)&PySSL_Type) != 0)
1658 return;
1659 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
1660 PY_SSL_ERROR_ZERO_RETURN);
1661 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
1662 PY_SSL_ERROR_WANT_READ);
1663 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
1664 PY_SSL_ERROR_WANT_WRITE);
1665 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
1666 PY_SSL_ERROR_WANT_X509_LOOKUP);
1667 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
1668 PY_SSL_ERROR_SYSCALL);
1669 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
1670 PY_SSL_ERROR_SSL);
1671 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1672 PY_SSL_ERROR_WANT_CONNECT);
1673 /* non ssl.h errorcodes */
1674 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1675 PY_SSL_ERROR_EOF);
1676 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1677 PY_SSL_ERROR_INVALID_ERROR_CODE);
1678 /* cert requirements */
1679 PyModule_AddIntConstant(m, "CERT_NONE",
1680 PY_SSL_CERT_NONE);
1681 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1682 PY_SSL_CERT_OPTIONAL);
1683 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1684 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001685
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001686 /* protocol versions */
1687 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1688 PY_SSL_VERSION_SSL2);
1689 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1690 PY_SSL_VERSION_SSL3);
1691 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1692 PY_SSL_VERSION_SSL23);
1693 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1694 PY_SSL_VERSION_TLS1);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001695}