blob: 331bffafac8ae027052f4af9b988252642dc782b [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
12
Bill Janssen6e027db2007-11-15 22:23:56 +000013 XXX what about SSL_MODE_AUTO_RETRY?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000014*/
15
16#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000017
Thomas Wouters1b7f8912007-09-19 03:06:30 +000018#ifdef WITH_THREAD
19#include "pythread.h"
20#define PySSL_BEGIN_ALLOW_THREADS { \
Bill Janssen6e027db2007-11-15 22:23:56 +000021 PyThreadState *_save = NULL; \
Thomas Wouters1b7f8912007-09-19 03:06:30 +000022 if (_ssl_locks_count>0) {_save = PyEval_SaveThread();}
23#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)};
24#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()};
25#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \
26 }
27
28#else /* no WITH_THREAD */
29
30#define PySSL_BEGIN_ALLOW_THREADS
31#define PySSL_BLOCK_THREADS
32#define PySSL_UNBLOCK_THREADS
33#define PySSL_END_ALLOW_THREADS
34
35#endif
36
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000037enum py_ssl_error {
38 /* these mirror ssl.h */
Thomas Woutersed03b412007-08-28 21:37:11 +000039 PY_SSL_ERROR_NONE,
40 PY_SSL_ERROR_SSL,
41 PY_SSL_ERROR_WANT_READ,
42 PY_SSL_ERROR_WANT_WRITE,
43 PY_SSL_ERROR_WANT_X509_LOOKUP,
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000044 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
Thomas Woutersed03b412007-08-28 21:37:11 +000045 PY_SSL_ERROR_ZERO_RETURN,
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000046 PY_SSL_ERROR_WANT_CONNECT,
Thomas Woutersed03b412007-08-28 21:37:11 +000047 /* start of non ssl.h errorcodes */
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000048 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
Bill Janssen54cc54c2007-12-14 22:08:56 +000049 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000050 PY_SSL_ERROR_INVALID_ERROR_CODE
51};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000052
Thomas Woutersed03b412007-08-28 21:37:11 +000053enum py_ssl_server_or_client {
54 PY_SSL_CLIENT,
55 PY_SSL_SERVER
56};
57
58enum py_ssl_cert_requirements {
59 PY_SSL_CERT_NONE,
60 PY_SSL_CERT_OPTIONAL,
61 PY_SSL_CERT_REQUIRED
62};
63
64enum py_ssl_version {
65 PY_SSL_VERSION_SSL2,
66 PY_SSL_VERSION_SSL3,
67 PY_SSL_VERSION_SSL23,
68 PY_SSL_VERSION_TLS1,
69};
70
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000071/* Include symbols from _socket module */
72#include "socketmodule.h"
73
Thomas Woutersed03b412007-08-28 21:37:11 +000074#if defined(HAVE_POLL_H)
Thomas Wouters0e3f5912006-08-11 14:57:12 +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"
Thomas Wouters1b7f8912007-09-19 03:06:30 +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
Thomas Wouters1b7f8912007-09-19 03:06:30 +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 {
114 PyObject_HEAD
Bill Janssen54cc54c2007-12-14 22:08:56 +0000115 PyObject *Socket; /* weakref to socket on which we're layered */
Thomas Woutersed03b412007-08-28 21:37:11 +0000116 SSL_CTX* ctx;
117 SSL* ssl;
118 X509* peer_cert;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000119
120} PySSLObject;
121
Jeremy Hylton938ace62002-07-17 16:30:39 +0000122static PyTypeObject PySSL_Type;
123static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args);
124static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000125static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000126 int writing);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000127static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args);
128static PyObject *PySSL_cipher(PySSLObject *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000129
Christian Heimes90aa7642007-12-19 02:45:37 +0000130#define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000131
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000132typedef enum {
133 SOCKET_IS_NONBLOCKING,
134 SOCKET_IS_BLOCKING,
135 SOCKET_HAS_TIMED_OUT,
136 SOCKET_HAS_BEEN_CLOSED,
Neal Norwitz389cea82006-02-13 00:35:21 +0000137 SOCKET_TOO_LARGE_FOR_SELECT,
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000138 SOCKET_OPERATION_OK
139} timeout_state;
140
Thomas Woutersed03b412007-08-28 21:37:11 +0000141/* Wrap error strings with filename and line # */
142#define STRINGIFY1(x) #x
143#define STRINGIFY2(x) STRINGIFY1(x)
144#define ERRSTR1(x,y,z) (x ":" y ": " z)
145#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
146
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000147/* XXX It might be helpful to augment the error message generated
148 below with the name of the SSL function that generated the error.
149 I expect it's obvious most of the time.
150*/
151
152static PyObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000153PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000154{
Thomas Woutersed03b412007-08-28 21:37:11 +0000155 PyObject *v;
156 char buf[2048];
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000157 char *errstr;
158 int err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000159 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000160
161 assert(ret <= 0);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000162
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000163 if (obj->ssl != NULL) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000164 err = SSL_get_error(obj->ssl, ret);
165
166 switch (err) {
167 case SSL_ERROR_ZERO_RETURN:
168 errstr = "TLS/SSL connection has been closed";
169 p = PY_SSL_ERROR_ZERO_RETURN;
170 break;
171 case SSL_ERROR_WANT_READ:
172 errstr = "The operation did not complete (read)";
173 p = PY_SSL_ERROR_WANT_READ;
174 break;
175 case SSL_ERROR_WANT_WRITE:
176 p = PY_SSL_ERROR_WANT_WRITE;
177 errstr = "The operation did not complete (write)";
178 break;
179 case SSL_ERROR_WANT_X509_LOOKUP:
180 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
181 errstr =
182 "The operation did not complete (X509 lookup)";
183 break;
184 case SSL_ERROR_WANT_CONNECT:
185 p = PY_SSL_ERROR_WANT_CONNECT;
186 errstr = "The operation did not complete (connect)";
187 break;
188 case SSL_ERROR_SYSCALL:
189 {
190 unsigned long e = ERR_get_error();
191 if (e == 0) {
Bill Janssen54cc54c2007-12-14 22:08:56 +0000192 PySocketSockObject *s
193 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
194 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000195 p = PY_SSL_ERROR_EOF;
196 errstr =
197 "EOF occurred in violation of protocol";
198 } else if (ret == -1) {
199 /* underlying BIO reported an I/O error */
Bill Janssen54cc54c2007-12-14 22:08:56 +0000200 return s->errorhandler();
Thomas Woutersed03b412007-08-28 21:37:11 +0000201 } else { /* possible? */
202 p = PY_SSL_ERROR_SYSCALL;
203 errstr = "Some I/O error occurred";
204 }
205 } else {
Jeremy Hylton4e547302002-07-02 18:25:00 +0000206 p = PY_SSL_ERROR_SYSCALL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000207 /* XXX Protected by global interpreter lock */
208 errstr = ERR_error_string(e, NULL);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000209 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000210 break;
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000211 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000212 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? */
220 errstr =
221 "A failure in the SSL library occurred";
222 }
223 break;
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000224 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000225 default:
226 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
227 errstr = "Invalid error code";
228 }
229 } else {
230 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000231 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000232 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
233 v = Py_BuildValue("(is)", p, buf);
234 if (v != NULL) {
235 PyErr_SetObject(PySSLErrorObject, v);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000236 Py_DECREF(v);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000237 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000238 return NULL;
239}
240
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000241static PyObject *
242_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
243
244 char buf[2048];
245 PyObject *v;
246
247 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);
252 v = Py_BuildValue("(is)", errcode, buf);
253 if (v != NULL) {
254 PyErr_SetObject(PySSLErrorObject, v);
255 Py_DECREF(v);
256 }
257 return NULL;
258}
259
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000260static PySSLObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000261newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file,
262 enum py_ssl_server_or_client socket_type,
263 enum py_ssl_cert_requirements certreq,
264 enum py_ssl_version proto_version,
265 char *cacerts_file)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000266{
267 PySSLObject *self;
268 char *errstr = NULL;
269 int ret;
Thomas Woutersed03b412007-08-28 21:37:11 +0000270 int verification_mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000271
Guido van Rossume6650f92007-12-06 19:05:55 +0000272 self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000273 if (self == NULL)
274 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000275 self->peer_cert = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000276 self->ssl = NULL;
277 self->ctx = NULL;
278 self->Socket = NULL;
279
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000280 /* Make sure the SSL error state is initialized */
281 (void) ERR_get_state();
282 ERR_clear_error();
283
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000284 if ((key_file && !cert_file) || (!key_file && cert_file)) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000285 errstr = ERRSTR("Both the key & certificate files "
286 "must be specified");
287 goto fail;
288 }
289
290 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");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000294 goto fail;
295 }
296
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000297 PySSL_BEGIN_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000298 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 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000304 else if (proto_version == PY_SSL_VERSION_SSL23)
Thomas Woutersed03b412007-08-28 21:37:11 +0000305 self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000306 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000307
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000308 if (self->ctx == NULL) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000309 errstr = ERRSTR("Invalid SSL protocol variant specified.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000310 goto fail;
311 }
312
Thomas Woutersed03b412007-08-28 21:37:11 +0000313 if (certreq != PY_SSL_CERT_NONE) {
314 if (cacerts_file == NULL) {
315 errstr = ERRSTR("No root certificates specified for "
316 "verification of other-side certificates.");
317 goto fail;
318 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000319 PySSL_BEGIN_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000320 ret = SSL_CTX_load_verify_locations(self->ctx,
321 cacerts_file,
322 NULL);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000323 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000324 if (ret != 1) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000325 _setSSLError(NULL, 0, __FILE__, __LINE__);
Thomas Woutersed03b412007-08-28 21:37:11 +0000326 goto fail;
327 }
328 }
329 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000330 if (key_file) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000331 PySSL_BEGIN_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000332 ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
Thomas Woutersed03b412007-08-28 21:37:11 +0000333 SSL_FILETYPE_PEM);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000334 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000335 if (ret != 1) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000336 _setSSLError(NULL, ret, __FILE__, __LINE__);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000337 goto fail;
338 }
339
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000340 PySSL_BEGIN_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000341 ret = SSL_CTX_use_certificate_chain_file(self->ctx,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000342 cert_file);
343 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000344 if (ret != 1) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000345 /*
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 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000353 }
354 }
355
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000356 /* ssl compatibility */
357 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
358
Thomas Woutersed03b412007-08-28 21:37:11 +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 */
367
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000368 PySSL_BEGIN_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000369 self->ssl = SSL_new(self->ctx); /* New ssl struct */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000370 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000371 SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000372
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000373 /* If the socket is in non-blocking mode or timeout mode, set the BIO
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000374 * to non-blocking mode (blocking is the default)
375 */
376 if (Sock->sock_timeout >= 0.0) {
377 /* Set both the read and write BIO's to non-blocking mode */
378 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
379 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
380 }
381
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000382 PySSL_BEGIN_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000383 if (socket_type == PY_SSL_CLIENT)
384 SSL_set_connect_state(self->ssl);
385 else
386 SSL_set_accept_state(self->ssl);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000387 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000388
Bill Janssen54cc54c2007-12-14 22:08:56 +0000389 self->Socket = PyWeakref_NewRef((PyObject *) Sock, Py_None);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000390 return self;
391 fail:
392 if (errstr)
393 PyErr_SetString(PySSLErrorObject, errstr);
394 Py_DECREF(self);
395 return NULL;
396}
397
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000398static PyObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000399PySSL_sslwrap(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000400{
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000401 PySocketSockObject *Sock;
Thomas Woutersed03b412007-08-28 21:37:11 +0000402 int server_side = 0;
403 int verification_mode = PY_SSL_CERT_NONE;
404 int protocol = PY_SSL_VERSION_SSL23;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000405 char *key_file = NULL;
406 char *cert_file = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000407 char *cacerts_file = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000408
Thomas Woutersed03b412007-08-28 21:37:11 +0000409 if (!PyArg_ParseTuple(args, "O!i|zziiz:sslwrap",
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000410 PySocketModule.Sock_Type,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000411 &Sock,
Thomas Woutersed03b412007-08-28 21:37:11 +0000412 &server_side,
413 &key_file, &cert_file,
414 &verification_mode, &protocol,
415 &cacerts_file))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000416 return NULL;
417
Thomas Woutersed03b412007-08-28 21:37:11 +0000418 /*
419 fprintf(stderr,
420 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
421 "protocol %d, certs %p\n",
422 server_side, key_file, cert_file, verification_mode,
423 protocol, cacerts_file);
424 */
425
426 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
427 server_side, verification_mode,
428 protocol, cacerts_file);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000429}
430
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000431PyDoc_STRVAR(ssl_doc,
Thomas Woutersed03b412007-08-28 21:37:11 +0000432"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
433" cacertsfile]) -> sslobject");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000434
435/* SSL object methods */
436
Bill Janssen6e027db2007-11-15 22:23:56 +0000437static PyObject *PySSL_SSLdo_handshake(PySSLObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000438{
Bill Janssen6e027db2007-11-15 22:23:56 +0000439 int ret;
440 int err;
441 int sockstate;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000442
Bill Janssen6e027db2007-11-15 22:23:56 +0000443 /* Actually negotiate SSL connection */
444 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
445 sockstate = 0;
446 do {
Bill Janssen54cc54c2007-12-14 22:08:56 +0000447 PySocketSockObject *sock
448 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
449 if (((PyObject*)sock) == Py_None) {
450 _setSSLError("Underlying socket connection gone",
451 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
452 return NULL;
453 }
454
Bill Janssen6e027db2007-11-15 22:23:56 +0000455 PySSL_BEGIN_ALLOW_THREADS
456 ret = SSL_do_handshake(self->ssl);
457 err = SSL_get_error(self->ssl, ret);
458 PySSL_END_ALLOW_THREADS
459 if(PyErr_CheckSignals()) {
460 return NULL;
461 }
462 if (err == SSL_ERROR_WANT_READ) {
Bill Janssen54cc54c2007-12-14 22:08:56 +0000463 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Bill Janssen6e027db2007-11-15 22:23:56 +0000464 } else if (err == SSL_ERROR_WANT_WRITE) {
Bill Janssen54cc54c2007-12-14 22:08:56 +0000465 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Bill Janssen6e027db2007-11-15 22:23:56 +0000466 } else {
467 sockstate = SOCKET_OPERATION_OK;
468 }
469 if (sockstate == SOCKET_HAS_TIMED_OUT) {
470 PyErr_SetString(PySSLErrorObject,
471 ERRSTR("The handshake operation timed out"));
472 return NULL;
473 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
474 PyErr_SetString(PySSLErrorObject,
475 ERRSTR("Underlying socket has been closed."));
476 return NULL;
477 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
478 PyErr_SetString(PySSLErrorObject,
479 ERRSTR("Underlying socket too large for select()."));
480 return NULL;
481 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
482 break;
483 }
484 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
485 if (ret < 1)
486 return PySSL_SetError(self, ret, __FILE__, __LINE__);
487 self->ssl->debug = 1;
488
489 if (self->peer_cert)
490 X509_free (self->peer_cert);
491 PySSL_BEGIN_ALLOW_THREADS
492 self->peer_cert = SSL_get_peer_certificate(self->ssl);
493 PySSL_END_ALLOW_THREADS
494
495 Py_INCREF(Py_None);
496 return Py_None;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000497}
498
Thomas Woutersed03b412007-08-28 21:37:11 +0000499static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000500_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000501
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000502 char namebuf[X509_NAME_MAXLEN];
503 int buflen;
504 PyObject *name_obj;
505 PyObject *value_obj;
506 PyObject *attr;
507 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000508
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000509 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
510 if (buflen < 0) {
511 _setSSLError(NULL, 0, __FILE__, __LINE__);
512 goto fail;
Thomas Woutersed03b412007-08-28 21:37:11 +0000513 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000514 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000515 if (name_obj == NULL)
516 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000517
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000518 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
519 if (buflen < 0) {
520 _setSSLError(NULL, 0, __FILE__, __LINE__);
521 Py_DECREF(name_obj);
522 goto fail;
523 }
524 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
525 buflen, "strict");
526 OPENSSL_free(valuebuf);
527 if (value_obj == NULL) {
528 Py_DECREF(name_obj);
529 goto fail;
530 }
531 attr = PyTuple_New(2);
532 if (attr == NULL) {
533 Py_DECREF(name_obj);
534 Py_DECREF(value_obj);
535 goto fail;
536 }
537 PyTuple_SET_ITEM(attr, 0, name_obj);
538 PyTuple_SET_ITEM(attr, 1, value_obj);
539 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000540
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000541 fail:
Thomas Woutersed03b412007-08-28 21:37:11 +0000542 return NULL;
543}
544
545static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000546_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000547{
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000548 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
549 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
550 PyObject *rdnt;
551 PyObject *attr = NULL; /* tuple to hold an attribute */
552 int entry_count = X509_NAME_entry_count(xname);
553 X509_NAME_ENTRY *entry;
554 ASN1_OBJECT *name;
555 ASN1_STRING *value;
556 int index_counter;
557 int rdn_level = -1;
558 int retcode;
559
560 dn = PyList_New(0);
561 if (dn == NULL)
562 return NULL;
563 /* now create another tuple to hold the top-level RDN */
564 rdn = PyList_New(0);
565 if (rdn == NULL)
566 goto fail0;
567
568 for (index_counter = 0;
569 index_counter < entry_count;
570 index_counter++)
571 {
572 entry = X509_NAME_get_entry(xname, index_counter);
573
574 /* check to see if we've gotten to a new RDN */
575 if (rdn_level >= 0) {
576 if (rdn_level != entry->set) {
577 /* yes, new RDN */
578 /* add old RDN to DN */
579 rdnt = PyList_AsTuple(rdn);
580 Py_DECREF(rdn);
581 if (rdnt == NULL)
582 goto fail0;
583 retcode = PyList_Append(dn, rdnt);
584 Py_DECREF(rdnt);
585 if (retcode < 0)
586 goto fail0;
587 /* create new RDN */
588 rdn = PyList_New(0);
589 if (rdn == NULL)
590 goto fail0;
591 }
592 }
593 rdn_level = entry->set;
594
595 /* now add this attribute to the current RDN */
596 name = X509_NAME_ENTRY_get_object(entry);
597 value = X509_NAME_ENTRY_get_data(entry);
598 attr = _create_tuple_for_attribute(name, value);
599 /*
600 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
601 entry->set,
602 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
Guido van Rossumf06628b2007-11-21 20:01:53 +0000603 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000604 */
605 if (attr == NULL)
606 goto fail1;
607 retcode = PyList_Append(rdn, attr);
608 Py_DECREF(attr);
609 if (retcode < 0)
610 goto fail1;
611 }
612 /* now, there's typically a dangling RDN */
613 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
614 rdnt = PyList_AsTuple(rdn);
615 Py_DECREF(rdn);
616 if (rdnt == NULL)
617 goto fail0;
618 retcode = PyList_Append(dn, rdnt);
619 Py_DECREF(rdnt);
620 if (retcode < 0)
621 goto fail0;
622 }
623
624 /* convert list to tuple */
625 rdnt = PyList_AsTuple(dn);
626 Py_DECREF(dn);
627 if (rdnt == NULL)
628 return NULL;
629 return rdnt;
630
631 fail1:
632 Py_XDECREF(rdn);
633
634 fail0:
635 Py_XDECREF(dn);
636 return NULL;
637}
638
639static PyObject *
640_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000641
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000642 /* this code follows the procedure outlined in
643 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
644 function to extract the STACK_OF(GENERAL_NAME),
645 then iterates through the stack to add the
646 names. */
647
648 int i, j;
649 PyObject *peer_alt_names = Py_None;
650 PyObject *v, *t;
651 X509_EXTENSION *ext = NULL;
652 GENERAL_NAMES *names = NULL;
653 GENERAL_NAME *name;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000654 X509V3_EXT_METHOD *method;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000655 BIO *biobuf = NULL;
656 char buf[2048];
657 char *vptr;
658 int len;
Christian Heimes0449f632007-12-15 01:27:15 +0000659 const unsigned char *p;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000660
661 if (certificate == NULL)
662 return peer_alt_names;
663
664 /* get a memory buffer */
665 biobuf = BIO_new(BIO_s_mem());
666
667 i = 0;
668 while ((i = X509_get_ext_by_NID(
669 certificate, NID_subject_alt_name, i)) >= 0) {
670
671 if (peer_alt_names == Py_None) {
672 peer_alt_names = PyList_New(0);
673 if (peer_alt_names == NULL)
674 goto fail;
675 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000676
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000677 /* now decode the altName */
678 ext = X509_get_ext(certificate, i);
679 if(!(method = X509V3_EXT_get(ext))) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000680 PyErr_SetString
681 (PySSLErrorObject,
682 ERRSTR("No method for internalizing subjectAltName!"));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000683 goto fail;
684 }
685
686 p = ext->value->data;
Christian Heimes412dc9c2008-01-27 18:55:54 +0000687 if (method->it)
Bill Janssen6e027db2007-11-15 22:23:56 +0000688 names = (GENERAL_NAMES*)
689 (ASN1_item_d2i(NULL,
690 &p,
691 ext->value->length,
692 ASN1_ITEM_ptr(method->it)));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000693 else
Bill Janssen6e027db2007-11-15 22:23:56 +0000694 names = (GENERAL_NAMES*)
695 (method->d2i(NULL,
696 &p,
697 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000698
699 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
700
701 /* get a rendering of each name in the set of names */
702
703 name = sk_GENERAL_NAME_value(names, j);
704 if (name->type == GEN_DIRNAME) {
705
Bill Janssen6e027db2007-11-15 22:23:56 +0000706 /* we special-case DirName as a tuple of
707 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000708
709 t = PyTuple_New(2);
710 if (t == NULL) {
711 goto fail;
712 }
713
Bill Janssen6e027db2007-11-15 22:23:56 +0000714 v = PyUnicode_FromString("DirName");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000715 if (v == NULL) {
716 Py_DECREF(t);
717 goto fail;
718 }
719 PyTuple_SET_ITEM(t, 0, v);
720
721 v = _create_tuple_for_X509_NAME (name->d.dirn);
722 if (v == NULL) {
723 Py_DECREF(t);
724 goto fail;
725 }
726 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000727
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000728 } else {
729
730 /* for everything else, we use the OpenSSL print form */
731
732 (void) BIO_reset(biobuf);
733 GENERAL_NAME_print(biobuf, name);
734 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
735 if (len < 0) {
736 _setSSLError(NULL, 0, __FILE__, __LINE__);
737 goto fail;
738 }
739 vptr = strchr(buf, ':');
740 if (vptr == NULL)
741 goto fail;
742 t = PyTuple_New(2);
743 if (t == NULL)
744 goto fail;
Bill Janssen6e027db2007-11-15 22:23:56 +0000745 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000746 if (v == NULL) {
747 Py_DECREF(t);
748 goto fail;
749 }
750 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen6e027db2007-11-15 22:23:56 +0000751 v = PyUnicode_FromStringAndSize((vptr + 1),
752 (len - (vptr - buf + 1)));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000753 if (v == NULL) {
754 Py_DECREF(t);
755 goto fail;
756 }
757 PyTuple_SET_ITEM(t, 1, v);
758 }
759
760 /* and add that rendering to the list */
761
762 if (PyList_Append(peer_alt_names, t) < 0) {
763 Py_DECREF(t);
764 goto fail;
765 }
766 Py_DECREF(t);
767 }
768 }
769 BIO_free(biobuf);
770 if (peer_alt_names != Py_None) {
771 v = PyList_AsTuple(peer_alt_names);
772 Py_DECREF(peer_alt_names);
773 return v;
774 } else {
775 return peer_alt_names;
776 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000777
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000778
779 fail:
780 if (biobuf != NULL)
781 BIO_free(biobuf);
782
783 if (peer_alt_names != Py_None) {
784 Py_XDECREF(peer_alt_names);
785 }
786
787 return NULL;
788}
789
790static PyObject *
791_decode_certificate (X509 *certificate, int verbose) {
792
Thomas Woutersed03b412007-08-28 21:37:11 +0000793 PyObject *retval = NULL;
794 BIO *biobuf = NULL;
795 PyObject *peer;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000796 PyObject *peer_alt_names = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000797 PyObject *issuer;
798 PyObject *version;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000799 PyObject *sn_obj;
800 ASN1_INTEGER *serialNumber;
Thomas Woutersed03b412007-08-28 21:37:11 +0000801 char buf[2048];
802 int len;
803 ASN1_TIME *notBefore, *notAfter;
804 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000805
806 retval = PyDict_New();
807 if (retval == NULL)
808 return NULL;
809
Thomas Wouters89d996e2007-09-08 17:39:28 +0000810 peer = _create_tuple_for_X509_NAME(
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000811 X509_get_subject_name(certificate));
Thomas Woutersed03b412007-08-28 21:37:11 +0000812 if (peer == NULL)
813 goto fail0;
814 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
815 Py_DECREF(peer);
816 goto fail0;
817 }
818 Py_DECREF(peer);
819
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000820 if (verbose) {
821 issuer = _create_tuple_for_X509_NAME(
822 X509_get_issuer_name(certificate));
823 if (issuer == NULL)
824 goto fail0;
825 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
826 Py_DECREF(issuer);
827 goto fail0;
828 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000829 Py_DECREF(issuer);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000830
Christian Heimes217cfd12007-12-02 14:31:20 +0000831 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000832 if (PyDict_SetItemString(retval, "version", version) < 0) {
833 Py_DECREF(version);
834 goto fail0;
835 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000836 Py_DECREF(version);
Thomas Woutersed03b412007-08-28 21:37:11 +0000837 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000838
Thomas Woutersed03b412007-08-28 21:37:11 +0000839 /* get a memory buffer */
840 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000841
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000842 if (verbose) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000843
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000844 (void) BIO_reset(biobuf);
845 serialNumber = X509_get_serialNumber(certificate);
846 /* should not exceed 20 octets, 160 bits, so buf is big enough */
847 i2a_ASN1_INTEGER(biobuf, serialNumber);
848 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
849 if (len < 0) {
850 _setSSLError(NULL, 0, __FILE__, __LINE__);
851 goto fail1;
852 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000853 sn_obj = PyUnicode_FromStringAndSize(buf, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000854 if (sn_obj == NULL)
855 goto fail1;
856 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
857 Py_DECREF(sn_obj);
858 goto fail1;
859 }
860 Py_DECREF(sn_obj);
861
862 (void) BIO_reset(biobuf);
863 notBefore = X509_get_notBefore(certificate);
864 ASN1_TIME_print(biobuf, notBefore);
865 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
866 if (len < 0) {
867 _setSSLError(NULL, 0, __FILE__, __LINE__);
868 goto fail1;
869 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000870 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000871 if (pnotBefore == NULL)
872 goto fail1;
873 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
874 Py_DECREF(pnotBefore);
875 goto fail1;
876 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000877 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000878 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000879
880 (void) BIO_reset(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000881 notAfter = X509_get_notAfter(certificate);
Thomas Woutersed03b412007-08-28 21:37:11 +0000882 ASN1_TIME_print(biobuf, notAfter);
883 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000884 if (len < 0) {
885 _setSSLError(NULL, 0, __FILE__, __LINE__);
886 goto fail1;
887 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000888 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
Thomas Woutersed03b412007-08-28 21:37:11 +0000889 if (pnotAfter == NULL)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000890 goto fail1;
Thomas Woutersed03b412007-08-28 21:37:11 +0000891 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
892 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000893 goto fail1;
Thomas Woutersed03b412007-08-28 21:37:11 +0000894 }
895 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000896
897 /* Now look for subjectAltName */
898
899 peer_alt_names = _get_peer_alt_names(certificate);
900 if (peer_alt_names == NULL)
901 goto fail1;
902 else if (peer_alt_names != Py_None) {
903 if (PyDict_SetItemString(retval, "subjectAltName",
904 peer_alt_names) < 0) {
905 Py_DECREF(peer_alt_names);
906 goto fail1;
907 }
908 Py_DECREF(peer_alt_names);
909 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000910
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000911 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000912 return retval;
913
914 fail1:
915 if (biobuf != NULL)
916 BIO_free(biobuf);
917 fail0:
918 Py_XDECREF(retval);
919 return NULL;
920}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000921
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000922
923static PyObject *
924PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
925
926 PyObject *retval = NULL;
927 char *filename = NULL;
928 X509 *x=NULL;
929 BIO *cert;
930 int verbose = 1;
931
Bill Janssen6e027db2007-11-15 22:23:56 +0000932 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate",
933 &filename, &verbose))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000934 return NULL;
935
936 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000937 PyErr_SetString(PySSLErrorObject,
938 "Can't malloc memory to read file");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000939 goto fail0;
940 }
941
942 if (BIO_read_filename(cert,filename) <= 0) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000943 PyErr_SetString(PySSLErrorObject,
944 "Can't open file");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000945 goto fail0;
946 }
947
948 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
949 if (x == NULL) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000950 PyErr_SetString(PySSLErrorObject,
951 "Error decoding PEM-encoded file");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000952 goto fail0;
953 }
954
955 retval = _decode_certificate(x, verbose);
956
957 fail0:
Guido van Rossumf06628b2007-11-21 20:01:53 +0000958
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000959 if (cert != NULL) BIO_free(cert);
960 return retval;
961}
962
963
964static PyObject *
965PySSL_peercert(PySSLObject *self, PyObject *args)
966{
967 PyObject *retval = NULL;
968 int len;
969 int verification;
970 PyObject *binary_mode = Py_None;
971
972 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
973 return NULL;
974
975 if (!self->peer_cert)
976 Py_RETURN_NONE;
977
978 if (PyObject_IsTrue(binary_mode)) {
979 /* return cert in DER-encoded format */
980
981 unsigned char *bytes_buf = NULL;
982
983 bytes_buf = NULL;
984 len = i2d_X509(self->peer_cert, &bytes_buf);
985 if (len < 0) {
986 PySSL_SetError(self, len, __FILE__, __LINE__);
987 return NULL;
988 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000989 /* this is actually an immutable bytes sequence */
Guido van Rossumf06628b2007-11-21 20:01:53 +0000990 retval = PyString_FromStringAndSize
Bill Janssen6e027db2007-11-15 22:23:56 +0000991 ((const char *) bytes_buf, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000992 OPENSSL_free(bytes_buf);
993 return retval;
994
995 } else {
996
997 verification = SSL_CTX_get_verify_mode(self->ctx);
998 if ((verification & SSL_VERIFY_PEER) == 0)
999 return PyDict_New();
1000 else
1001 return _decode_certificate (self->peer_cert, 0);
1002 }
1003}
1004
1005PyDoc_STRVAR(PySSL_peercert_doc,
1006"peer_certificate([der=False]) -> certificate\n\
1007\n\
1008Returns the certificate for the peer. If no certificate was provided,\n\
1009returns None. If a certificate was provided, but not validated, returns\n\
1010an empty dictionary. Otherwise returns a dict containing information\n\
1011about the peer certificate.\n\
1012\n\
1013If the optional argument is True, returns a DER-encoded copy of the\n\
1014peer certificate, or None if no certificate was provided. This will\n\
1015return the certificate even if it wasn't validated.");
1016
1017static PyObject *PySSL_cipher (PySSLObject *self) {
1018
1019 PyObject *retval, *v;
1020 SSL_CIPHER *current;
1021 char *cipher_name;
1022 char *cipher_protocol;
1023
1024 if (self->ssl == NULL)
1025 return Py_None;
1026 current = SSL_get_current_cipher(self->ssl);
1027 if (current == NULL)
1028 return Py_None;
1029
1030 retval = PyTuple_New(3);
1031 if (retval == NULL)
1032 return NULL;
1033
1034 cipher_name = (char *) SSL_CIPHER_get_name(current);
1035 if (cipher_name == NULL) {
1036 PyTuple_SET_ITEM(retval, 0, Py_None);
1037 } else {
Bill Janssen6e027db2007-11-15 22:23:56 +00001038 v = PyUnicode_FromString(cipher_name);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001039 if (v == NULL)
1040 goto fail0;
1041 PyTuple_SET_ITEM(retval, 0, v);
1042 }
1043 cipher_protocol = SSL_CIPHER_get_version(current);
1044 if (cipher_protocol == NULL) {
1045 PyTuple_SET_ITEM(retval, 1, Py_None);
1046 } else {
Bill Janssen6e027db2007-11-15 22:23:56 +00001047 v = PyUnicode_FromString(cipher_protocol);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001048 if (v == NULL)
1049 goto fail0;
1050 PyTuple_SET_ITEM(retval, 1, v);
1051 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001052 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001053 if (v == NULL)
1054 goto fail0;
1055 PyTuple_SET_ITEM(retval, 2, v);
1056 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001057
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001058 fail0:
1059 Py_DECREF(retval);
1060 return NULL;
1061}
1062
Guido van Rossume6650f92007-12-06 19:05:55 +00001063static void PySSL_dealloc(PySSLObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001064{
Thomas Woutersed03b412007-08-28 21:37:11 +00001065 if (self->peer_cert) /* Possible not to have one? */
Guido van Rossume6650f92007-12-06 19:05:55 +00001066 X509_free (self->peer_cert);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001067 if (self->ssl)
Thomas Woutersed03b412007-08-28 21:37:11 +00001068 SSL_free(self->ssl);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001069 if (self->ctx)
Thomas Woutersed03b412007-08-28 21:37:11 +00001070 SSL_CTX_free(self->ctx);
Guido van Rossume6650f92007-12-06 19:05:55 +00001071 Py_XDECREF(self->Socket);
1072 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001073}
1074
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001075/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001076 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001077 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001078 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001079
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001080static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001081check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001082{
1083 fd_set fds;
1084 struct timeval tv;
1085 int rc;
1086
1087 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001088 if (s->sock_timeout < 0.0)
1089 return SOCKET_IS_BLOCKING;
1090 else if (s->sock_timeout == 0.0)
1091 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001092
1093 /* Guard against closed socket */
1094 if (s->sock_fd < 0)
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001095 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001096
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001097 /* Prefer poll, if available, since you can poll() any fd
1098 * which can't be done with select(). */
1099#ifdef HAVE_POLL
1100 {
1101 struct pollfd pollfd;
1102 int timeout;
1103
1104 pollfd.fd = s->sock_fd;
1105 pollfd.events = writing ? POLLOUT : POLLIN;
1106
1107 /* s->sock_timeout is in seconds, timeout in ms */
1108 timeout = (int)(s->sock_timeout * 1000 + 0.5);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001109 PySSL_BEGIN_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001110 rc = poll(&pollfd, 1, timeout);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001111 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001112
1113 goto normal_return;
1114 }
1115#endif
1116
Neal Norwitz082b2df2006-02-07 07:04:46 +00001117 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001118#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Neal Norwitz082b2df2006-02-07 07:04:46 +00001119 if (s->sock_fd >= FD_SETSIZE)
Neal Norwitz389cea82006-02-13 00:35:21 +00001120 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001121#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001122
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001123 /* Construct the arguments to select */
1124 tv.tv_sec = (int)s->sock_timeout;
1125 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1126 FD_ZERO(&fds);
1127 FD_SET(s->sock_fd, &fds);
1128
1129 /* See if the socket is ready */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001130 PySSL_BEGIN_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001131 if (writing)
1132 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1133 else
1134 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001135 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001136
Bill Janssen6e027db2007-11-15 22:23:56 +00001137#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001138normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001139#endif
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001140 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1141 (when we are able to write or when there's something to read) */
1142 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001143}
1144
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001145static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1146{
1147 char *data;
1148 int len;
Martin v. Löwis405a7952003-10-27 14:24:37 +00001149 int count;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001150 int sockstate;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001151 int err;
Bill Janssen6e027db2007-11-15 22:23:56 +00001152 int nonblocking;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001153 PySocketSockObject *sock
1154 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
1155
1156 if (((PyObject*)sock) == Py_None) {
1157 _setSSLError("Underlying socket connection gone",
1158 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1159 return NULL;
1160 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001161
Bill Janssen6e027db2007-11-15 22:23:56 +00001162 if (!PyArg_ParseTuple(args, "y#:write", &data, &count))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001163 return NULL;
1164
Bill Janssen6e027db2007-11-15 22:23:56 +00001165 /* just in case the blocking state of the socket has been changed */
Bill Janssen54cc54c2007-12-14 22:08:56 +00001166 nonblocking = (sock->sock_timeout >= 0.0);
Bill Janssen6e027db2007-11-15 22:23:56 +00001167 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1168 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1169
Bill Janssen54cc54c2007-12-14 22:08:56 +00001170 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001171 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001172 PyErr_SetString(PySSLErrorObject,
1173 "The write operation timed out");
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001174 return NULL;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001175 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001176 PyErr_SetString(PySSLErrorObject,
1177 "Underlying socket has been closed.");
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001178 return NULL;
Neal Norwitz389cea82006-02-13 00:35:21 +00001179 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001180 PyErr_SetString(PySSLErrorObject,
1181 "Underlying socket too large for select().");
Neal Norwitz082b2df2006-02-07 07:04:46 +00001182 return NULL;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001183 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001184 do {
1185 err = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001186 PySSL_BEGIN_ALLOW_THREADS
Martin v. Löwis405a7952003-10-27 14:24:37 +00001187 len = SSL_write(self->ssl, data, count);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001188 err = SSL_get_error(self->ssl, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001189 PySSL_END_ALLOW_THREADS
Martin v. Löwisafec8e32003-06-28 07:40:23 +00001190 if(PyErr_CheckSignals()) {
1191 return NULL;
1192 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001193 if (err == SSL_ERROR_WANT_READ) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001194 sockstate =
Bill Janssen54cc54c2007-12-14 22:08:56 +00001195 check_socket_and_wait_for_timeout(sock, 0);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001196 } else if (err == SSL_ERROR_WANT_WRITE) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001197 sockstate =
Bill Janssen54cc54c2007-12-14 22:08:56 +00001198 check_socket_and_wait_for_timeout(sock, 1);
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001199 } else {
1200 sockstate = SOCKET_OPERATION_OK;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001201 }
Thomas Woutersed03b412007-08-28 21:37:11 +00001202 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1203 PyErr_SetString(PySSLErrorObject,
1204 "The write operation timed out");
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001205 return NULL;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001206 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001207 PyErr_SetString(PySSLErrorObject,
1208 "Underlying socket has been closed.");
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001209 return NULL;
1210 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1211 break;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001212 }
1213 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001214 if (len > 0)
Christian Heimes217cfd12007-12-02 14:31:20 +00001215 return PyLong_FromLong(len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001216 else
Thomas Woutersed03b412007-08-28 21:37:11 +00001217 return PySSL_SetError(self, len, __FILE__, __LINE__);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001218}
1219
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001220PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001221"write(s) -> len\n\
1222\n\
1223Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001224of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001225
Bill Janssen6e027db2007-11-15 22:23:56 +00001226static PyObject *PySSL_SSLpending(PySSLObject *self)
1227{
1228 int count = 0;
1229
1230 PySSL_BEGIN_ALLOW_THREADS
1231 count = SSL_pending(self->ssl);
1232 PySSL_END_ALLOW_THREADS
1233 if (count < 0)
1234 return PySSL_SetError(self, count, __FILE__, __LINE__);
1235 else
Christian Heimes217cfd12007-12-02 14:31:20 +00001236 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001237}
1238
1239PyDoc_STRVAR(PySSL_SSLpending_doc,
1240"pending() -> count\n\
1241\n\
1242Returns the number of already decrypted bytes available for read,\n\
1243pending on the connection.\n");
1244
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001245static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1246{
Bill Janssen6e027db2007-11-15 22:23:56 +00001247 PyObject *buf = NULL;
1248 int buf_passed = 0;
1249 int count = -1;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001250 int len = 1024;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001251 int sockstate;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001252 int err;
Bill Janssen6e027db2007-11-15 22:23:56 +00001253 int nonblocking;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001254 PySocketSockObject *sock
1255 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
1256
1257 if (((PyObject*)sock) == Py_None) {
1258 _setSSLError("Underlying socket connection gone",
1259 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1260 return NULL;
1261 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001262
Bill Janssen6e027db2007-11-15 22:23:56 +00001263 if (!PyArg_ParseTuple(args, "|Oi:read", &buf, &count))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001264 return NULL;
Bill Janssen6e027db2007-11-15 22:23:56 +00001265 if ((buf == NULL) || (buf == Py_None)) {
1266 if (!(buf = PyBytes_FromStringAndSize((char *) 0, len)))
1267 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00001268 } else if (PyLong_Check(buf)) {
1269 len = PyLong_AS_LONG(buf);
Bill Janssen6e027db2007-11-15 22:23:56 +00001270 if (!(buf = PyBytes_FromStringAndSize((char *) 0, len)))
1271 return NULL;
1272 } else {
1273 if (!PyBytes_Check(buf))
1274 return NULL;
1275 len = PyBytes_Size(buf);
1276 if ((count > 0) && (count <= len))
1277 len = count;
1278 buf_passed = 1;
1279 }
1280
1281 /* just in case the blocking state of the socket has been changed */
Bill Janssen54cc54c2007-12-14 22:08:56 +00001282 nonblocking = (sock->sock_timeout >= 0.0);
Bill Janssen6e027db2007-11-15 22:23:56 +00001283 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1284 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Thomas Woutersed03b412007-08-28 21:37:11 +00001285
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001286 /* first check if there are bytes ready to be read */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001287 PySSL_BEGIN_ALLOW_THREADS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001288 count = SSL_pending(self->ssl);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001289 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001290
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001291 if (!count) {
Bill Janssen54cc54c2007-12-14 22:08:56 +00001292 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001293 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001294 PyErr_SetString(PySSLErrorObject,
1295 "The read operation timed out");
Bill Janssen6e027db2007-11-15 22:23:56 +00001296 if (!buf_passed) {
1297 Py_DECREF(buf);
1298 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001299 return NULL;
1300 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001301 PyErr_SetString(PySSLErrorObject,
1302 "Underlying socket too large for select().");
Bill Janssen6e027db2007-11-15 22:23:56 +00001303 if (!buf_passed) {
1304 Py_DECREF(buf);
1305 }
Thomas Woutersed03b412007-08-28 21:37:11 +00001306 Py_DECREF(buf);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001307 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001308 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001309 count = 0;
1310 goto done;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001311 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001312 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001313 do {
1314 err = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001315 PySSL_BEGIN_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001316 count = SSL_read(self->ssl, PyBytes_AsString(buf), len);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001317 err = SSL_get_error(self->ssl, count);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001318 PySSL_END_ALLOW_THREADS
Martin v. Löwisafec8e32003-06-28 07:40:23 +00001319 if(PyErr_CheckSignals()) {
Bill Janssen6e027db2007-11-15 22:23:56 +00001320 if (!buf_passed) {
1321 Py_DECREF(buf);
1322 }
Martin v. Löwisafec8e32003-06-28 07:40:23 +00001323 return NULL;
1324 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001325 if (err == SSL_ERROR_WANT_READ) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001326 sockstate =
Bill Janssen54cc54c2007-12-14 22:08:56 +00001327 check_socket_and_wait_for_timeout(sock, 0);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001328 } else if (err == SSL_ERROR_WANT_WRITE) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001329 sockstate =
Bill Janssen54cc54c2007-12-14 22:08:56 +00001330 check_socket_and_wait_for_timeout(sock, 1);
Thomas Woutersed03b412007-08-28 21:37:11 +00001331 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1332 (SSL_get_shutdown(self->ssl) ==
1333 SSL_RECEIVED_SHUTDOWN))
1334 {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001335 count = 0;
1336 goto done;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001337 } else {
1338 sockstate = SOCKET_OPERATION_OK;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001339 }
Thomas Woutersed03b412007-08-28 21:37:11 +00001340 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1341 PyErr_SetString(PySSLErrorObject,
1342 "The read operation timed out");
Bill Janssen6e027db2007-11-15 22:23:56 +00001343 if (!buf_passed) {
1344 Py_DECREF(buf);
1345 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001346 return NULL;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001347 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1348 break;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001349 }
1350 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Thomas Woutersed03b412007-08-28 21:37:11 +00001351 if (count <= 0) {
Bill Janssen6e027db2007-11-15 22:23:56 +00001352 if (!buf_passed) {
1353 Py_DECREF(buf);
1354 }
Thomas Woutersed03b412007-08-28 21:37:11 +00001355 return PySSL_SetError(self, count, __FILE__, __LINE__);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001356 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001357 done:
Bill Janssen6e027db2007-11-15 22:23:56 +00001358 if (!buf_passed) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001359 PyObject *res = PyString_FromStringAndSize(
1360 PyBytes_AS_STRING(buf), count);
1361 Py_DECREF(buf);
1362 return res;
Bill Janssen6e027db2007-11-15 22:23:56 +00001363 } else {
Christian Heimes217cfd12007-12-02 14:31:20 +00001364 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001365 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001366}
1367
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001368PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001369"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001370\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001371Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001372
1373static PyMethodDef PySSLMethods[] = {
Bill Janssen6e027db2007-11-15 22:23:56 +00001374 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001375 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001376 PySSL_SSLwrite_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001377 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001378 PySSL_SSLread_doc},
Bill Janssen6e027db2007-11-15 22:23:56 +00001379 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1380 PySSL_SSLpending_doc},
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001381 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1382 PySSL_peercert_doc},
1383 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001384 {NULL, NULL}
1385};
1386
Guido van Rossume6650f92007-12-06 19:05:55 +00001387static PyObject *PySSL_getattr(PySSLObject *self, char *name)
1388{
1389 return Py_FindMethod(PySSLMethods, (PyObject *)self, name);
1390}
1391
Jeremy Hylton938ace62002-07-17 16:30:39 +00001392static PyTypeObject PySSL_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001393 PyVarObject_HEAD_INIT(NULL, 0)
Guido van Rossume6650f92007-12-06 19:05:55 +00001394 "ssl.SSLContext", /*tp_name*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001395 sizeof(PySSLObject), /*tp_basicsize*/
1396 0, /*tp_itemsize*/
1397 /* methods */
1398 (destructor)PySSL_dealloc, /*tp_dealloc*/
1399 0, /*tp_print*/
Guido van Rossume6650f92007-12-06 19:05:55 +00001400 (getattrfunc)PySSL_getattr, /*tp_getattr*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001401 0, /*tp_setattr*/
1402 0, /*tp_compare*/
1403 0, /*tp_repr*/
1404 0, /*tp_as_number*/
1405 0, /*tp_as_sequence*/
1406 0, /*tp_as_mapping*/
1407 0, /*tp_hash*/
1408};
1409
1410#ifdef HAVE_OPENSSL_RAND
1411
1412/* helper routines for seeding the SSL PRNG */
1413static PyObject *
1414PySSL_RAND_add(PyObject *self, PyObject *args)
1415{
1416 char *buf;
1417 int len;
1418 double entropy;
1419
1420 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
1421 return NULL;
1422 RAND_add(buf, len, entropy);
1423 Py_INCREF(Py_None);
1424 return Py_None;
1425}
1426
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001427PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001428"RAND_add(string, entropy)\n\
1429\n\
1430Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001431bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001432
1433static PyObject *
1434PySSL_RAND_status(PyObject *self)
1435{
Christian Heimes217cfd12007-12-02 14:31:20 +00001436 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001437}
1438
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001439PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001440"RAND_status() -> 0 or 1\n\
1441\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001442Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1443It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1444using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001445
1446static PyObject *
1447PySSL_RAND_egd(PyObject *self, PyObject *arg)
1448{
1449 int bytes;
1450
Bill Janssen6e027db2007-11-15 22:23:56 +00001451 if (!PyUnicode_Check(arg))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001452 return PyErr_Format(PyExc_TypeError,
1453 "RAND_egd() expected string, found %s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001454 Py_TYPE(arg)->tp_name);
Bill Janssen6e027db2007-11-15 22:23:56 +00001455 bytes = RAND_egd(PyUnicode_AsString(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001456 if (bytes == -1) {
1457 PyErr_SetString(PySSLErrorObject,
1458 "EGD connection failed or EGD did not return "
1459 "enough data to seed the PRNG");
1460 return NULL;
1461 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001462 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001463}
1464
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001465PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001466"RAND_egd(path) -> bytes\n\
1467\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001468Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1469Returns number of bytes read. Raises SSLError if connection to EGD\n\
1470fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001471
1472#endif
1473
1474/* List of functions exported by this module. */
1475
1476static PyMethodDef PySSL_methods[] = {
Thomas Woutersed03b412007-08-28 21:37:11 +00001477 {"sslwrap", PySSL_sslwrap,
1478 METH_VARARGS, ssl_doc},
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001479 {"_test_decode_cert", PySSL_test_decode_certificate,
1480 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001481#ifdef HAVE_OPENSSL_RAND
Thomas Woutersed03b412007-08-28 21:37:11 +00001482 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001483 PySSL_RAND_add_doc},
1484 {"RAND_egd", PySSL_RAND_egd, METH_O,
1485 PySSL_RAND_egd_doc},
1486 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1487 PySSL_RAND_status_doc},
1488#endif
Thomas Woutersed03b412007-08-28 21:37:11 +00001489 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001490};
1491
1492
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001493#ifdef WITH_THREAD
1494
1495/* an implementation of OpenSSL threading operations in terms
1496 of the Python C thread library */
1497
1498static PyThread_type_lock *_ssl_locks = NULL;
1499
1500static unsigned long _ssl_thread_id_function (void) {
1501 return PyThread_get_thread_ident();
1502}
1503
Bill Janssen6e027db2007-11-15 22:23:56 +00001504static void _ssl_thread_locking_function
1505 (int mode, int n, const char *file, int line) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001506 /* this function is needed to perform locking on shared data
1507 structures. (Note that OpenSSL uses a number of global data
Bill Janssen6e027db2007-11-15 22:23:56 +00001508 structures that will be implicitly shared whenever multiple
1509 threads use OpenSSL.) Multi-threaded applications will
1510 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001511
Bill Janssen6e027db2007-11-15 22:23:56 +00001512 locking_function() must be able to handle up to
1513 CRYPTO_num_locks() different mutex locks. It sets the n-th
1514 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001515
1516 file and line are the file number of the function setting the
1517 lock. They can be useful for debugging.
1518 */
1519
1520 if ((_ssl_locks == NULL) ||
1521 (n < 0) || (n >= _ssl_locks_count))
1522 return;
1523
1524 if (mode & CRYPTO_LOCK) {
1525 PyThread_acquire_lock(_ssl_locks[n], 1);
1526 } else {
1527 PyThread_release_lock(_ssl_locks[n]);
1528 }
1529}
1530
1531static int _setup_ssl_threads(void) {
1532
1533 int i;
1534
1535 if (_ssl_locks == NULL) {
1536 _ssl_locks_count = CRYPTO_num_locks();
1537 _ssl_locks = (PyThread_type_lock *)
1538 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1539 if (_ssl_locks == NULL)
1540 return 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001541 memset(_ssl_locks, 0,
1542 sizeof(PyThread_type_lock) * _ssl_locks_count);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001543 for (i = 0; i < _ssl_locks_count; i++) {
1544 _ssl_locks[i] = PyThread_allocate_lock();
1545 if (_ssl_locks[i] == NULL) {
1546 int j;
1547 for (j = 0; j < i; j++) {
1548 PyThread_free_lock(_ssl_locks[j]);
1549 }
1550 free(_ssl_locks);
1551 return 0;
1552 }
1553 }
1554 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1555 CRYPTO_set_id_callback(_ssl_thread_id_function);
1556 }
1557 return 1;
1558}
1559
1560#endif /* def HAVE_THREAD */
1561
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001562PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001563"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001564for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001565
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001566PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001567init_ssl(void)
1568{
1569 PyObject *m, *d;
1570
Christian Heimes90aa7642007-12-19 02:45:37 +00001571 Py_TYPE(&PySSL_Type) = &PyType_Type;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001572
1573 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001574 if (m == NULL)
1575 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001576 d = PyModule_GetDict(m);
1577
1578 /* Load _socket module and its C API */
1579 if (PySocketModule_ImportModuleAndAPI())
Thomas Woutersed03b412007-08-28 21:37:11 +00001580 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001581
1582 /* Init OpenSSL */
1583 SSL_load_error_strings();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001584#ifdef WITH_THREAD
1585 /* note that this will start threading if not already started */
1586 if (!_setup_ssl_threads()) {
1587 return;
1588 }
1589#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001590 SSLeay_add_ssl_algorithms();
1591
1592 /* Add symbols to module dict */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001593 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
Thomas Woutersed03b412007-08-28 21:37:11 +00001594 PySocketModule.error,
1595 NULL);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001596 if (PySSLErrorObject == NULL)
1597 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001598 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
Thomas Woutersed03b412007-08-28 21:37:11 +00001599 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001600 if (PyDict_SetItemString(d, "SSLType",
1601 (PyObject *)&PySSL_Type) != 0)
1602 return;
1603 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001604 PY_SSL_ERROR_ZERO_RETURN);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001605 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001606 PY_SSL_ERROR_WANT_READ);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001607 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001608 PY_SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001609 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001610 PY_SSL_ERROR_WANT_X509_LOOKUP);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001611 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001612 PY_SSL_ERROR_SYSCALL);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001613 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001614 PY_SSL_ERROR_SSL);
1615 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1616 PY_SSL_ERROR_WANT_CONNECT);
1617 /* non ssl.h errorcodes */
1618 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1619 PY_SSL_ERROR_EOF);
1620 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1621 PY_SSL_ERROR_INVALID_ERROR_CODE);
Thomas Woutersed03b412007-08-28 21:37:11 +00001622 /* cert requirements */
1623 PyModule_AddIntConstant(m, "CERT_NONE",
1624 PY_SSL_CERT_NONE);
1625 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1626 PY_SSL_CERT_OPTIONAL);
1627 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1628 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001629
Thomas Woutersed03b412007-08-28 21:37:11 +00001630 /* protocol versions */
1631 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1632 PY_SSL_VERSION_SSL2);
1633 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1634 PY_SSL_VERSION_SSL3);
1635 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1636 PY_SSL_VERSION_SSL23);
1637 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1638 PY_SSL_VERSION_TLS1);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001639}