blob: 46f71e858e2696c22d3547a9286cb3e4cc1037eb [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 */
Antoine Pitroud358e052012-01-27 09:42:45 +0100360 SSL_CTX_set_options(self->ctx,
361 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Bill Janssen98d19da2007-09-10 21:51:02 +0000362
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000363 verification_mode = SSL_VERIFY_NONE;
364 if (certreq == PY_SSL_CERT_OPTIONAL)
365 verification_mode = SSL_VERIFY_PEER;
366 else if (certreq == PY_SSL_CERT_REQUIRED)
367 verification_mode = (SSL_VERIFY_PEER |
368 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
369 SSL_CTX_set_verify(self->ctx, verification_mode,
370 NULL); /* set verify lvl */
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000371
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000372 PySSL_BEGIN_ALLOW_THREADS
373 self->ssl = SSL_new(self->ctx); /* New ssl struct */
374 PySSL_END_ALLOW_THREADS
375 SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */
Antoine Pitrou206685b2010-04-09 20:44:09 +0000376#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000377 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou206685b2010-04-09 20:44:09 +0000378#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000379
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000380 /* If the socket is in non-blocking mode or timeout mode, set the BIO
381 * to non-blocking mode (blocking is the default)
382 */
383 if (Sock->sock_timeout >= 0.0) {
384 /* Set both the read and write BIO's to non-blocking mode */
385 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
386 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
387 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000388
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000389 PySSL_BEGIN_ALLOW_THREADS
390 if (socket_type == PY_SSL_CLIENT)
391 SSL_set_connect_state(self->ssl);
392 else
393 SSL_set_accept_state(self->ssl);
394 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000395
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000396 self->Socket = Sock;
397 Py_INCREF(self->Socket);
398 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000399 fail:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000400 if (errstr)
401 PyErr_SetString(PySSLErrorObject, errstr);
402 Py_DECREF(self);
403 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000404}
405
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000406static PyObject *
Guido van Rossum780b80d2007-08-27 18:42:23 +0000407PySSL_sslwrap(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000408{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000409 PySocketSockObject *Sock;
410 int server_side = 0;
411 int verification_mode = PY_SSL_CERT_NONE;
412 int protocol = PY_SSL_VERSION_SSL23;
413 char *key_file = NULL;
414 char *cert_file = NULL;
415 char *cacerts_file = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000416
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000417 if (!PyArg_ParseTuple(args, "O!i|zziiz:sslwrap",
418 PySocketModule.Sock_Type,
419 &Sock,
420 &server_side,
421 &key_file, &cert_file,
422 &verification_mode, &protocol,
423 &cacerts_file))
424 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000425
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000426 /*
427 fprintf(stderr,
428 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
429 "protocol %d, certs %p\n",
430 server_side, key_file, cert_file, verification_mode,
431 protocol, cacerts_file);
432 */
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000433
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000434 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
435 server_side, verification_mode,
436 protocol, cacerts_file);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000437}
438
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000439PyDoc_STRVAR(ssl_doc,
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000440"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
441" cacertsfile]) -> sslobject");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000442
443/* SSL object methods */
444
Bill Janssen934b16d2008-06-28 22:19:33 +0000445static PyObject *PySSL_SSLdo_handshake(PySSLObject *self)
446{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000447 int ret;
448 int err;
449 int sockstate, nonblocking;
Antoine Pitrouc689d962010-04-24 20:13:37 +0000450
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000451 /* just in case the blocking state of the socket has been changed */
452 nonblocking = (self->Socket->sock_timeout >= 0.0);
453 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
454 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +0000455
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000456 /* Actually negotiate SSL connection */
457 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
458 sockstate = 0;
459 do {
460 PySSL_BEGIN_ALLOW_THREADS
461 ret = SSL_do_handshake(self->ssl);
462 err = SSL_get_error(self->ssl, ret);
463 PySSL_END_ALLOW_THREADS
464 if(PyErr_CheckSignals()) {
465 return NULL;
466 }
467 if (err == SSL_ERROR_WANT_READ) {
468 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
469 } else if (err == SSL_ERROR_WANT_WRITE) {
470 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
471 } else {
472 sockstate = SOCKET_OPERATION_OK;
473 }
474 if (sockstate == SOCKET_HAS_TIMED_OUT) {
475 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou96125cf2010-05-12 14:05:34 +0000476 ERRSTR("The handshake operation timed out"));
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000477 return NULL;
478 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
479 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou96125cf2010-05-12 14:05:34 +0000480 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000481 return NULL;
482 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
483 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou96125cf2010-05-12 14:05:34 +0000484 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000485 return NULL;
486 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
487 break;
488 }
489 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
490 if (ret < 1)
491 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen934b16d2008-06-28 22:19:33 +0000492
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000493 if (self->peer_cert)
494 X509_free (self->peer_cert);
495 PySSL_BEGIN_ALLOW_THREADS
496 if ((self->peer_cert = SSL_get_peer_certificate(self->ssl))) {
497 X509_NAME_oneline(X509_get_subject_name(self->peer_cert),
498 self->server, X509_NAME_MAXLEN);
499 X509_NAME_oneline(X509_get_issuer_name(self->peer_cert),
500 self->issuer, X509_NAME_MAXLEN);
501 }
502 PySSL_END_ALLOW_THREADS
Bill Janssen934b16d2008-06-28 22:19:33 +0000503
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000504 Py_INCREF(Py_None);
505 return Py_None;
Bill Janssen934b16d2008-06-28 22:19:33 +0000506}
507
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000508static PyObject *
509PySSL_server(PySSLObject *self)
510{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000511 return PyString_FromString(self->server);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000512}
513
514static PyObject *
515PySSL_issuer(PySSLObject *self)
516{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000517 return PyString_FromString(self->issuer);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000518}
519
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000520static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000521_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000522
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000523 char namebuf[X509_NAME_MAXLEN];
524 int buflen;
525 PyObject *name_obj;
526 PyObject *value_obj;
527 PyObject *attr;
528 unsigned char *valuebuf = NULL;
Guido van Rossum780b80d2007-08-27 18:42:23 +0000529
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000530 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
531 if (buflen < 0) {
532 _setSSLError(NULL, 0, __FILE__, __LINE__);
533 goto fail;
534 }
535 name_obj = PyString_FromStringAndSize(namebuf, buflen);
536 if (name_obj == NULL)
537 goto fail;
538
539 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
540 if (buflen < 0) {
541 _setSSLError(NULL, 0, __FILE__, __LINE__);
542 Py_DECREF(name_obj);
543 goto fail;
544 }
545 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou96125cf2010-05-12 14:05:34 +0000546 buflen, "strict");
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000547 OPENSSL_free(valuebuf);
548 if (value_obj == NULL) {
549 Py_DECREF(name_obj);
550 goto fail;
551 }
552 attr = PyTuple_New(2);
553 if (attr == NULL) {
554 Py_DECREF(name_obj);
555 Py_DECREF(value_obj);
556 goto fail;
557 }
558 PyTuple_SET_ITEM(attr, 0, name_obj);
559 PyTuple_SET_ITEM(attr, 1, value_obj);
560 return attr;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000561
Bill Janssen98d19da2007-09-10 21:51:02 +0000562 fail:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000563 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000564}
565
566static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000567_create_tuple_for_X509_NAME (X509_NAME *xname)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000568{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000569 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
570 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
571 PyObject *rdnt;
572 PyObject *attr = NULL; /* tuple to hold an attribute */
573 int entry_count = X509_NAME_entry_count(xname);
574 X509_NAME_ENTRY *entry;
575 ASN1_OBJECT *name;
576 ASN1_STRING *value;
577 int index_counter;
578 int rdn_level = -1;
579 int retcode;
Bill Janssen98d19da2007-09-10 21:51:02 +0000580
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000581 dn = PyList_New(0);
582 if (dn == NULL)
583 return NULL;
584 /* now create another tuple to hold the top-level RDN */
585 rdn = PyList_New(0);
586 if (rdn == NULL)
587 goto fail0;
Bill Janssen98d19da2007-09-10 21:51:02 +0000588
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000589 for (index_counter = 0;
590 index_counter < entry_count;
591 index_counter++)
592 {
593 entry = X509_NAME_get_entry(xname, index_counter);
Bill Janssen98d19da2007-09-10 21:51:02 +0000594
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000595 /* check to see if we've gotten to a new RDN */
596 if (rdn_level >= 0) {
597 if (rdn_level != entry->set) {
598 /* yes, new RDN */
599 /* add old RDN to DN */
600 rdnt = PyList_AsTuple(rdn);
601 Py_DECREF(rdn);
602 if (rdnt == NULL)
603 goto fail0;
604 retcode = PyList_Append(dn, rdnt);
605 Py_DECREF(rdnt);
606 if (retcode < 0)
607 goto fail0;
608 /* create new RDN */
609 rdn = PyList_New(0);
610 if (rdn == NULL)
611 goto fail0;
612 }
613 }
614 rdn_level = entry->set;
Bill Janssen98d19da2007-09-10 21:51:02 +0000615
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000616 /* now add this attribute to the current RDN */
617 name = X509_NAME_ENTRY_get_object(entry);
618 value = X509_NAME_ENTRY_get_data(entry);
619 attr = _create_tuple_for_attribute(name, value);
620 /*
621 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
622 entry->set,
623 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
624 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
625 */
626 if (attr == NULL)
627 goto fail1;
628 retcode = PyList_Append(rdn, attr);
629 Py_DECREF(attr);
630 if (retcode < 0)
631 goto fail1;
632 }
633 /* now, there's typically a dangling RDN */
634 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
635 rdnt = PyList_AsTuple(rdn);
636 Py_DECREF(rdn);
637 if (rdnt == NULL)
638 goto fail0;
639 retcode = PyList_Append(dn, rdnt);
640 Py_DECREF(rdnt);
641 if (retcode < 0)
642 goto fail0;
643 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000644
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000645 /* convert list to tuple */
646 rdnt = PyList_AsTuple(dn);
647 Py_DECREF(dn);
648 if (rdnt == NULL)
649 return NULL;
650 return rdnt;
Bill Janssen98d19da2007-09-10 21:51:02 +0000651
652 fail1:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000653 Py_XDECREF(rdn);
Bill Janssen98d19da2007-09-10 21:51:02 +0000654
655 fail0:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000656 Py_XDECREF(dn);
657 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000658}
659
660static PyObject *
661_get_peer_alt_names (X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000662
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000663 /* this code follows the procedure outlined in
664 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
665 function to extract the STACK_OF(GENERAL_NAME),
666 then iterates through the stack to add the
667 names. */
Bill Janssen98d19da2007-09-10 21:51:02 +0000668
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000669 int i, j;
670 PyObject *peer_alt_names = Py_None;
671 PyObject *v, *t;
672 X509_EXTENSION *ext = NULL;
673 GENERAL_NAMES *names = NULL;
674 GENERAL_NAME *name;
675 X509V3_EXT_METHOD *method;
676 BIO *biobuf = NULL;
677 char buf[2048];
678 char *vptr;
679 int len;
680 const unsigned char *p;
Bill Janssen98d19da2007-09-10 21:51:02 +0000681
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000682 if (certificate == NULL)
683 return peer_alt_names;
Bill Janssen98d19da2007-09-10 21:51:02 +0000684
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000685 /* get a memory buffer */
686 biobuf = BIO_new(BIO_s_mem());
Bill Janssen98d19da2007-09-10 21:51:02 +0000687
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000688 i = 0;
689 while ((i = X509_get_ext_by_NID(
690 certificate, NID_subject_alt_name, i)) >= 0) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000691
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000692 if (peer_alt_names == Py_None) {
693 peer_alt_names = PyList_New(0);
694 if (peer_alt_names == NULL)
695 goto fail;
696 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000697
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000698 /* now decode the altName */
699 ext = X509_get_ext(certificate, i);
700 if(!(method = X509V3_EXT_get(ext))) {
701 PyErr_SetString(PySSLErrorObject,
702 ERRSTR("No method for internalizing subjectAltName!"));
703 goto fail;
704 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000705
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000706 p = ext->value->data;
707 if (method->it)
708 names = (GENERAL_NAMES*) (ASN1_item_d2i(NULL,
709 &p,
710 ext->value->length,
711 ASN1_ITEM_ptr(method->it)));
712 else
713 names = (GENERAL_NAMES*) (method->d2i(NULL,
714 &p,
715 ext->value->length));
Bill Janssen98d19da2007-09-10 21:51:02 +0000716
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000717 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000718
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000719 /* get a rendering of each name in the set of names */
Bill Janssen98d19da2007-09-10 21:51:02 +0000720
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000721 name = sk_GENERAL_NAME_value(names, j);
722 if (name->type == GEN_DIRNAME) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000723
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000724 /* we special-case DirName as a tuple of tuples of attributes */
Bill Janssen98d19da2007-09-10 21:51:02 +0000725
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000726 t = PyTuple_New(2);
727 if (t == NULL) {
728 goto fail;
729 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000730
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000731 v = PyString_FromString("DirName");
732 if (v == NULL) {
733 Py_DECREF(t);
734 goto fail;
735 }
736 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen98d19da2007-09-10 21:51:02 +0000737
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000738 v = _create_tuple_for_X509_NAME (name->d.dirn);
739 if (v == NULL) {
740 Py_DECREF(t);
741 goto fail;
742 }
743 PyTuple_SET_ITEM(t, 1, v);
Bill Janssen98d19da2007-09-10 21:51:02 +0000744
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000745 } else {
Bill Janssen98d19da2007-09-10 21:51:02 +0000746
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000747 /* for everything else, we use the OpenSSL print form */
748
749 (void) BIO_reset(biobuf);
750 GENERAL_NAME_print(biobuf, name);
751 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
752 if (len < 0) {
753 _setSSLError(NULL, 0, __FILE__, __LINE__);
754 goto fail;
755 }
756 vptr = strchr(buf, ':');
757 if (vptr == NULL)
758 goto fail;
759 t = PyTuple_New(2);
760 if (t == NULL)
761 goto fail;
762 v = PyString_FromStringAndSize(buf, (vptr - buf));
763 if (v == NULL) {
764 Py_DECREF(t);
765 goto fail;
766 }
767 PyTuple_SET_ITEM(t, 0, v);
768 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
769 if (v == NULL) {
770 Py_DECREF(t);
771 goto fail;
772 }
773 PyTuple_SET_ITEM(t, 1, v);
774 }
775
776 /* and add that rendering to the list */
777
778 if (PyList_Append(peer_alt_names, t) < 0) {
779 Py_DECREF(t);
780 goto fail;
781 }
782 Py_DECREF(t);
783 }
784 }
785 BIO_free(biobuf);
786 if (peer_alt_names != Py_None) {
787 v = PyList_AsTuple(peer_alt_names);
788 Py_DECREF(peer_alt_names);
789 return v;
790 } else {
791 return peer_alt_names;
792 }
793
Bill Janssen98d19da2007-09-10 21:51:02 +0000794
795 fail:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000796 if (biobuf != NULL)
797 BIO_free(biobuf);
Bill Janssen98d19da2007-09-10 21:51:02 +0000798
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000799 if (peer_alt_names != Py_None) {
800 Py_XDECREF(peer_alt_names);
801 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000802
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000803 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000804}
805
806static PyObject *
807_decode_certificate (X509 *certificate, int verbose) {
808
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000809 PyObject *retval = NULL;
810 BIO *biobuf = NULL;
811 PyObject *peer;
812 PyObject *peer_alt_names = NULL;
813 PyObject *issuer;
814 PyObject *version;
815 PyObject *sn_obj;
816 ASN1_INTEGER *serialNumber;
817 char buf[2048];
818 int len;
819 ASN1_TIME *notBefore, *notAfter;
820 PyObject *pnotBefore, *pnotAfter;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000821
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000822 retval = PyDict_New();
823 if (retval == NULL)
824 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000825
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000826 peer = _create_tuple_for_X509_NAME(
827 X509_get_subject_name(certificate));
828 if (peer == NULL)
829 goto fail0;
830 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
831 Py_DECREF(peer);
832 goto fail0;
833 }
834 Py_DECREF(peer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000835
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000836 if (verbose) {
837 issuer = _create_tuple_for_X509_NAME(
838 X509_get_issuer_name(certificate));
839 if (issuer == NULL)
840 goto fail0;
841 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
842 Py_DECREF(issuer);
843 goto fail0;
844 }
845 Py_DECREF(issuer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000846
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000847 version = PyInt_FromLong(X509_get_version(certificate) + 1);
848 if (PyDict_SetItemString(retval, "version", version) < 0) {
849 Py_DECREF(version);
850 goto fail0;
851 }
852 Py_DECREF(version);
853 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000854
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000855 /* get a memory buffer */
856 biobuf = BIO_new(BIO_s_mem());
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000857
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000858 if (verbose) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000859
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000860 (void) BIO_reset(biobuf);
861 serialNumber = X509_get_serialNumber(certificate);
862 /* should not exceed 20 octets, 160 bits, so buf is big enough */
863 i2a_ASN1_INTEGER(biobuf, serialNumber);
864 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
865 if (len < 0) {
866 _setSSLError(NULL, 0, __FILE__, __LINE__);
867 goto fail1;
868 }
869 sn_obj = PyString_FromStringAndSize(buf, len);
870 if (sn_obj == NULL)
871 goto fail1;
872 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
873 Py_DECREF(sn_obj);
874 goto fail1;
875 }
876 Py_DECREF(sn_obj);
Bill Janssen98d19da2007-09-10 21:51:02 +0000877
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000878 (void) BIO_reset(biobuf);
879 notBefore = X509_get_notBefore(certificate);
880 ASN1_TIME_print(biobuf, notBefore);
881 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
882 if (len < 0) {
883 _setSSLError(NULL, 0, __FILE__, __LINE__);
884 goto fail1;
885 }
886 pnotBefore = PyString_FromStringAndSize(buf, len);
887 if (pnotBefore == NULL)
888 goto fail1;
889 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
890 Py_DECREF(pnotBefore);
891 goto fail1;
892 }
893 Py_DECREF(pnotBefore);
894 }
895
896 (void) BIO_reset(biobuf);
897 notAfter = X509_get_notAfter(certificate);
898 ASN1_TIME_print(biobuf, notAfter);
899 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
900 if (len < 0) {
901 _setSSLError(NULL, 0, __FILE__, __LINE__);
902 goto fail1;
903 }
904 pnotAfter = PyString_FromStringAndSize(buf, len);
905 if (pnotAfter == NULL)
906 goto fail1;
907 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
908 Py_DECREF(pnotAfter);
909 goto fail1;
910 }
911 Py_DECREF(pnotAfter);
912
913 /* Now look for subjectAltName */
914
915 peer_alt_names = _get_peer_alt_names(certificate);
916 if (peer_alt_names == NULL)
917 goto fail1;
918 else if (peer_alt_names != Py_None) {
919 if (PyDict_SetItemString(retval, "subjectAltName",
920 peer_alt_names) < 0) {
921 Py_DECREF(peer_alt_names);
922 goto fail1;
923 }
924 Py_DECREF(peer_alt_names);
925 }
926
927 BIO_free(biobuf);
928 return retval;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000929
930 fail1:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000931 if (biobuf != NULL)
932 BIO_free(biobuf);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000933 fail0:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000934 Py_XDECREF(retval);
935 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000936}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000937
Bill Janssen98d19da2007-09-10 21:51:02 +0000938
939static PyObject *
940PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
941
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000942 PyObject *retval = NULL;
943 char *filename = NULL;
944 X509 *x=NULL;
945 BIO *cert;
946 int verbose = 1;
Bill Janssen98d19da2007-09-10 21:51:02 +0000947
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000948 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", &filename, &verbose))
949 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000950
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000951 if ((cert=BIO_new(BIO_s_file())) == NULL) {
952 PyErr_SetString(PySSLErrorObject, "Can't malloc memory to read file");
953 goto fail0;
954 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000955
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000956 if (BIO_read_filename(cert,filename) <= 0) {
957 PyErr_SetString(PySSLErrorObject, "Can't open file");
958 goto fail0;
959 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000960
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000961 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
962 if (x == NULL) {
963 PyErr_SetString(PySSLErrorObject, "Error decoding PEM-encoded file");
964 goto fail0;
965 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000966
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000967 retval = _decode_certificate(x, verbose);
Mark Dickinsonc1ef2fa2010-08-03 18:50:32 +0000968 X509_free(x);
Bill Janssen98d19da2007-09-10 21:51:02 +0000969
970 fail0:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000971
972 if (cert != NULL) BIO_free(cert);
973 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +0000974}
975
976
977static PyObject *
978PySSL_peercert(PySSLObject *self, PyObject *args)
979{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000980 PyObject *retval = NULL;
981 int len;
982 int verification;
983 PyObject *binary_mode = Py_None;
Bill Janssen98d19da2007-09-10 21:51:02 +0000984
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000985 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
986 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000987
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000988 if (!self->peer_cert)
989 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +0000990
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000991 if (PyObject_IsTrue(binary_mode)) {
992 /* return cert in DER-encoded format */
Bill Janssen98d19da2007-09-10 21:51:02 +0000993
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000994 unsigned char *bytes_buf = NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000995
Antoine Pitrou7fd622a2010-05-05 15:59:19 +0000996 bytes_buf = NULL;
997 len = i2d_X509(self->peer_cert, &bytes_buf);
998 if (len < 0) {
999 PySSL_SetError(self, len, __FILE__, __LINE__);
1000 return NULL;
1001 }
1002 retval = PyString_FromStringAndSize((const char *) bytes_buf, len);
1003 OPENSSL_free(bytes_buf);
1004 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +00001005
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001006 } else {
Bill Janssen98d19da2007-09-10 21:51:02 +00001007
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001008 verification = SSL_CTX_get_verify_mode(self->ctx);
1009 if ((verification & SSL_VERIFY_PEER) == 0)
1010 return PyDict_New();
1011 else
1012 return _decode_certificate (self->peer_cert, 0);
1013 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001014}
1015
1016PyDoc_STRVAR(PySSL_peercert_doc,
1017"peer_certificate([der=False]) -> certificate\n\
1018\n\
1019Returns the certificate for the peer. If no certificate was provided,\n\
1020returns None. If a certificate was provided, but not validated, returns\n\
1021an empty dictionary. Otherwise returns a dict containing information\n\
1022about the peer certificate.\n\
1023\n\
1024If the optional argument is True, returns a DER-encoded copy of the\n\
1025peer certificate, or None if no certificate was provided. This will\n\
1026return the certificate even if it wasn't validated.");
1027
1028static PyObject *PySSL_cipher (PySSLObject *self) {
1029
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001030 PyObject *retval, *v;
1031 SSL_CIPHER *current;
1032 char *cipher_name;
1033 char *cipher_protocol;
Bill Janssen98d19da2007-09-10 21:51:02 +00001034
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001035 if (self->ssl == NULL)
1036 return Py_None;
1037 current = SSL_get_current_cipher(self->ssl);
1038 if (current == NULL)
1039 return Py_None;
Bill Janssen98d19da2007-09-10 21:51:02 +00001040
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001041 retval = PyTuple_New(3);
1042 if (retval == NULL)
1043 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001044
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001045 cipher_name = (char *) SSL_CIPHER_get_name(current);
1046 if (cipher_name == NULL) {
1047 PyTuple_SET_ITEM(retval, 0, Py_None);
1048 } else {
1049 v = PyString_FromString(cipher_name);
1050 if (v == NULL)
1051 goto fail0;
1052 PyTuple_SET_ITEM(retval, 0, v);
1053 }
1054 cipher_protocol = SSL_CIPHER_get_version(current);
1055 if (cipher_protocol == NULL) {
1056 PyTuple_SET_ITEM(retval, 1, Py_None);
1057 } else {
1058 v = PyString_FromString(cipher_protocol);
1059 if (v == NULL)
1060 goto fail0;
1061 PyTuple_SET_ITEM(retval, 1, v);
1062 }
1063 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1064 if (v == NULL)
1065 goto fail0;
1066 PyTuple_SET_ITEM(retval, 2, v);
1067 return retval;
1068
Bill Janssen98d19da2007-09-10 21:51:02 +00001069 fail0:
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001070 Py_DECREF(retval);
1071 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001072}
1073
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001074static void PySSL_dealloc(PySSLObject *self)
1075{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001076 if (self->peer_cert) /* Possible not to have one? */
1077 X509_free (self->peer_cert);
1078 if (self->ssl)
1079 SSL_free(self->ssl);
1080 if (self->ctx)
1081 SSL_CTX_free(self->ctx);
1082 Py_XDECREF(self->Socket);
1083 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001084}
1085
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001086/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001087 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001088 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001089 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001090
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001091static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001092check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001093{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001094 fd_set fds;
1095 struct timeval tv;
1096 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001097
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001098 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1099 if (s->sock_timeout < 0.0)
1100 return SOCKET_IS_BLOCKING;
1101 else if (s->sock_timeout == 0.0)
1102 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001103
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001104 /* Guard against closed socket */
1105 if (s->sock_fd < 0)
1106 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001107
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001108 /* Prefer poll, if available, since you can poll() any fd
1109 * which can't be done with select(). */
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001110#ifdef HAVE_POLL
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001111 {
1112 struct pollfd pollfd;
1113 int timeout;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001114
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001115 pollfd.fd = s->sock_fd;
1116 pollfd.events = writing ? POLLOUT : POLLIN;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001117
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001118 /* s->sock_timeout is in seconds, timeout in ms */
1119 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1120 PySSL_BEGIN_ALLOW_THREADS
1121 rc = poll(&pollfd, 1, timeout);
1122 PySSL_END_ALLOW_THREADS
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001123
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001124 goto normal_return;
1125 }
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001126#endif
1127
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001128 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001129#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001130 if (s->sock_fd >= FD_SETSIZE)
1131 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001132#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001133
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001134 /* Construct the arguments to select */
1135 tv.tv_sec = (int)s->sock_timeout;
1136 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1137 FD_ZERO(&fds);
1138 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001139
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001140 /* See if the socket is ready */
1141 PySSL_BEGIN_ALLOW_THREADS
1142 if (writing)
1143 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1144 else
1145 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1146 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001147
Bill Janssen934b16d2008-06-28 22:19:33 +00001148#ifdef HAVE_POLL
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001149normal_return:
Bill Janssen934b16d2008-06-28 22:19:33 +00001150#endif
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001151 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1152 (when we are able to write or when there's something to read) */
1153 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001154}
1155
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001156static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1157{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001158 char *data;
1159 int len;
1160 int count;
1161 int sockstate;
1162 int err;
1163 int nonblocking;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001164
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001165 if (!PyArg_ParseTuple(args, "s#:write", &data, &count))
1166 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001167
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001168 /* just in case the blocking state of the socket has been changed */
1169 nonblocking = (self->Socket->sock_timeout >= 0.0);
1170 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1171 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001172
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001173 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1174 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1175 PyErr_SetString(PySSLErrorObject,
1176 "The write operation timed out");
1177 return NULL;
1178 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1179 PyErr_SetString(PySSLErrorObject,
1180 "Underlying socket has been closed.");
1181 return NULL;
1182 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1183 PyErr_SetString(PySSLErrorObject,
1184 "Underlying socket too large for select().");
1185 return NULL;
1186 }
1187 do {
1188 err = 0;
1189 PySSL_BEGIN_ALLOW_THREADS
1190 len = SSL_write(self->ssl, data, count);
1191 err = SSL_get_error(self->ssl, len);
1192 PySSL_END_ALLOW_THREADS
1193 if(PyErr_CheckSignals()) {
1194 return NULL;
1195 }
1196 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001197 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001198 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001199 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001200 } else {
1201 sockstate = SOCKET_OPERATION_OK;
1202 }
1203 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1204 PyErr_SetString(PySSLErrorObject,
1205 "The write operation timed out");
1206 return NULL;
1207 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1208 PyErr_SetString(PySSLErrorObject,
1209 "Underlying socket has been closed.");
1210 return NULL;
1211 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1212 break;
1213 }
1214 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1215 if (len > 0)
1216 return PyInt_FromLong(len);
1217 else
1218 return PySSL_SetError(self, len, __FILE__, __LINE__);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001219}
1220
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001221PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001222"write(s) -> len\n\
1223\n\
1224Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001225of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001226
Bill Janssen934b16d2008-06-28 22:19:33 +00001227static PyObject *PySSL_SSLpending(PySSLObject *self)
1228{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001229 int count = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001230
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001231 PySSL_BEGIN_ALLOW_THREADS
1232 count = SSL_pending(self->ssl);
1233 PySSL_END_ALLOW_THREADS
1234 if (count < 0)
1235 return PySSL_SetError(self, count, __FILE__, __LINE__);
1236 else
1237 return PyInt_FromLong(count);
Bill Janssen934b16d2008-06-28 22:19:33 +00001238}
1239
1240PyDoc_STRVAR(PySSL_SSLpending_doc,
1241"pending() -> count\n\
1242\n\
1243Returns the number of already decrypted bytes available for read,\n\
1244pending on the connection.\n");
1245
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001246static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1247{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001248 PyObject *buf;
1249 int count = 0;
1250 int len = 1024;
1251 int sockstate;
1252 int err;
1253 int nonblocking;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001254
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001255 if (!PyArg_ParseTuple(args, "|i:read", &len))
1256 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001257
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001258 if (!(buf = PyString_FromStringAndSize((char *) 0, len)))
1259 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001260
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001261 /* just in case the blocking state of the socket has been changed */
1262 nonblocking = (self->Socket->sock_timeout >= 0.0);
1263 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1264 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001265
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001266 /* first check if there are bytes ready to be read */
1267 PySSL_BEGIN_ALLOW_THREADS
1268 count = SSL_pending(self->ssl);
1269 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001270
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001271 if (!count) {
1272 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1273 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1274 PyErr_SetString(PySSLErrorObject,
1275 "The read operation timed out");
1276 Py_DECREF(buf);
1277 return NULL;
1278 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1279 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001280 "Underlying socket too large for select().");
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001281 Py_DECREF(buf);
1282 return NULL;
1283 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1284 if (SSL_get_shutdown(self->ssl) !=
1285 SSL_RECEIVED_SHUTDOWN)
1286 {
1287 Py_DECREF(buf);
1288 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001289 "Socket closed without SSL shutdown handshake");
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001290 return NULL;
1291 } else {
1292 /* should contain a zero-length string */
1293 _PyString_Resize(&buf, 0);
1294 return buf;
1295 }
1296 }
1297 }
1298 do {
1299 err = 0;
1300 PySSL_BEGIN_ALLOW_THREADS
1301 count = SSL_read(self->ssl, PyString_AsString(buf), len);
1302 err = SSL_get_error(self->ssl, count);
1303 PySSL_END_ALLOW_THREADS
1304 if(PyErr_CheckSignals()) {
1305 Py_DECREF(buf);
1306 return NULL;
1307 }
1308 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001309 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001310 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001311 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001312 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1313 (SSL_get_shutdown(self->ssl) ==
1314 SSL_RECEIVED_SHUTDOWN))
1315 {
1316 _PyString_Resize(&buf, 0);
1317 return buf;
1318 } else {
1319 sockstate = SOCKET_OPERATION_OK;
1320 }
1321 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1322 PyErr_SetString(PySSLErrorObject,
1323 "The read operation timed out");
1324 Py_DECREF(buf);
1325 return NULL;
1326 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1327 break;
1328 }
1329 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1330 if (count <= 0) {
1331 Py_DECREF(buf);
1332 return PySSL_SetError(self, count, __FILE__, __LINE__);
1333 }
1334 if (count != len)
1335 _PyString_Resize(&buf, count);
1336 return buf;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001337}
1338
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001339PyDoc_STRVAR(PySSL_SSLread_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001340"read([len]) -> string\n\
1341\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001342Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001343
Bill Janssen934b16d2008-06-28 22:19:33 +00001344static PyObject *PySSL_SSLshutdown(PySSLObject *self)
1345{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001346 int err, ssl_err, sockstate, nonblocking;
1347 int zeros = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001348
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001349 /* Guard against closed socket */
1350 if (self->Socket->sock_fd < 0) {
1351 PyErr_SetString(PySSLErrorObject,
1352 "Underlying socket has been closed.");
1353 return NULL;
1354 }
Bill Janssen934b16d2008-06-28 22:19:33 +00001355
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001356 /* Just in case the blocking state of the socket has been changed */
1357 nonblocking = (self->Socket->sock_timeout >= 0.0);
1358 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1359 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitrou07072162010-04-23 21:07:58 +00001360
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001361 while (1) {
1362 PySSL_BEGIN_ALLOW_THREADS
1363 /* Disable read-ahead so that unwrap can work correctly.
1364 * Otherwise OpenSSL might read in too much data,
1365 * eating clear text data that happens to be
1366 * transmitted after the SSL shutdown.
1367 * Should be safe to call repeatedly everytime this
1368 * function is used and the shutdown_seen_zero != 0
1369 * condition is met.
1370 */
1371 if (self->shutdown_seen_zero)
1372 SSL_set_read_ahead(self->ssl, 0);
1373 err = SSL_shutdown(self->ssl);
1374 PySSL_END_ALLOW_THREADS
1375 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1376 if (err > 0)
1377 break;
1378 if (err == 0) {
1379 /* Don't loop endlessly; instead preserve legacy
1380 behaviour of trying SSL_shutdown() only twice.
1381 This looks necessary for OpenSSL < 0.9.8m */
1382 if (++zeros > 1)
1383 break;
1384 /* Shutdown was sent, now try receiving */
1385 self->shutdown_seen_zero = 1;
1386 continue;
1387 }
Antoine Pitrou07072162010-04-23 21:07:58 +00001388
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001389 /* Possibly retry shutdown until timeout or failure */
1390 ssl_err = SSL_get_error(self->ssl, err);
1391 if (ssl_err == SSL_ERROR_WANT_READ)
1392 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1393 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1394 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1395 else
1396 break;
1397 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1398 if (ssl_err == SSL_ERROR_WANT_READ)
1399 PyErr_SetString(PySSLErrorObject,
1400 "The read operation timed out");
1401 else
1402 PyErr_SetString(PySSLErrorObject,
1403 "The write operation timed out");
1404 return NULL;
1405 }
1406 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1407 PyErr_SetString(PySSLErrorObject,
1408 "Underlying socket too large for select().");
1409 return NULL;
1410 }
1411 else if (sockstate != SOCKET_OPERATION_OK)
1412 /* Retain the SSL error code */
1413 break;
1414 }
Bill Janssen934b16d2008-06-28 22:19:33 +00001415
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001416 if (err < 0)
1417 return PySSL_SetError(self, err, __FILE__, __LINE__);
1418 else {
1419 Py_INCREF(self->Socket);
1420 return (PyObject *) (self->Socket);
1421 }
Bill Janssen934b16d2008-06-28 22:19:33 +00001422}
1423
1424PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1425"shutdown(s) -> socket\n\
1426\n\
1427Does the SSL shutdown handshake with the remote end, and returns\n\
1428the underlying socket object.");
1429
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001430static PyMethodDef PySSLMethods[] = {
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001431 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1432 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1433 PySSL_SSLwrite_doc},
1434 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1435 PySSL_SSLread_doc},
1436 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1437 PySSL_SSLpending_doc},
1438 {"server", (PyCFunction)PySSL_server, METH_NOARGS},
1439 {"issuer", (PyCFunction)PySSL_issuer, METH_NOARGS},
1440 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1441 PySSL_peercert_doc},
1442 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1443 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1444 PySSL_SSLshutdown_doc},
1445 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001446};
1447
1448static PyObject *PySSL_getattr(PySSLObject *self, char *name)
1449{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001450 return Py_FindMethod(PySSLMethods, (PyObject *)self, name);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001451}
1452
Jeremy Hylton938ace62002-07-17 16:30:39 +00001453static PyTypeObject PySSL_Type = {
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001454 PyVarObject_HEAD_INIT(NULL, 0)
1455 "ssl.SSLContext", /*tp_name*/
1456 sizeof(PySSLObject), /*tp_basicsize*/
1457 0, /*tp_itemsize*/
1458 /* methods */
1459 (destructor)PySSL_dealloc, /*tp_dealloc*/
1460 0, /*tp_print*/
1461 (getattrfunc)PySSL_getattr, /*tp_getattr*/
1462 0, /*tp_setattr*/
1463 0, /*tp_compare*/
1464 0, /*tp_repr*/
1465 0, /*tp_as_number*/
1466 0, /*tp_as_sequence*/
1467 0, /*tp_as_mapping*/
1468 0, /*tp_hash*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001469};
1470
1471#ifdef HAVE_OPENSSL_RAND
1472
1473/* helper routines for seeding the SSL PRNG */
1474static PyObject *
1475PySSL_RAND_add(PyObject *self, PyObject *args)
1476{
1477 char *buf;
1478 int len;
1479 double entropy;
1480
1481 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001482 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001483 RAND_add(buf, len, entropy);
1484 Py_INCREF(Py_None);
1485 return Py_None;
1486}
1487
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001488PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001489"RAND_add(string, entropy)\n\
1490\n\
1491Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00001492bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001493
1494static PyObject *
1495PySSL_RAND_status(PyObject *self)
1496{
1497 return PyInt_FromLong(RAND_status());
1498}
1499
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001500PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001501"RAND_status() -> 0 or 1\n\
1502\n\
1503Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1504It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001505using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001506
1507static PyObject *
1508PySSL_RAND_egd(PyObject *self, PyObject *arg)
1509{
1510 int bytes;
1511
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001512 if (!PyString_Check(arg))
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001513 return PyErr_Format(PyExc_TypeError,
1514 "RAND_egd() expected string, found %s",
1515 Py_TYPE(arg)->tp_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001516 bytes = RAND_egd(PyString_AS_STRING(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001517 if (bytes == -1) {
Antoine Pitrou96125cf2010-05-12 14:05:34 +00001518 PyErr_SetString(PySSLErrorObject,
1519 "EGD connection failed or EGD did not return "
1520 "enough data to seed the PRNG");
1521 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001522 }
1523 return PyInt_FromLong(bytes);
1524}
1525
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001526PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001527"RAND_egd(path) -> bytes\n\
1528\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00001529Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1530Returns number of bytes read. Raises SSLError if connection to EGD\n\
1531fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001532
1533#endif
1534
1535/* List of functions exported by this module. */
1536
1537static PyMethodDef PySSL_methods[] = {
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001538 {"sslwrap", PySSL_sslwrap,
1539 METH_VARARGS, ssl_doc},
1540 {"_test_decode_cert", PySSL_test_decode_certificate,
1541 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001542#ifdef HAVE_OPENSSL_RAND
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001543 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1544 PySSL_RAND_add_doc},
1545 {"RAND_egd", PySSL_RAND_egd, METH_O,
1546 PySSL_RAND_egd_doc},
1547 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1548 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001549#endif
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001550 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001551};
1552
1553
Bill Janssen98d19da2007-09-10 21:51:02 +00001554#ifdef WITH_THREAD
1555
1556/* an implementation of OpenSSL threading operations in terms
1557 of the Python C thread library */
1558
1559static PyThread_type_lock *_ssl_locks = NULL;
1560
1561static unsigned long _ssl_thread_id_function (void) {
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001562 return PyThread_get_thread_ident();
Bill Janssen98d19da2007-09-10 21:51:02 +00001563}
1564
1565static void _ssl_thread_locking_function (int mode, int n, const char *file, int line) {
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001566 /* this function is needed to perform locking on shared data
1567 structures. (Note that OpenSSL uses a number of global data
1568 structures that will be implicitly shared whenever multiple threads
1569 use OpenSSL.) Multi-threaded applications will crash at random if
1570 it is not set.
Bill Janssen98d19da2007-09-10 21:51:02 +00001571
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001572 locking_function() must be able to handle up to CRYPTO_num_locks()
1573 different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and
1574 releases it otherwise.
Bill Janssen98d19da2007-09-10 21:51:02 +00001575
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001576 file and line are the file number of the function setting the
1577 lock. They can be useful for debugging.
1578 */
Bill Janssen98d19da2007-09-10 21:51:02 +00001579
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001580 if ((_ssl_locks == NULL) ||
1581 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1582 return;
Bill Janssen98d19da2007-09-10 21:51:02 +00001583
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001584 if (mode & CRYPTO_LOCK) {
1585 PyThread_acquire_lock(_ssl_locks[n], 1);
1586 } else {
1587 PyThread_release_lock(_ssl_locks[n]);
1588 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001589}
1590
1591static int _setup_ssl_threads(void) {
1592
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001593 unsigned int i;
Bill Janssen98d19da2007-09-10 21:51:02 +00001594
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001595 if (_ssl_locks == NULL) {
1596 _ssl_locks_count = CRYPTO_num_locks();
1597 _ssl_locks = (PyThread_type_lock *)
1598 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1599 if (_ssl_locks == NULL)
1600 return 0;
1601 memset(_ssl_locks, 0, sizeof(PyThread_type_lock) * _ssl_locks_count);
1602 for (i = 0; i < _ssl_locks_count; i++) {
1603 _ssl_locks[i] = PyThread_allocate_lock();
1604 if (_ssl_locks[i] == NULL) {
1605 unsigned int j;
1606 for (j = 0; j < i; j++) {
1607 PyThread_free_lock(_ssl_locks[j]);
1608 }
1609 free(_ssl_locks);
1610 return 0;
1611 }
1612 }
1613 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1614 CRYPTO_set_id_callback(_ssl_thread_id_function);
1615 }
1616 return 1;
Bill Janssen98d19da2007-09-10 21:51:02 +00001617}
1618
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001619#endif /* def HAVE_THREAD */
Bill Janssen98d19da2007-09-10 21:51:02 +00001620
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001621PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001622"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001623for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001624
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001625PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001626init_ssl(void)
1627{
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001628 PyObject *m, *d;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001629
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001630 Py_TYPE(&PySSL_Type) = &PyType_Type;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001631
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001632 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
1633 if (m == NULL)
1634 return;
1635 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001636
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001637 /* Load _socket module and its C API */
1638 if (PySocketModule_ImportModuleAndAPI())
1639 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001640
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001641 /* Init OpenSSL */
1642 SSL_load_error_strings();
1643 SSL_library_init();
Bill Janssen98d19da2007-09-10 21:51:02 +00001644#ifdef WITH_THREAD
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001645 /* note that this will start threading if not already started */
1646 if (!_setup_ssl_threads()) {
1647 return;
1648 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001649#endif
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001650 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001651
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001652 /* Add symbols to module dict */
1653 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
1654 PySocketModule.error,
1655 NULL);
1656 if (PySSLErrorObject == NULL)
1657 return;
1658 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
1659 return;
1660 if (PyDict_SetItemString(d, "SSLType",
1661 (PyObject *)&PySSL_Type) != 0)
1662 return;
1663 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
1664 PY_SSL_ERROR_ZERO_RETURN);
1665 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
1666 PY_SSL_ERROR_WANT_READ);
1667 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
1668 PY_SSL_ERROR_WANT_WRITE);
1669 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
1670 PY_SSL_ERROR_WANT_X509_LOOKUP);
1671 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
1672 PY_SSL_ERROR_SYSCALL);
1673 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
1674 PY_SSL_ERROR_SSL);
1675 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1676 PY_SSL_ERROR_WANT_CONNECT);
1677 /* non ssl.h errorcodes */
1678 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1679 PY_SSL_ERROR_EOF);
1680 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1681 PY_SSL_ERROR_INVALID_ERROR_CODE);
1682 /* cert requirements */
1683 PyModule_AddIntConstant(m, "CERT_NONE",
1684 PY_SSL_CERT_NONE);
1685 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1686 PY_SSL_CERT_OPTIONAL);
1687 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1688 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001689
Antoine Pitrou7fd622a2010-05-05 15:59:19 +00001690 /* protocol versions */
1691 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1692 PY_SSL_VERSION_SSL2);
1693 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1694 PY_SSL_VERSION_SSL3);
1695 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1696 PY_SSL_VERSION_SSL23);
1697 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1698 PY_SSL_VERSION_TLS1);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001699}