blob: 1aedaf8a7aed0e730c27bea411a48bff172a909a [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 */
49 PY_SSL_ERROR_INVALID_ERROR_CODE
50};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000051
Thomas Woutersed03b412007-08-28 21:37:11 +000052enum py_ssl_server_or_client {
53 PY_SSL_CLIENT,
54 PY_SSL_SERVER
55};
56
57enum py_ssl_cert_requirements {
58 PY_SSL_CERT_NONE,
59 PY_SSL_CERT_OPTIONAL,
60 PY_SSL_CERT_REQUIRED
61};
62
63enum py_ssl_version {
64 PY_SSL_VERSION_SSL2,
65 PY_SSL_VERSION_SSL3,
66 PY_SSL_VERSION_SSL23,
67 PY_SSL_VERSION_TLS1,
68};
69
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000070/* Include symbols from _socket module */
71#include "socketmodule.h"
72
Thomas Woutersed03b412007-08-28 21:37:11 +000073#if defined(HAVE_POLL_H)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000074#include <poll.h>
75#elif defined(HAVE_SYS_POLL_H)
76#include <sys/poll.h>
77#endif
78
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000079/* Include OpenSSL header files */
80#include "openssl/rsa.h"
81#include "openssl/crypto.h"
82#include "openssl/x509.h"
Thomas Wouters1b7f8912007-09-19 03:06:30 +000083#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000084#include "openssl/pem.h"
85#include "openssl/ssl.h"
86#include "openssl/err.h"
87#include "openssl/rand.h"
88
89/* SSL error object */
90static PyObject *PySSLErrorObject;
91
Thomas Wouters1b7f8912007-09-19 03:06:30 +000092#ifdef WITH_THREAD
93
94/* serves as a flag to see whether we've initialized the SSL thread support. */
95/* 0 means no, greater than 0 means yes */
96
97static unsigned int _ssl_locks_count = 0;
98
99#endif /* def WITH_THREAD */
100
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000101/* SSL socket object */
102
103#define X509_NAME_MAXLEN 256
104
105/* RAND_* APIs got added to OpenSSL in 0.9.5 */
106#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
107# define HAVE_OPENSSL_RAND 1
108#else
109# undef HAVE_OPENSSL_RAND
110#endif
111
112typedef struct {
113 PyObject_HEAD
114 PySocketSockObject *Socket; /* Socket on which we're layered */
Thomas Woutersed03b412007-08-28 21:37:11 +0000115 SSL_CTX* ctx;
116 SSL* ssl;
117 X509* peer_cert;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000118
119} PySSLObject;
120
Jeremy Hylton938ace62002-07-17 16:30:39 +0000121static PyTypeObject PySSL_Type;
122static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args);
123static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000124static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000125 int writing);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000126static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args);
127static PyObject *PySSL_cipher(PySSLObject *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000128
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000129#define PySSLObject_Check(v) (Py_Type(v) == &PySSL_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000130
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000131typedef enum {
132 SOCKET_IS_NONBLOCKING,
133 SOCKET_IS_BLOCKING,
134 SOCKET_HAS_TIMED_OUT,
135 SOCKET_HAS_BEEN_CLOSED,
Neal Norwitz389cea82006-02-13 00:35:21 +0000136 SOCKET_TOO_LARGE_FOR_SELECT,
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000137 SOCKET_OPERATION_OK
138} timeout_state;
139
Thomas Woutersed03b412007-08-28 21:37:11 +0000140/* Wrap error strings with filename and line # */
141#define STRINGIFY1(x) #x
142#define STRINGIFY2(x) STRINGIFY1(x)
143#define ERRSTR1(x,y,z) (x ":" y ": " z)
144#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
145
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000146/* XXX It might be helpful to augment the error message generated
147 below with the name of the SSL function that generated the error.
148 I expect it's obvious most of the time.
149*/
150
151static PyObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000152PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000153{
Thomas Woutersed03b412007-08-28 21:37:11 +0000154 PyObject *v;
155 char buf[2048];
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000156 char *errstr;
157 int err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000158 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000159
160 assert(ret <= 0);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000161
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000162 if (obj->ssl != NULL) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000163 err = SSL_get_error(obj->ssl, ret);
164
165 switch (err) {
166 case SSL_ERROR_ZERO_RETURN:
167 errstr = "TLS/SSL connection has been closed";
168 p = PY_SSL_ERROR_ZERO_RETURN;
169 break;
170 case SSL_ERROR_WANT_READ:
171 errstr = "The operation did not complete (read)";
172 p = PY_SSL_ERROR_WANT_READ;
173 break;
174 case SSL_ERROR_WANT_WRITE:
175 p = PY_SSL_ERROR_WANT_WRITE;
176 errstr = "The operation did not complete (write)";
177 break;
178 case SSL_ERROR_WANT_X509_LOOKUP:
179 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
180 errstr =
181 "The operation did not complete (X509 lookup)";
182 break;
183 case SSL_ERROR_WANT_CONNECT:
184 p = PY_SSL_ERROR_WANT_CONNECT;
185 errstr = "The operation did not complete (connect)";
186 break;
187 case SSL_ERROR_SYSCALL:
188 {
189 unsigned long e = ERR_get_error();
190 if (e == 0) {
191 if (ret == 0 || !obj->Socket) {
192 p = PY_SSL_ERROR_EOF;
193 errstr =
194 "EOF occurred in violation of protocol";
195 } else if (ret == -1) {
196 /* underlying BIO reported an I/O error */
197 return obj->Socket->errorhandler();
198 } else { /* possible? */
199 p = PY_SSL_ERROR_SYSCALL;
200 errstr = "Some I/O error occurred";
201 }
202 } else {
Jeremy Hylton4e547302002-07-02 18:25:00 +0000203 p = PY_SSL_ERROR_SYSCALL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000204 /* XXX Protected by global interpreter lock */
205 errstr = ERR_error_string(e, NULL);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000206 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000207 break;
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000208 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000209 case SSL_ERROR_SSL:
210 {
211 unsigned long e = ERR_get_error();
212 p = PY_SSL_ERROR_SSL;
213 if (e != 0)
214 /* XXX Protected by global interpreter lock */
215 errstr = ERR_error_string(e, NULL);
216 else { /* possible? */
217 errstr =
218 "A failure in the SSL library occurred";
219 }
220 break;
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000221 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000222 default:
223 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
224 errstr = "Invalid error code";
225 }
226 } else {
227 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000228 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000229 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
230 v = Py_BuildValue("(is)", p, buf);
231 if (v != NULL) {
232 PyErr_SetObject(PySSLErrorObject, v);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000233 Py_DECREF(v);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000234 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000235 return NULL;
236}
237
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000238static PyObject *
239_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
240
241 char buf[2048];
242 PyObject *v;
243
244 if (errstr == NULL) {
245 errcode = ERR_peek_last_error();
246 errstr = ERR_error_string(errcode, NULL);
247 }
248 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
249 v = Py_BuildValue("(is)", errcode, buf);
250 if (v != NULL) {
251 PyErr_SetObject(PySSLErrorObject, v);
252 Py_DECREF(v);
253 }
254 return NULL;
255}
256
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000257static PySSLObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000258newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file,
259 enum py_ssl_server_or_client socket_type,
260 enum py_ssl_cert_requirements certreq,
261 enum py_ssl_version proto_version,
262 char *cacerts_file)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000263{
264 PySSLObject *self;
265 char *errstr = NULL;
266 int ret;
Thomas Woutersed03b412007-08-28 21:37:11 +0000267 int verification_mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000268
Guido van Rossum03b5c9a2007-12-06 18:39:46 +0000269 self = PyObject_GC_New(PySSLObject, &PySSL_Type); /* Create new object */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000270 if (self == NULL)
271 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000272 self->peer_cert = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000273 self->ssl = NULL;
274 self->ctx = NULL;
275 self->Socket = NULL;
276
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000277 /* Make sure the SSL error state is initialized */
278 (void) ERR_get_state();
279 ERR_clear_error();
280
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000281 if ((key_file && !cert_file) || (!key_file && cert_file)) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000282 errstr = ERRSTR("Both the key & certificate files "
283 "must be specified");
284 goto fail;
285 }
286
287 if ((socket_type == PY_SSL_SERVER) &&
288 ((key_file == NULL) || (cert_file == NULL))) {
289 errstr = ERRSTR("Both the key & certificate files "
290 "must be specified for server-side operation");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000291 goto fail;
292 }
293
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000294 PySSL_BEGIN_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000295 if (proto_version == PY_SSL_VERSION_TLS1)
296 self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */
297 else if (proto_version == PY_SSL_VERSION_SSL3)
298 self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */
299 else if (proto_version == PY_SSL_VERSION_SSL2)
300 self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000301 else if (proto_version == PY_SSL_VERSION_SSL23)
Thomas Woutersed03b412007-08-28 21:37:11 +0000302 self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000303 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000304
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000305 if (self->ctx == NULL) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000306 errstr = ERRSTR("Invalid SSL protocol variant specified.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000307 goto fail;
308 }
309
Thomas Woutersed03b412007-08-28 21:37:11 +0000310 if (certreq != PY_SSL_CERT_NONE) {
311 if (cacerts_file == NULL) {
312 errstr = ERRSTR("No root certificates specified for "
313 "verification of other-side certificates.");
314 goto fail;
315 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000316 PySSL_BEGIN_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000317 ret = SSL_CTX_load_verify_locations(self->ctx,
318 cacerts_file,
319 NULL);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000320 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000321 if (ret != 1) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000322 _setSSLError(NULL, 0, __FILE__, __LINE__);
Thomas Woutersed03b412007-08-28 21:37:11 +0000323 goto fail;
324 }
325 }
326 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000327 if (key_file) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000328 PySSL_BEGIN_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000329 ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
Thomas Woutersed03b412007-08-28 21:37:11 +0000330 SSL_FILETYPE_PEM);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000331 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000332 if (ret != 1) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000333 _setSSLError(NULL, ret, __FILE__, __LINE__);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000334 goto fail;
335 }
336
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000337 PySSL_BEGIN_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000338 ret = SSL_CTX_use_certificate_chain_file(self->ctx,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000339 cert_file);
340 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000341 if (ret != 1) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000342 /*
343 fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
344 ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
345 */
346 if (ERR_peek_last_error() != 0) {
347 _setSSLError(NULL, ret, __FILE__, __LINE__);
348 goto fail;
349 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000350 }
351 }
352
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000353 /* ssl compatibility */
354 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
355
Thomas Woutersed03b412007-08-28 21:37:11 +0000356 verification_mode = SSL_VERIFY_NONE;
357 if (certreq == PY_SSL_CERT_OPTIONAL)
358 verification_mode = SSL_VERIFY_PEER;
359 else if (certreq == PY_SSL_CERT_REQUIRED)
360 verification_mode = (SSL_VERIFY_PEER |
361 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
362 SSL_CTX_set_verify(self->ctx, verification_mode,
363 NULL); /* set verify lvl */
364
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000365 PySSL_BEGIN_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000366 self->ssl = SSL_new(self->ctx); /* New ssl struct */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000367 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000368 SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000369
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000370 /* If the socket is in non-blocking mode or timeout mode, set the BIO
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000371 * to non-blocking mode (blocking is the default)
372 */
373 if (Sock->sock_timeout >= 0.0) {
374 /* Set both the read and write BIO's to non-blocking mode */
375 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
376 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
377 }
378
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000379 PySSL_BEGIN_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000380 if (socket_type == PY_SSL_CLIENT)
381 SSL_set_connect_state(self->ssl);
382 else
383 SSL_set_accept_state(self->ssl);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000384 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000385
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000386 self->Socket = Sock;
387 Py_INCREF(self->Socket);
Guido van Rossum03b5c9a2007-12-06 18:39:46 +0000388 _PyObject_GC_TRACK(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000389 return self;
390 fail:
391 if (errstr)
392 PyErr_SetString(PySSLErrorObject, errstr);
393 Py_DECREF(self);
394 return NULL;
395}
396
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000397static PyObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000398PySSL_sslwrap(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000399{
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000400 PySocketSockObject *Sock;
Thomas Woutersed03b412007-08-28 21:37:11 +0000401 int server_side = 0;
402 int verification_mode = PY_SSL_CERT_NONE;
403 int protocol = PY_SSL_VERSION_SSL23;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000404 char *key_file = NULL;
405 char *cert_file = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000406 char *cacerts_file = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000407
Thomas Woutersed03b412007-08-28 21:37:11 +0000408 if (!PyArg_ParseTuple(args, "O!i|zziiz:sslwrap",
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000409 PySocketModule.Sock_Type,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000410 &Sock,
Thomas Woutersed03b412007-08-28 21:37:11 +0000411 &server_side,
412 &key_file, &cert_file,
413 &verification_mode, &protocol,
414 &cacerts_file))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000415 return NULL;
416
Thomas Woutersed03b412007-08-28 21:37:11 +0000417 /*
418 fprintf(stderr,
419 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
420 "protocol %d, certs %p\n",
421 server_side, key_file, cert_file, verification_mode,
422 protocol, cacerts_file);
423 */
424
425 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
426 server_side, verification_mode,
427 protocol, cacerts_file);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000428}
429
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000430PyDoc_STRVAR(ssl_doc,
Thomas Woutersed03b412007-08-28 21:37:11 +0000431"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
432" cacertsfile]) -> sslobject");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000433
434/* SSL object methods */
435
Bill Janssen6e027db2007-11-15 22:23:56 +0000436static PyObject *PySSL_SSLdo_handshake(PySSLObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000437{
Bill Janssen6e027db2007-11-15 22:23:56 +0000438 int ret;
439 int err;
440 int sockstate;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000441
Bill Janssen6e027db2007-11-15 22:23:56 +0000442 /* Actually negotiate SSL connection */
443 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
444 sockstate = 0;
445 do {
446 PySSL_BEGIN_ALLOW_THREADS
447 ret = SSL_do_handshake(self->ssl);
448 err = SSL_get_error(self->ssl, ret);
449 PySSL_END_ALLOW_THREADS
450 if(PyErr_CheckSignals()) {
451 return NULL;
452 }
453 if (err == SSL_ERROR_WANT_READ) {
454 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
455 } else if (err == SSL_ERROR_WANT_WRITE) {
456 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
457 } else {
458 sockstate = SOCKET_OPERATION_OK;
459 }
460 if (sockstate == SOCKET_HAS_TIMED_OUT) {
461 PyErr_SetString(PySSLErrorObject,
462 ERRSTR("The handshake operation timed out"));
463 return NULL;
464 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
465 PyErr_SetString(PySSLErrorObject,
466 ERRSTR("Underlying socket has been closed."));
467 return NULL;
468 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
469 PyErr_SetString(PySSLErrorObject,
470 ERRSTR("Underlying socket too large for select()."));
471 return NULL;
472 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
473 break;
474 }
475 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
476 if (ret < 1)
477 return PySSL_SetError(self, ret, __FILE__, __LINE__);
478 self->ssl->debug = 1;
479
480 if (self->peer_cert)
481 X509_free (self->peer_cert);
482 PySSL_BEGIN_ALLOW_THREADS
483 self->peer_cert = SSL_get_peer_certificate(self->ssl);
484 PySSL_END_ALLOW_THREADS
485
486 Py_INCREF(Py_None);
487 return Py_None;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000488}
489
Thomas Woutersed03b412007-08-28 21:37:11 +0000490static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000491_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000492
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000493 char namebuf[X509_NAME_MAXLEN];
494 int buflen;
495 PyObject *name_obj;
496 PyObject *value_obj;
497 PyObject *attr;
498 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000499
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000500 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
501 if (buflen < 0) {
502 _setSSLError(NULL, 0, __FILE__, __LINE__);
503 goto fail;
Thomas Woutersed03b412007-08-28 21:37:11 +0000504 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000505 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000506 if (name_obj == NULL)
507 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000508
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000509 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
510 if (buflen < 0) {
511 _setSSLError(NULL, 0, __FILE__, __LINE__);
512 Py_DECREF(name_obj);
513 goto fail;
514 }
515 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
516 buflen, "strict");
517 OPENSSL_free(valuebuf);
518 if (value_obj == NULL) {
519 Py_DECREF(name_obj);
520 goto fail;
521 }
522 attr = PyTuple_New(2);
523 if (attr == NULL) {
524 Py_DECREF(name_obj);
525 Py_DECREF(value_obj);
526 goto fail;
527 }
528 PyTuple_SET_ITEM(attr, 0, name_obj);
529 PyTuple_SET_ITEM(attr, 1, value_obj);
530 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000531
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000532 fail:
Thomas Woutersed03b412007-08-28 21:37:11 +0000533 return NULL;
534}
535
536static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000537_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000538{
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000539 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
540 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
541 PyObject *rdnt;
542 PyObject *attr = NULL; /* tuple to hold an attribute */
543 int entry_count = X509_NAME_entry_count(xname);
544 X509_NAME_ENTRY *entry;
545 ASN1_OBJECT *name;
546 ASN1_STRING *value;
547 int index_counter;
548 int rdn_level = -1;
549 int retcode;
550
551 dn = PyList_New(0);
552 if (dn == NULL)
553 return NULL;
554 /* now create another tuple to hold the top-level RDN */
555 rdn = PyList_New(0);
556 if (rdn == NULL)
557 goto fail0;
558
559 for (index_counter = 0;
560 index_counter < entry_count;
561 index_counter++)
562 {
563 entry = X509_NAME_get_entry(xname, index_counter);
564
565 /* check to see if we've gotten to a new RDN */
566 if (rdn_level >= 0) {
567 if (rdn_level != entry->set) {
568 /* yes, new RDN */
569 /* add old RDN to DN */
570 rdnt = PyList_AsTuple(rdn);
571 Py_DECREF(rdn);
572 if (rdnt == NULL)
573 goto fail0;
574 retcode = PyList_Append(dn, rdnt);
575 Py_DECREF(rdnt);
576 if (retcode < 0)
577 goto fail0;
578 /* create new RDN */
579 rdn = PyList_New(0);
580 if (rdn == NULL)
581 goto fail0;
582 }
583 }
584 rdn_level = entry->set;
585
586 /* now add this attribute to the current RDN */
587 name = X509_NAME_ENTRY_get_object(entry);
588 value = X509_NAME_ENTRY_get_data(entry);
589 attr = _create_tuple_for_attribute(name, value);
590 /*
591 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
592 entry->set,
593 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
Guido van Rossumf06628b2007-11-21 20:01:53 +0000594 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000595 */
596 if (attr == NULL)
597 goto fail1;
598 retcode = PyList_Append(rdn, attr);
599 Py_DECREF(attr);
600 if (retcode < 0)
601 goto fail1;
602 }
603 /* now, there's typically a dangling RDN */
604 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
605 rdnt = PyList_AsTuple(rdn);
606 Py_DECREF(rdn);
607 if (rdnt == NULL)
608 goto fail0;
609 retcode = PyList_Append(dn, rdnt);
610 Py_DECREF(rdnt);
611 if (retcode < 0)
612 goto fail0;
613 }
614
615 /* convert list to tuple */
616 rdnt = PyList_AsTuple(dn);
617 Py_DECREF(dn);
618 if (rdnt == NULL)
619 return NULL;
620 return rdnt;
621
622 fail1:
623 Py_XDECREF(rdn);
624
625 fail0:
626 Py_XDECREF(dn);
627 return NULL;
628}
629
630static PyObject *
631_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000632
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000633 /* this code follows the procedure outlined in
634 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
635 function to extract the STACK_OF(GENERAL_NAME),
636 then iterates through the stack to add the
637 names. */
638
639 int i, j;
640 PyObject *peer_alt_names = Py_None;
641 PyObject *v, *t;
642 X509_EXTENSION *ext = NULL;
643 GENERAL_NAMES *names = NULL;
644 GENERAL_NAME *name;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000645 X509V3_EXT_METHOD *method;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000646 BIO *biobuf = NULL;
647 char buf[2048];
648 char *vptr;
649 int len;
650 unsigned char *p;
651
652 if (certificate == NULL)
653 return peer_alt_names;
654
655 /* get a memory buffer */
656 biobuf = BIO_new(BIO_s_mem());
657
658 i = 0;
659 while ((i = X509_get_ext_by_NID(
660 certificate, NID_subject_alt_name, i)) >= 0) {
661
662 if (peer_alt_names == Py_None) {
663 peer_alt_names = PyList_New(0);
664 if (peer_alt_names == NULL)
665 goto fail;
666 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000667
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000668 /* now decode the altName */
669 ext = X509_get_ext(certificate, i);
670 if(!(method = X509V3_EXT_get(ext))) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000671 PyErr_SetString
672 (PySSLErrorObject,
673 ERRSTR("No method for internalizing subjectAltName!"));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000674 goto fail;
675 }
676
677 p = ext->value->data;
678 if(method->it)
Bill Janssen6e027db2007-11-15 22:23:56 +0000679 names = (GENERAL_NAMES*)
680 (ASN1_item_d2i(NULL,
681 &p,
682 ext->value->length,
683 ASN1_ITEM_ptr(method->it)));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000684 else
Bill Janssen6e027db2007-11-15 22:23:56 +0000685 names = (GENERAL_NAMES*)
686 (method->d2i(NULL,
687 &p,
688 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000689
690 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
691
692 /* get a rendering of each name in the set of names */
693
694 name = sk_GENERAL_NAME_value(names, j);
695 if (name->type == GEN_DIRNAME) {
696
Bill Janssen6e027db2007-11-15 22:23:56 +0000697 /* we special-case DirName as a tuple of
698 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000699
700 t = PyTuple_New(2);
701 if (t == NULL) {
702 goto fail;
703 }
704
Bill Janssen6e027db2007-11-15 22:23:56 +0000705 v = PyUnicode_FromString("DirName");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000706 if (v == NULL) {
707 Py_DECREF(t);
708 goto fail;
709 }
710 PyTuple_SET_ITEM(t, 0, v);
711
712 v = _create_tuple_for_X509_NAME (name->d.dirn);
713 if (v == NULL) {
714 Py_DECREF(t);
715 goto fail;
716 }
717 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000718
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000719 } else {
720
721 /* for everything else, we use the OpenSSL print form */
722
723 (void) BIO_reset(biobuf);
724 GENERAL_NAME_print(biobuf, name);
725 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
726 if (len < 0) {
727 _setSSLError(NULL, 0, __FILE__, __LINE__);
728 goto fail;
729 }
730 vptr = strchr(buf, ':');
731 if (vptr == NULL)
732 goto fail;
733 t = PyTuple_New(2);
734 if (t == NULL)
735 goto fail;
Bill Janssen6e027db2007-11-15 22:23:56 +0000736 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000737 if (v == NULL) {
738 Py_DECREF(t);
739 goto fail;
740 }
741 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen6e027db2007-11-15 22:23:56 +0000742 v = PyUnicode_FromStringAndSize((vptr + 1),
743 (len - (vptr - buf + 1)));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000744 if (v == NULL) {
745 Py_DECREF(t);
746 goto fail;
747 }
748 PyTuple_SET_ITEM(t, 1, v);
749 }
750
751 /* and add that rendering to the list */
752
753 if (PyList_Append(peer_alt_names, t) < 0) {
754 Py_DECREF(t);
755 goto fail;
756 }
757 Py_DECREF(t);
758 }
759 }
760 BIO_free(biobuf);
761 if (peer_alt_names != Py_None) {
762 v = PyList_AsTuple(peer_alt_names);
763 Py_DECREF(peer_alt_names);
764 return v;
765 } else {
766 return peer_alt_names;
767 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000768
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000769
770 fail:
771 if (biobuf != NULL)
772 BIO_free(biobuf);
773
774 if (peer_alt_names != Py_None) {
775 Py_XDECREF(peer_alt_names);
776 }
777
778 return NULL;
779}
780
781static PyObject *
782_decode_certificate (X509 *certificate, int verbose) {
783
Thomas Woutersed03b412007-08-28 21:37:11 +0000784 PyObject *retval = NULL;
785 BIO *biobuf = NULL;
786 PyObject *peer;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000787 PyObject *peer_alt_names = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000788 PyObject *issuer;
789 PyObject *version;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000790 PyObject *sn_obj;
791 ASN1_INTEGER *serialNumber;
Thomas Woutersed03b412007-08-28 21:37:11 +0000792 char buf[2048];
793 int len;
794 ASN1_TIME *notBefore, *notAfter;
795 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000796
797 retval = PyDict_New();
798 if (retval == NULL)
799 return NULL;
800
Thomas Wouters89d996e2007-09-08 17:39:28 +0000801 peer = _create_tuple_for_X509_NAME(
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000802 X509_get_subject_name(certificate));
Thomas Woutersed03b412007-08-28 21:37:11 +0000803 if (peer == NULL)
804 goto fail0;
805 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
806 Py_DECREF(peer);
807 goto fail0;
808 }
809 Py_DECREF(peer);
810
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000811 if (verbose) {
812 issuer = _create_tuple_for_X509_NAME(
813 X509_get_issuer_name(certificate));
814 if (issuer == NULL)
815 goto fail0;
816 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
817 Py_DECREF(issuer);
818 goto fail0;
819 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000820 Py_DECREF(issuer);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000821
Christian Heimes217cfd12007-12-02 14:31:20 +0000822 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000823 if (PyDict_SetItemString(retval, "version", version) < 0) {
824 Py_DECREF(version);
825 goto fail0;
826 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000827 Py_DECREF(version);
Thomas Woutersed03b412007-08-28 21:37:11 +0000828 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000829
Thomas Woutersed03b412007-08-28 21:37:11 +0000830 /* get a memory buffer */
831 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000832
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000833 if (verbose) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000834
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000835 (void) BIO_reset(biobuf);
836 serialNumber = X509_get_serialNumber(certificate);
837 /* should not exceed 20 octets, 160 bits, so buf is big enough */
838 i2a_ASN1_INTEGER(biobuf, serialNumber);
839 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
840 if (len < 0) {
841 _setSSLError(NULL, 0, __FILE__, __LINE__);
842 goto fail1;
843 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000844 sn_obj = PyUnicode_FromStringAndSize(buf, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000845 if (sn_obj == NULL)
846 goto fail1;
847 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
848 Py_DECREF(sn_obj);
849 goto fail1;
850 }
851 Py_DECREF(sn_obj);
852
853 (void) BIO_reset(biobuf);
854 notBefore = X509_get_notBefore(certificate);
855 ASN1_TIME_print(biobuf, notBefore);
856 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
857 if (len < 0) {
858 _setSSLError(NULL, 0, __FILE__, __LINE__);
859 goto fail1;
860 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000861 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000862 if (pnotBefore == NULL)
863 goto fail1;
864 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
865 Py_DECREF(pnotBefore);
866 goto fail1;
867 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000868 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000869 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000870
871 (void) BIO_reset(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000872 notAfter = X509_get_notAfter(certificate);
Thomas Woutersed03b412007-08-28 21:37:11 +0000873 ASN1_TIME_print(biobuf, notAfter);
874 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000875 if (len < 0) {
876 _setSSLError(NULL, 0, __FILE__, __LINE__);
877 goto fail1;
878 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000879 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
Thomas Woutersed03b412007-08-28 21:37:11 +0000880 if (pnotAfter == NULL)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000881 goto fail1;
Thomas Woutersed03b412007-08-28 21:37:11 +0000882 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
883 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000884 goto fail1;
Thomas Woutersed03b412007-08-28 21:37:11 +0000885 }
886 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000887
888 /* Now look for subjectAltName */
889
890 peer_alt_names = _get_peer_alt_names(certificate);
891 if (peer_alt_names == NULL)
892 goto fail1;
893 else if (peer_alt_names != Py_None) {
894 if (PyDict_SetItemString(retval, "subjectAltName",
895 peer_alt_names) < 0) {
896 Py_DECREF(peer_alt_names);
897 goto fail1;
898 }
899 Py_DECREF(peer_alt_names);
900 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000901
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000902 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000903 return retval;
904
905 fail1:
906 if (biobuf != NULL)
907 BIO_free(biobuf);
908 fail0:
909 Py_XDECREF(retval);
910 return NULL;
911}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000912
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000913
914static PyObject *
915PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
916
917 PyObject *retval = NULL;
918 char *filename = NULL;
919 X509 *x=NULL;
920 BIO *cert;
921 int verbose = 1;
922
Bill Janssen6e027db2007-11-15 22:23:56 +0000923 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate",
924 &filename, &verbose))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000925 return NULL;
926
927 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000928 PyErr_SetString(PySSLErrorObject,
929 "Can't malloc memory to read file");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000930 goto fail0;
931 }
932
933 if (BIO_read_filename(cert,filename) <= 0) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000934 PyErr_SetString(PySSLErrorObject,
935 "Can't open file");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000936 goto fail0;
937 }
938
939 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
940 if (x == NULL) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000941 PyErr_SetString(PySSLErrorObject,
942 "Error decoding PEM-encoded file");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000943 goto fail0;
944 }
945
946 retval = _decode_certificate(x, verbose);
947
948 fail0:
Guido van Rossumf06628b2007-11-21 20:01:53 +0000949
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000950 if (cert != NULL) BIO_free(cert);
951 return retval;
952}
953
954
955static PyObject *
956PySSL_peercert(PySSLObject *self, PyObject *args)
957{
958 PyObject *retval = NULL;
959 int len;
960 int verification;
961 PyObject *binary_mode = Py_None;
962
963 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
964 return NULL;
965
966 if (!self->peer_cert)
967 Py_RETURN_NONE;
968
969 if (PyObject_IsTrue(binary_mode)) {
970 /* return cert in DER-encoded format */
971
972 unsigned char *bytes_buf = NULL;
973
974 bytes_buf = NULL;
975 len = i2d_X509(self->peer_cert, &bytes_buf);
976 if (len < 0) {
977 PySSL_SetError(self, len, __FILE__, __LINE__);
978 return NULL;
979 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000980 /* this is actually an immutable bytes sequence */
Guido van Rossumf06628b2007-11-21 20:01:53 +0000981 retval = PyString_FromStringAndSize
Bill Janssen6e027db2007-11-15 22:23:56 +0000982 ((const char *) bytes_buf, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000983 OPENSSL_free(bytes_buf);
984 return retval;
985
986 } else {
987
988 verification = SSL_CTX_get_verify_mode(self->ctx);
989 if ((verification & SSL_VERIFY_PEER) == 0)
990 return PyDict_New();
991 else
992 return _decode_certificate (self->peer_cert, 0);
993 }
994}
995
996PyDoc_STRVAR(PySSL_peercert_doc,
997"peer_certificate([der=False]) -> certificate\n\
998\n\
999Returns the certificate for the peer. If no certificate was provided,\n\
1000returns None. If a certificate was provided, but not validated, returns\n\
1001an empty dictionary. Otherwise returns a dict containing information\n\
1002about the peer certificate.\n\
1003\n\
1004If the optional argument is True, returns a DER-encoded copy of the\n\
1005peer certificate, or None if no certificate was provided. This will\n\
1006return the certificate even if it wasn't validated.");
1007
1008static PyObject *PySSL_cipher (PySSLObject *self) {
1009
1010 PyObject *retval, *v;
1011 SSL_CIPHER *current;
1012 char *cipher_name;
1013 char *cipher_protocol;
1014
1015 if (self->ssl == NULL)
1016 return Py_None;
1017 current = SSL_get_current_cipher(self->ssl);
1018 if (current == NULL)
1019 return Py_None;
1020
1021 retval = PyTuple_New(3);
1022 if (retval == NULL)
1023 return NULL;
1024
1025 cipher_name = (char *) SSL_CIPHER_get_name(current);
1026 if (cipher_name == NULL) {
1027 PyTuple_SET_ITEM(retval, 0, Py_None);
1028 } else {
Bill Janssen6e027db2007-11-15 22:23:56 +00001029 v = PyUnicode_FromString(cipher_name);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001030 if (v == NULL)
1031 goto fail0;
1032 PyTuple_SET_ITEM(retval, 0, v);
1033 }
1034 cipher_protocol = SSL_CIPHER_get_version(current);
1035 if (cipher_protocol == NULL) {
1036 PyTuple_SET_ITEM(retval, 1, Py_None);
1037 } else {
Bill Janssen6e027db2007-11-15 22:23:56 +00001038 v = PyUnicode_FromString(cipher_protocol);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001039 if (v == NULL)
1040 goto fail0;
1041 PyTuple_SET_ITEM(retval, 1, v);
1042 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001043 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001044 if (v == NULL)
1045 goto fail0;
1046 PyTuple_SET_ITEM(retval, 2, v);
1047 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001048
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001049 fail0:
1050 Py_DECREF(retval);
1051 return NULL;
1052}
1053
Guido van Rossum03b5c9a2007-12-06 18:39:46 +00001054/* GC support. */
1055static int
1056PySSL_traverse(PySSLObject *self, visitproc visit, void *arg)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001057{
Guido van Rossum03b5c9a2007-12-06 18:39:46 +00001058 Py_VISIT(self->Socket);
1059 return 0;
1060}
1061
1062static int
1063PySSL_clear(PySSLObject *self)
1064{
1065 Py_CLEAR(self->Socket);
1066 return 0;
1067}
1068
1069static void
1070PySSL_dealloc(PySSLObject *self)
1071{
1072 PyObject *o;
1073 PyObject *exc_type, *exc_value, *exc_tb;
1074
1075 PyErr_Fetch(&exc_type, &exc_value, &exc_tb);
1076 o = PyObject_CallMethod((PyObject*)self, "_real_close", NULL);
1077 Py_XDECREF(o);
1078 PyErr_Restore(exc_type, exc_value, exc_tb);
1079
1080 PyObject_GC_UnTrack(self);
Thomas Woutersed03b412007-08-28 21:37:11 +00001081 if (self->peer_cert) /* Possible not to have one? */
Guido van Rossum03b5c9a2007-12-06 18:39:46 +00001082 X509_free(self->peer_cert);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001083 if (self->ssl)
Thomas Woutersed03b412007-08-28 21:37:11 +00001084 SSL_free(self->ssl);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001085 if (self->ctx)
Thomas Woutersed03b412007-08-28 21:37:11 +00001086 SSL_CTX_free(self->ctx);
Guido van Rossum03b5c9a2007-12-06 18:39:46 +00001087 Py_CLEAR(self->Socket);
1088 Py_Type(self)->tp_free((PyObject *)self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001089}
1090
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001091/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001092 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001093 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001094 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001095
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001096static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001097check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001098{
1099 fd_set fds;
1100 struct timeval tv;
1101 int rc;
1102
1103 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001104 if (s->sock_timeout < 0.0)
1105 return SOCKET_IS_BLOCKING;
1106 else if (s->sock_timeout == 0.0)
1107 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001108
1109 /* Guard against closed socket */
1110 if (s->sock_fd < 0)
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001111 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001112
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001113 /* Prefer poll, if available, since you can poll() any fd
1114 * which can't be done with select(). */
1115#ifdef HAVE_POLL
1116 {
1117 struct pollfd pollfd;
1118 int timeout;
1119
1120 pollfd.fd = s->sock_fd;
1121 pollfd.events = writing ? POLLOUT : POLLIN;
1122
1123 /* s->sock_timeout is in seconds, timeout in ms */
1124 timeout = (int)(s->sock_timeout * 1000 + 0.5);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001125 PySSL_BEGIN_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001126 rc = poll(&pollfd, 1, timeout);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001127 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001128
1129 goto normal_return;
1130 }
1131#endif
1132
Neal Norwitz082b2df2006-02-07 07:04:46 +00001133 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001134#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Neal Norwitz082b2df2006-02-07 07:04:46 +00001135 if (s->sock_fd >= FD_SETSIZE)
Neal Norwitz389cea82006-02-13 00:35:21 +00001136 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001137#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001138
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001139 /* Construct the arguments to select */
1140 tv.tv_sec = (int)s->sock_timeout;
1141 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1142 FD_ZERO(&fds);
1143 FD_SET(s->sock_fd, &fds);
1144
1145 /* See if the socket is ready */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001146 PySSL_BEGIN_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001147 if (writing)
1148 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1149 else
1150 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001151 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001152
Bill Janssen6e027db2007-11-15 22:23:56 +00001153#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001154normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001155#endif
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001156 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1157 (when we are able to write or when there's something to read) */
1158 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001159}
1160
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001161static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1162{
1163 char *data;
1164 int len;
Martin v. Löwis405a7952003-10-27 14:24:37 +00001165 int count;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001166 int sockstate;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001167 int err;
Bill Janssen6e027db2007-11-15 22:23:56 +00001168 int nonblocking;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001169
Bill Janssen6e027db2007-11-15 22:23:56 +00001170 if (!PyArg_ParseTuple(args, "y#:write", &data, &count))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001171 return NULL;
1172
Bill Janssen6e027db2007-11-15 22:23:56 +00001173 /* just in case the blocking state of the socket has been changed */
1174 nonblocking = (self->Socket->sock_timeout >= 0.0);
1175 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1176 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1177
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001178 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1179 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001180 PyErr_SetString(PySSLErrorObject,
1181 "The write operation timed out");
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001182 return NULL;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001183 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001184 PyErr_SetString(PySSLErrorObject,
1185 "Underlying socket has been closed.");
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001186 return NULL;
Neal Norwitz389cea82006-02-13 00:35:21 +00001187 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001188 PyErr_SetString(PySSLErrorObject,
1189 "Underlying socket too large for select().");
Neal Norwitz082b2df2006-02-07 07:04:46 +00001190 return NULL;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001191 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001192 do {
1193 err = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001194 PySSL_BEGIN_ALLOW_THREADS
Martin v. Löwis405a7952003-10-27 14:24:37 +00001195 len = SSL_write(self->ssl, data, count);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001196 err = SSL_get_error(self->ssl, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001197 PySSL_END_ALLOW_THREADS
Martin v. Löwisafec8e32003-06-28 07:40:23 +00001198 if(PyErr_CheckSignals()) {
1199 return NULL;
1200 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001201 if (err == SSL_ERROR_WANT_READ) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001202 sockstate =
1203 check_socket_and_wait_for_timeout(self->Socket, 0);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001204 } else if (err == SSL_ERROR_WANT_WRITE) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001205 sockstate =
1206 check_socket_and_wait_for_timeout(self->Socket, 1);
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001207 } else {
1208 sockstate = SOCKET_OPERATION_OK;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001209 }
Thomas Woutersed03b412007-08-28 21:37:11 +00001210 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1211 PyErr_SetString(PySSLErrorObject,
1212 "The write operation timed out");
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001213 return NULL;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001214 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001215 PyErr_SetString(PySSLErrorObject,
1216 "Underlying socket has been closed.");
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001217 return NULL;
1218 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1219 break;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001220 }
1221 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001222 if (len > 0)
Christian Heimes217cfd12007-12-02 14:31:20 +00001223 return PyLong_FromLong(len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001224 else
Thomas Woutersed03b412007-08-28 21:37:11 +00001225 return PySSL_SetError(self, len, __FILE__, __LINE__);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001226}
1227
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001228PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001229"write(s) -> len\n\
1230\n\
1231Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001232of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001233
Bill Janssen6e027db2007-11-15 22:23:56 +00001234static PyObject *PySSL_SSLpending(PySSLObject *self)
1235{
1236 int count = 0;
1237
1238 PySSL_BEGIN_ALLOW_THREADS
1239 count = SSL_pending(self->ssl);
1240 PySSL_END_ALLOW_THREADS
1241 if (count < 0)
1242 return PySSL_SetError(self, count, __FILE__, __LINE__);
1243 else
Christian Heimes217cfd12007-12-02 14:31:20 +00001244 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001245}
1246
1247PyDoc_STRVAR(PySSL_SSLpending_doc,
1248"pending() -> count\n\
1249\n\
1250Returns the number of already decrypted bytes available for read,\n\
1251pending on the connection.\n");
1252
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001253static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1254{
Bill Janssen6e027db2007-11-15 22:23:56 +00001255 PyObject *buf = NULL;
1256 int buf_passed = 0;
1257 int count = -1;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001258 int len = 1024;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001259 int sockstate;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001260 int err;
Bill Janssen6e027db2007-11-15 22:23:56 +00001261 int nonblocking;
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;
1265
Bill Janssen6e027db2007-11-15 22:23:56 +00001266 if ((buf == NULL) || (buf == Py_None)) {
1267 if (!(buf = PyBytes_FromStringAndSize((char *) 0, len)))
1268 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00001269 } else if (PyLong_Check(buf)) {
1270 len = PyLong_AS_LONG(buf);
Bill Janssen6e027db2007-11-15 22:23:56 +00001271 if (!(buf = PyBytes_FromStringAndSize((char *) 0, len)))
1272 return NULL;
1273 } else {
1274 if (!PyBytes_Check(buf))
1275 return NULL;
1276 len = PyBytes_Size(buf);
1277 if ((count > 0) && (count <= len))
1278 len = count;
1279 buf_passed = 1;
1280 }
1281
1282 /* just in case the blocking state of the socket has been changed */
1283 nonblocking = (self->Socket->sock_timeout >= 0.0);
1284 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1285 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Thomas Woutersed03b412007-08-28 21:37:11 +00001286
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001287 /* first check if there are bytes ready to be read */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001288 PySSL_BEGIN_ALLOW_THREADS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001289 count = SSL_pending(self->ssl);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001290 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001291
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001292 if (!count) {
1293 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1294 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001295 PyErr_SetString(PySSLErrorObject,
1296 "The read operation timed out");
Bill Janssen6e027db2007-11-15 22:23:56 +00001297 if (!buf_passed) {
1298 Py_DECREF(buf);
1299 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001300 return NULL;
1301 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001302 PyErr_SetString(PySSLErrorObject,
1303 "Underlying socket too large for select().");
Bill Janssen6e027db2007-11-15 22:23:56 +00001304 if (!buf_passed) {
1305 Py_DECREF(buf);
1306 }
Thomas Woutersed03b412007-08-28 21:37:11 +00001307 Py_DECREF(buf);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001308 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001309 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001310 count = 0;
1311 goto done;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001312 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001313 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001314 do {
1315 err = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001316 PySSL_BEGIN_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001317 count = SSL_read(self->ssl, PyBytes_AsString(buf), len);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001318 err = SSL_get_error(self->ssl, count);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001319 PySSL_END_ALLOW_THREADS
Martin v. Löwisafec8e32003-06-28 07:40:23 +00001320 if(PyErr_CheckSignals()) {
Bill Janssen6e027db2007-11-15 22:23:56 +00001321 if (!buf_passed) {
1322 Py_DECREF(buf);
1323 }
Martin v. Löwisafec8e32003-06-28 07:40:23 +00001324 return NULL;
1325 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001326 if (err == SSL_ERROR_WANT_READ) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001327 sockstate =
1328 check_socket_and_wait_for_timeout(self->Socket, 0);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001329 } else if (err == SSL_ERROR_WANT_WRITE) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001330 sockstate =
1331 check_socket_and_wait_for_timeout(self->Socket, 1);
1332 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1333 (SSL_get_shutdown(self->ssl) ==
1334 SSL_RECEIVED_SHUTDOWN))
1335 {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001336 count = 0;
1337 goto done;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001338 } else {
1339 sockstate = SOCKET_OPERATION_OK;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001340 }
Thomas Woutersed03b412007-08-28 21:37:11 +00001341 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1342 PyErr_SetString(PySSLErrorObject,
1343 "The read operation timed out");
Bill Janssen6e027db2007-11-15 22:23:56 +00001344 if (!buf_passed) {
1345 Py_DECREF(buf);
1346 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001347 return NULL;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001348 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1349 break;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001350 }
1351 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Thomas Woutersed03b412007-08-28 21:37:11 +00001352 if (count <= 0) {
Bill Janssen6e027db2007-11-15 22:23:56 +00001353 if (!buf_passed) {
1354 Py_DECREF(buf);
1355 }
Thomas Woutersed03b412007-08-28 21:37:11 +00001356 return PySSL_SetError(self, count, __FILE__, __LINE__);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001357 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001358 done:
Bill Janssen6e027db2007-11-15 22:23:56 +00001359 if (!buf_passed) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001360 PyObject *res = PyString_FromStringAndSize(
1361 PyBytes_AS_STRING(buf), count);
1362 Py_DECREF(buf);
1363 return res;
Bill Janssen6e027db2007-11-15 22:23:56 +00001364 } else {
Christian Heimes217cfd12007-12-02 14:31:20 +00001365 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001366 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001367}
1368
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001369PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001370"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001371\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001372Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001373
1374static PyMethodDef PySSLMethods[] = {
Bill Janssen6e027db2007-11-15 22:23:56 +00001375 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001376 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001377 PySSL_SSLwrite_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001378 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001379 PySSL_SSLread_doc},
Bill Janssen6e027db2007-11-15 22:23:56 +00001380 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1381 PySSL_SSLpending_doc},
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001382 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1383 PySSL_peercert_doc},
1384 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001385 {NULL, NULL}
1386};
1387
Jeremy Hylton938ace62002-07-17 16:30:39 +00001388static PyTypeObject PySSL_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001389 PyVarObject_HEAD_INIT(NULL, 0)
Guido van Rossum03b5c9a2007-12-06 18:39:46 +00001390 "_ssl.SSLContext", /*tp_name*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001391 sizeof(PySSLObject), /*tp_basicsize*/
1392 0, /*tp_itemsize*/
1393 /* methods */
1394 (destructor)PySSL_dealloc, /*tp_dealloc*/
1395 0, /*tp_print*/
Guido van Rossum03b5c9a2007-12-06 18:39:46 +00001396 0, /*tp_getattr*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001397 0, /*tp_setattr*/
1398 0, /*tp_compare*/
1399 0, /*tp_repr*/
1400 0, /*tp_as_number*/
1401 0, /*tp_as_sequence*/
1402 0, /*tp_as_mapping*/
1403 0, /*tp_hash*/
Guido van Rossum03b5c9a2007-12-06 18:39:46 +00001404 0, /* tp_call */
1405 0, /* tp_str */
1406 PyObject_GenericGetAttr, /* tp_getattro */
1407 0, /* tp_setattro */
1408 0, /* tp_as_buffer */
1409 Py_TPFLAGS_DEFAULT |
1410 Py_TPFLAGS_HAVE_GC, /* tp_flags */
1411 0, /* tp_doc */
1412 (traverseproc)PySSL_traverse, /* tp_traverse */
1413 (inquiry)PySSL_clear, /* tp_clear */
1414 0, /* tp_richcompare */
1415 0, /* tp_weaklistoffset */
1416 0, /* tp_iter */
1417 0, /* tp_iternext */
1418 PySSLMethods, /* tp_methods */
1419 0, /* tp_members */
1420 0, /* tp_getset */
1421 0, /* tp_base */
1422 0, /* tp_dict */
1423 0, /* tp_descr_get */
1424 0, /* tp_descr_set */
1425 0, /* tp_dictoffset */
1426 0, /* tp_init */
1427 PyType_GenericAlloc, /* tp_alloc */
1428 PyType_GenericNew, /* tp_new */
1429 PyObject_GC_Del, /* tp_free */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001430};
1431
1432#ifdef HAVE_OPENSSL_RAND
1433
1434/* helper routines for seeding the SSL PRNG */
1435static PyObject *
1436PySSL_RAND_add(PyObject *self, PyObject *args)
1437{
1438 char *buf;
1439 int len;
1440 double entropy;
1441
1442 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
1443 return NULL;
1444 RAND_add(buf, len, entropy);
1445 Py_INCREF(Py_None);
1446 return Py_None;
1447}
1448
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001449PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001450"RAND_add(string, entropy)\n\
1451\n\
1452Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001453bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001454
1455static PyObject *
1456PySSL_RAND_status(PyObject *self)
1457{
Christian Heimes217cfd12007-12-02 14:31:20 +00001458 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001459}
1460
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001461PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001462"RAND_status() -> 0 or 1\n\
1463\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001464Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1465It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1466using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001467
1468static PyObject *
1469PySSL_RAND_egd(PyObject *self, PyObject *arg)
1470{
1471 int bytes;
1472
Bill Janssen6e027db2007-11-15 22:23:56 +00001473 if (!PyUnicode_Check(arg))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001474 return PyErr_Format(PyExc_TypeError,
1475 "RAND_egd() expected string, found %s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001476 Py_Type(arg)->tp_name);
Bill Janssen6e027db2007-11-15 22:23:56 +00001477 bytes = RAND_egd(PyUnicode_AsString(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001478 if (bytes == -1) {
1479 PyErr_SetString(PySSLErrorObject,
1480 "EGD connection failed or EGD did not return "
1481 "enough data to seed the PRNG");
1482 return NULL;
1483 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001484 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001485}
1486
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001487PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001488"RAND_egd(path) -> bytes\n\
1489\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001490Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1491Returns number of bytes read. Raises SSLError if connection to EGD\n\
1492fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001493
1494#endif
1495
1496/* List of functions exported by this module. */
1497
1498static PyMethodDef PySSL_methods[] = {
Thomas Woutersed03b412007-08-28 21:37:11 +00001499 {"sslwrap", PySSL_sslwrap,
1500 METH_VARARGS, ssl_doc},
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001501 {"_test_decode_cert", PySSL_test_decode_certificate,
1502 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001503#ifdef HAVE_OPENSSL_RAND
Thomas Woutersed03b412007-08-28 21:37:11 +00001504 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001505 PySSL_RAND_add_doc},
1506 {"RAND_egd", PySSL_RAND_egd, METH_O,
1507 PySSL_RAND_egd_doc},
1508 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1509 PySSL_RAND_status_doc},
1510#endif
Thomas Woutersed03b412007-08-28 21:37:11 +00001511 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001512};
1513
1514
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001515#ifdef WITH_THREAD
1516
1517/* an implementation of OpenSSL threading operations in terms
1518 of the Python C thread library */
1519
1520static PyThread_type_lock *_ssl_locks = NULL;
1521
1522static unsigned long _ssl_thread_id_function (void) {
1523 return PyThread_get_thread_ident();
1524}
1525
Bill Janssen6e027db2007-11-15 22:23:56 +00001526static void _ssl_thread_locking_function
1527 (int mode, int n, const char *file, int line) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001528 /* this function is needed to perform locking on shared data
1529 structures. (Note that OpenSSL uses a number of global data
Bill Janssen6e027db2007-11-15 22:23:56 +00001530 structures that will be implicitly shared whenever multiple
1531 threads use OpenSSL.) Multi-threaded applications will
1532 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001533
Bill Janssen6e027db2007-11-15 22:23:56 +00001534 locking_function() must be able to handle up to
1535 CRYPTO_num_locks() different mutex locks. It sets the n-th
1536 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001537
1538 file and line are the file number of the function setting the
1539 lock. They can be useful for debugging.
1540 */
1541
1542 if ((_ssl_locks == NULL) ||
1543 (n < 0) || (n >= _ssl_locks_count))
1544 return;
1545
1546 if (mode & CRYPTO_LOCK) {
1547 PyThread_acquire_lock(_ssl_locks[n], 1);
1548 } else {
1549 PyThread_release_lock(_ssl_locks[n]);
1550 }
1551}
1552
1553static int _setup_ssl_threads(void) {
1554
1555 int i;
1556
1557 if (_ssl_locks == NULL) {
1558 _ssl_locks_count = CRYPTO_num_locks();
1559 _ssl_locks = (PyThread_type_lock *)
1560 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1561 if (_ssl_locks == NULL)
1562 return 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001563 memset(_ssl_locks, 0,
1564 sizeof(PyThread_type_lock) * _ssl_locks_count);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001565 for (i = 0; i < _ssl_locks_count; i++) {
1566 _ssl_locks[i] = PyThread_allocate_lock();
1567 if (_ssl_locks[i] == NULL) {
1568 int j;
1569 for (j = 0; j < i; j++) {
1570 PyThread_free_lock(_ssl_locks[j]);
1571 }
1572 free(_ssl_locks);
1573 return 0;
1574 }
1575 }
1576 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1577 CRYPTO_set_id_callback(_ssl_thread_id_function);
1578 }
1579 return 1;
1580}
1581
1582#endif /* def HAVE_THREAD */
1583
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001584PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001585"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001586for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001587
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001588PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001589init_ssl(void)
1590{
1591 PyObject *m, *d;
1592
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001593 Py_Type(&PySSL_Type) = &PyType_Type;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001594
1595 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001596 if (m == NULL)
1597 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001598 d = PyModule_GetDict(m);
1599
1600 /* Load _socket module and its C API */
1601 if (PySocketModule_ImportModuleAndAPI())
Thomas Woutersed03b412007-08-28 21:37:11 +00001602 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001603
1604 /* Init OpenSSL */
1605 SSL_load_error_strings();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001606#ifdef WITH_THREAD
1607 /* note that this will start threading if not already started */
1608 if (!_setup_ssl_threads()) {
1609 return;
1610 }
1611#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001612 SSLeay_add_ssl_algorithms();
1613
1614 /* Add symbols to module dict */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001615 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
Thomas Woutersed03b412007-08-28 21:37:11 +00001616 PySocketModule.error,
1617 NULL);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001618 if (PySSLErrorObject == NULL)
1619 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001620 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
Thomas Woutersed03b412007-08-28 21:37:11 +00001621 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001622 if (PyDict_SetItemString(d, "SSLType",
1623 (PyObject *)&PySSL_Type) != 0)
1624 return;
1625 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001626 PY_SSL_ERROR_ZERO_RETURN);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001627 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001628 PY_SSL_ERROR_WANT_READ);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001629 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001630 PY_SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001631 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001632 PY_SSL_ERROR_WANT_X509_LOOKUP);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001633 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001634 PY_SSL_ERROR_SYSCALL);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001635 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001636 PY_SSL_ERROR_SSL);
1637 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1638 PY_SSL_ERROR_WANT_CONNECT);
1639 /* non ssl.h errorcodes */
1640 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1641 PY_SSL_ERROR_EOF);
1642 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1643 PY_SSL_ERROR_INVALID_ERROR_CODE);
Thomas Woutersed03b412007-08-28 21:37:11 +00001644 /* cert requirements */
1645 PyModule_AddIntConstant(m, "CERT_NONE",
1646 PY_SSL_CERT_NONE);
1647 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1648 PY_SSL_CERT_OPTIONAL);
1649 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1650 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001651
Thomas Woutersed03b412007-08-28 21:37:11 +00001652 /* protocol versions */
1653 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1654 PY_SSL_VERSION_SSL2);
1655 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1656 PY_SSL_VERSION_SSL3);
1657 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1658 PY_SSL_VERSION_SSL23);
1659 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1660 PY_SSL_VERSION_TLS1);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001661}