blob: 64f4578f74652c0e8ad2de10612343940331a1e5 [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
269 self = PyObject_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);
388 return self;
389 fail:
390 if (errstr)
391 PyErr_SetString(PySSLErrorObject, errstr);
392 Py_DECREF(self);
393 return NULL;
394}
395
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000396static PyObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000397PySSL_sslwrap(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000398{
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000399 PySocketSockObject *Sock;
Thomas Woutersed03b412007-08-28 21:37:11 +0000400 int server_side = 0;
401 int verification_mode = PY_SSL_CERT_NONE;
402 int protocol = PY_SSL_VERSION_SSL23;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000403 char *key_file = NULL;
404 char *cert_file = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000405 char *cacerts_file = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000406
Thomas Woutersed03b412007-08-28 21:37:11 +0000407 if (!PyArg_ParseTuple(args, "O!i|zziiz:sslwrap",
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000408 PySocketModule.Sock_Type,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000409 &Sock,
Thomas Woutersed03b412007-08-28 21:37:11 +0000410 &server_side,
411 &key_file, &cert_file,
412 &verification_mode, &protocol,
413 &cacerts_file))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000414 return NULL;
415
Thomas Woutersed03b412007-08-28 21:37:11 +0000416 /*
417 fprintf(stderr,
418 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
419 "protocol %d, certs %p\n",
420 server_side, key_file, cert_file, verification_mode,
421 protocol, cacerts_file);
422 */
423
424 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
425 server_side, verification_mode,
426 protocol, cacerts_file);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000427}
428
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000429PyDoc_STRVAR(ssl_doc,
Thomas Woutersed03b412007-08-28 21:37:11 +0000430"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
431" cacertsfile]) -> sslobject");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000432
433/* SSL object methods */
434
Bill Janssen6e027db2007-11-15 22:23:56 +0000435static PyObject *PySSL_SSLdo_handshake(PySSLObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000436{
Bill Janssen6e027db2007-11-15 22:23:56 +0000437 int ret;
438 int err;
439 int sockstate;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000440
Bill Janssen6e027db2007-11-15 22:23:56 +0000441 /* Actually negotiate SSL connection */
442 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
443 sockstate = 0;
444 do {
445 PySSL_BEGIN_ALLOW_THREADS
446 ret = SSL_do_handshake(self->ssl);
447 err = SSL_get_error(self->ssl, ret);
448 PySSL_END_ALLOW_THREADS
449 if(PyErr_CheckSignals()) {
450 return NULL;
451 }
452 if (err == SSL_ERROR_WANT_READ) {
453 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
454 } else if (err == SSL_ERROR_WANT_WRITE) {
455 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
456 } else {
457 sockstate = SOCKET_OPERATION_OK;
458 }
459 if (sockstate == SOCKET_HAS_TIMED_OUT) {
460 PyErr_SetString(PySSLErrorObject,
461 ERRSTR("The handshake operation timed out"));
462 return NULL;
463 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
464 PyErr_SetString(PySSLErrorObject,
465 ERRSTR("Underlying socket has been closed."));
466 return NULL;
467 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
468 PyErr_SetString(PySSLErrorObject,
469 ERRSTR("Underlying socket too large for select()."));
470 return NULL;
471 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
472 break;
473 }
474 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
475 if (ret < 1)
476 return PySSL_SetError(self, ret, __FILE__, __LINE__);
477 self->ssl->debug = 1;
478
479 if (self->peer_cert)
480 X509_free (self->peer_cert);
481 PySSL_BEGIN_ALLOW_THREADS
482 self->peer_cert = SSL_get_peer_certificate(self->ssl);
483 PySSL_END_ALLOW_THREADS
484
485 Py_INCREF(Py_None);
486 return Py_None;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000487}
488
Thomas Woutersed03b412007-08-28 21:37:11 +0000489static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000490_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000491
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000492 char namebuf[X509_NAME_MAXLEN];
493 int buflen;
494 PyObject *name_obj;
495 PyObject *value_obj;
496 PyObject *attr;
497 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000498
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000499 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
500 if (buflen < 0) {
501 _setSSLError(NULL, 0, __FILE__, __LINE__);
502 goto fail;
Thomas Woutersed03b412007-08-28 21:37:11 +0000503 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000504 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000505 if (name_obj == NULL)
506 goto fail;
507
508 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
509 if (buflen < 0) {
510 _setSSLError(NULL, 0, __FILE__, __LINE__);
511 Py_DECREF(name_obj);
512 goto fail;
513 }
514 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
515 buflen, "strict");
516 OPENSSL_free(valuebuf);
517 if (value_obj == NULL) {
518 Py_DECREF(name_obj);
519 goto fail;
520 }
521 attr = PyTuple_New(2);
522 if (attr == NULL) {
523 Py_DECREF(name_obj);
524 Py_DECREF(value_obj);
525 goto fail;
526 }
527 PyTuple_SET_ITEM(attr, 0, name_obj);
528 PyTuple_SET_ITEM(attr, 1, value_obj);
529 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000530
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000531 fail:
Thomas Woutersed03b412007-08-28 21:37:11 +0000532 return NULL;
533}
534
535static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000536_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000537{
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000538 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
539 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
540 PyObject *rdnt;
541 PyObject *attr = NULL; /* tuple to hold an attribute */
542 int entry_count = X509_NAME_entry_count(xname);
543 X509_NAME_ENTRY *entry;
544 ASN1_OBJECT *name;
545 ASN1_STRING *value;
546 int index_counter;
547 int rdn_level = -1;
548 int retcode;
549
550 dn = PyList_New(0);
551 if (dn == NULL)
552 return NULL;
553 /* now create another tuple to hold the top-level RDN */
554 rdn = PyList_New(0);
555 if (rdn == NULL)
556 goto fail0;
557
558 for (index_counter = 0;
559 index_counter < entry_count;
560 index_counter++)
561 {
562 entry = X509_NAME_get_entry(xname, index_counter);
563
564 /* check to see if we've gotten to a new RDN */
565 if (rdn_level >= 0) {
566 if (rdn_level != entry->set) {
567 /* yes, new RDN */
568 /* add old RDN to DN */
569 rdnt = PyList_AsTuple(rdn);
570 Py_DECREF(rdn);
571 if (rdnt == NULL)
572 goto fail0;
573 retcode = PyList_Append(dn, rdnt);
574 Py_DECREF(rdnt);
575 if (retcode < 0)
576 goto fail0;
577 /* create new RDN */
578 rdn = PyList_New(0);
579 if (rdn == NULL)
580 goto fail0;
581 }
582 }
583 rdn_level = entry->set;
584
585 /* now add this attribute to the current RDN */
586 name = X509_NAME_ENTRY_get_object(entry);
587 value = X509_NAME_ENTRY_get_data(entry);
588 attr = _create_tuple_for_attribute(name, value);
589 /*
590 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
591 entry->set,
592 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
593 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
594 */
595 if (attr == NULL)
596 goto fail1;
597 retcode = PyList_Append(rdn, attr);
598 Py_DECREF(attr);
599 if (retcode < 0)
600 goto fail1;
601 }
602 /* now, there's typically a dangling RDN */
603 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
604 rdnt = PyList_AsTuple(rdn);
605 Py_DECREF(rdn);
606 if (rdnt == NULL)
607 goto fail0;
608 retcode = PyList_Append(dn, rdnt);
609 Py_DECREF(rdnt);
610 if (retcode < 0)
611 goto fail0;
612 }
613
614 /* convert list to tuple */
615 rdnt = PyList_AsTuple(dn);
616 Py_DECREF(dn);
617 if (rdnt == NULL)
618 return NULL;
619 return rdnt;
620
621 fail1:
622 Py_XDECREF(rdn);
623
624 fail0:
625 Py_XDECREF(dn);
626 return NULL;
627}
628
629static PyObject *
630_get_peer_alt_names (X509 *certificate) {
631
632 /* this code follows the procedure outlined in
633 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
634 function to extract the STACK_OF(GENERAL_NAME),
635 then iterates through the stack to add the
636 names. */
637
638 int i, j;
639 PyObject *peer_alt_names = Py_None;
640 PyObject *v, *t;
641 X509_EXTENSION *ext = NULL;
642 GENERAL_NAMES *names = NULL;
643 GENERAL_NAME *name;
644 X509V3_EXT_METHOD *method;
645 BIO *biobuf = NULL;
646 char buf[2048];
647 char *vptr;
648 int len;
649 unsigned char *p;
650
651 if (certificate == NULL)
652 return peer_alt_names;
653
654 /* get a memory buffer */
655 biobuf = BIO_new(BIO_s_mem());
656
657 i = 0;
658 while ((i = X509_get_ext_by_NID(
659 certificate, NID_subject_alt_name, i)) >= 0) {
660
661 if (peer_alt_names == Py_None) {
662 peer_alt_names = PyList_New(0);
663 if (peer_alt_names == NULL)
664 goto fail;
665 }
666
667 /* now decode the altName */
668 ext = X509_get_ext(certificate, i);
669 if(!(method = X509V3_EXT_get(ext))) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000670 PyErr_SetString
671 (PySSLErrorObject,
672 ERRSTR("No method for internalizing subjectAltName!"));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000673 goto fail;
674 }
675
676 p = ext->value->data;
677 if(method->it)
Bill Janssen6e027db2007-11-15 22:23:56 +0000678 names = (GENERAL_NAMES*)
679 (ASN1_item_d2i(NULL,
680 &p,
681 ext->value->length,
682 ASN1_ITEM_ptr(method->it)));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000683 else
Bill Janssen6e027db2007-11-15 22:23:56 +0000684 names = (GENERAL_NAMES*)
685 (method->d2i(NULL,
686 &p,
687 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000688
689 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
690
691 /* get a rendering of each name in the set of names */
692
693 name = sk_GENERAL_NAME_value(names, j);
694 if (name->type == GEN_DIRNAME) {
695
Bill Janssen6e027db2007-11-15 22:23:56 +0000696 /* we special-case DirName as a tuple of
697 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000698
699 t = PyTuple_New(2);
700 if (t == NULL) {
701 goto fail;
702 }
703
Bill Janssen6e027db2007-11-15 22:23:56 +0000704 v = PyUnicode_FromString("DirName");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000705 if (v == NULL) {
706 Py_DECREF(t);
707 goto fail;
708 }
709 PyTuple_SET_ITEM(t, 0, v);
710
711 v = _create_tuple_for_X509_NAME (name->d.dirn);
712 if (v == NULL) {
713 Py_DECREF(t);
714 goto fail;
715 }
716 PyTuple_SET_ITEM(t, 1, v);
717
718 } else {
719
720 /* for everything else, we use the OpenSSL print form */
721
722 (void) BIO_reset(biobuf);
723 GENERAL_NAME_print(biobuf, name);
724 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
725 if (len < 0) {
726 _setSSLError(NULL, 0, __FILE__, __LINE__);
727 goto fail;
728 }
729 vptr = strchr(buf, ':');
730 if (vptr == NULL)
731 goto fail;
732 t = PyTuple_New(2);
733 if (t == NULL)
734 goto fail;
Bill Janssen6e027db2007-11-15 22:23:56 +0000735 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000736 if (v == NULL) {
737 Py_DECREF(t);
738 goto fail;
739 }
740 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen6e027db2007-11-15 22:23:56 +0000741 v = PyUnicode_FromStringAndSize((vptr + 1),
742 (len - (vptr - buf + 1)));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000743 if (v == NULL) {
744 Py_DECREF(t);
745 goto fail;
746 }
747 PyTuple_SET_ITEM(t, 1, v);
748 }
749
750 /* and add that rendering to the list */
751
752 if (PyList_Append(peer_alt_names, t) < 0) {
753 Py_DECREF(t);
754 goto fail;
755 }
756 Py_DECREF(t);
757 }
758 }
759 BIO_free(biobuf);
760 if (peer_alt_names != Py_None) {
761 v = PyList_AsTuple(peer_alt_names);
762 Py_DECREF(peer_alt_names);
763 return v;
764 } else {
765 return peer_alt_names;
766 }
767
768
769 fail:
770 if (biobuf != NULL)
771 BIO_free(biobuf);
772
773 if (peer_alt_names != Py_None) {
774 Py_XDECREF(peer_alt_names);
775 }
776
777 return NULL;
778}
779
780static PyObject *
781_decode_certificate (X509 *certificate, int verbose) {
782
Thomas Woutersed03b412007-08-28 21:37:11 +0000783 PyObject *retval = NULL;
784 BIO *biobuf = NULL;
785 PyObject *peer;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000786 PyObject *peer_alt_names = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000787 PyObject *issuer;
788 PyObject *version;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000789 PyObject *sn_obj;
790 ASN1_INTEGER *serialNumber;
Thomas Woutersed03b412007-08-28 21:37:11 +0000791 char buf[2048];
792 int len;
793 ASN1_TIME *notBefore, *notAfter;
794 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000795
796 retval = PyDict_New();
797 if (retval == NULL)
798 return NULL;
799
Thomas Wouters89d996e2007-09-08 17:39:28 +0000800 peer = _create_tuple_for_X509_NAME(
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000801 X509_get_subject_name(certificate));
Thomas Woutersed03b412007-08-28 21:37:11 +0000802 if (peer == NULL)
803 goto fail0;
804 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
805 Py_DECREF(peer);
806 goto fail0;
807 }
808 Py_DECREF(peer);
809
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000810 if (verbose) {
811 issuer = _create_tuple_for_X509_NAME(
812 X509_get_issuer_name(certificate));
813 if (issuer == NULL)
814 goto fail0;
815 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
816 Py_DECREF(issuer);
817 goto fail0;
818 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000819 Py_DECREF(issuer);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000820
821 version = PyInt_FromLong(X509_get_version(certificate) + 1);
822 if (PyDict_SetItemString(retval, "version", version) < 0) {
823 Py_DECREF(version);
824 goto fail0;
825 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000826 Py_DECREF(version);
Thomas Woutersed03b412007-08-28 21:37:11 +0000827 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000828
Thomas Woutersed03b412007-08-28 21:37:11 +0000829 /* get a memory buffer */
830 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000831
832 if (verbose) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000833
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000834 (void) BIO_reset(biobuf);
835 serialNumber = X509_get_serialNumber(certificate);
836 /* should not exceed 20 octets, 160 bits, so buf is big enough */
837 i2a_ASN1_INTEGER(biobuf, serialNumber);
838 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
839 if (len < 0) {
840 _setSSLError(NULL, 0, __FILE__, __LINE__);
841 goto fail1;
842 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000843 sn_obj = PyUnicode_FromStringAndSize(buf, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000844 if (sn_obj == NULL)
845 goto fail1;
846 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
847 Py_DECREF(sn_obj);
848 goto fail1;
849 }
850 Py_DECREF(sn_obj);
851
852 (void) BIO_reset(biobuf);
853 notBefore = X509_get_notBefore(certificate);
854 ASN1_TIME_print(biobuf, notBefore);
855 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
856 if (len < 0) {
857 _setSSLError(NULL, 0, __FILE__, __LINE__);
858 goto fail1;
859 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000860 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000861 if (pnotBefore == NULL)
862 goto fail1;
863 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
864 Py_DECREF(pnotBefore);
865 goto fail1;
866 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000867 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000868 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000869
870 (void) BIO_reset(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000871 notAfter = X509_get_notAfter(certificate);
Thomas Woutersed03b412007-08-28 21:37:11 +0000872 ASN1_TIME_print(biobuf, notAfter);
873 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000874 if (len < 0) {
875 _setSSLError(NULL, 0, __FILE__, __LINE__);
876 goto fail1;
877 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000878 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
Thomas Woutersed03b412007-08-28 21:37:11 +0000879 if (pnotAfter == NULL)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000880 goto fail1;
Thomas Woutersed03b412007-08-28 21:37:11 +0000881 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
882 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000883 goto fail1;
Thomas Woutersed03b412007-08-28 21:37:11 +0000884 }
885 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000886
887 /* Now look for subjectAltName */
888
889 peer_alt_names = _get_peer_alt_names(certificate);
890 if (peer_alt_names == NULL)
891 goto fail1;
892 else if (peer_alt_names != Py_None) {
893 if (PyDict_SetItemString(retval, "subjectAltName",
894 peer_alt_names) < 0) {
895 Py_DECREF(peer_alt_names);
896 goto fail1;
897 }
898 Py_DECREF(peer_alt_names);
899 }
900
901 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000902 return retval;
903
904 fail1:
905 if (biobuf != NULL)
906 BIO_free(biobuf);
907 fail0:
908 Py_XDECREF(retval);
909 return NULL;
910}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000911
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000912
913static PyObject *
914PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
915
916 PyObject *retval = NULL;
917 char *filename = NULL;
918 X509 *x=NULL;
919 BIO *cert;
920 int verbose = 1;
921
Bill Janssen6e027db2007-11-15 22:23:56 +0000922 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate",
923 &filename, &verbose))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000924 return NULL;
925
926 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000927 PyErr_SetString(PySSLErrorObject,
928 "Can't malloc memory to read file");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000929 goto fail0;
930 }
931
932 if (BIO_read_filename(cert,filename) <= 0) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000933 PyErr_SetString(PySSLErrorObject,
934 "Can't open file");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000935 goto fail0;
936 }
937
938 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
939 if (x == NULL) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000940 PyErr_SetString(PySSLErrorObject,
941 "Error decoding PEM-encoded file");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000942 goto fail0;
943 }
944
945 retval = _decode_certificate(x, verbose);
946
947 fail0:
948
949 if (cert != NULL) BIO_free(cert);
950 return retval;
951}
952
953
954static PyObject *
955PySSL_peercert(PySSLObject *self, PyObject *args)
956{
957 PyObject *retval = NULL;
958 int len;
959 int verification;
960 PyObject *binary_mode = Py_None;
961
962 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
963 return NULL;
964
965 if (!self->peer_cert)
966 Py_RETURN_NONE;
967
968 if (PyObject_IsTrue(binary_mode)) {
969 /* return cert in DER-encoded format */
970
971 unsigned char *bytes_buf = NULL;
972
973 bytes_buf = NULL;
974 len = i2d_X509(self->peer_cert, &bytes_buf);
975 if (len < 0) {
976 PySSL_SetError(self, len, __FILE__, __LINE__);
977 return NULL;
978 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000979 /* this is actually an immutable bytes sequence */
980 retval = PyBytes_FromStringAndSize
981 ((const char *) bytes_buf, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000982 OPENSSL_free(bytes_buf);
983 return retval;
984
985 } else {
986
987 verification = SSL_CTX_get_verify_mode(self->ctx);
988 if ((verification & SSL_VERIFY_PEER) == 0)
989 return PyDict_New();
990 else
991 return _decode_certificate (self->peer_cert, 0);
992 }
993}
994
995PyDoc_STRVAR(PySSL_peercert_doc,
996"peer_certificate([der=False]) -> certificate\n\
997\n\
998Returns the certificate for the peer. If no certificate was provided,\n\
999returns None. If a certificate was provided, but not validated, returns\n\
1000an empty dictionary. Otherwise returns a dict containing information\n\
1001about the peer certificate.\n\
1002\n\
1003If the optional argument is True, returns a DER-encoded copy of the\n\
1004peer certificate, or None if no certificate was provided. This will\n\
1005return the certificate even if it wasn't validated.");
1006
1007static PyObject *PySSL_cipher (PySSLObject *self) {
1008
1009 PyObject *retval, *v;
1010 SSL_CIPHER *current;
1011 char *cipher_name;
1012 char *cipher_protocol;
1013
1014 if (self->ssl == NULL)
1015 return Py_None;
1016 current = SSL_get_current_cipher(self->ssl);
1017 if (current == NULL)
1018 return Py_None;
1019
1020 retval = PyTuple_New(3);
1021 if (retval == NULL)
1022 return NULL;
1023
1024 cipher_name = (char *) SSL_CIPHER_get_name(current);
1025 if (cipher_name == NULL) {
1026 PyTuple_SET_ITEM(retval, 0, Py_None);
1027 } else {
Bill Janssen6e027db2007-11-15 22:23:56 +00001028 v = PyUnicode_FromString(cipher_name);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001029 if (v == NULL)
1030 goto fail0;
1031 PyTuple_SET_ITEM(retval, 0, v);
1032 }
1033 cipher_protocol = SSL_CIPHER_get_version(current);
1034 if (cipher_protocol == NULL) {
1035 PyTuple_SET_ITEM(retval, 1, Py_None);
1036 } else {
Bill Janssen6e027db2007-11-15 22:23:56 +00001037 v = PyUnicode_FromString(cipher_protocol);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001038 if (v == NULL)
1039 goto fail0;
1040 PyTuple_SET_ITEM(retval, 1, v);
1041 }
1042 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1043 if (v == NULL)
1044 goto fail0;
1045 PyTuple_SET_ITEM(retval, 2, v);
1046 return retval;
1047
1048 fail0:
1049 Py_DECREF(retval);
1050 return NULL;
1051}
1052
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001053static void PySSL_dealloc(PySSLObject *self)
1054{
Thomas Woutersed03b412007-08-28 21:37:11 +00001055 if (self->peer_cert) /* Possible not to have one? */
1056 X509_free (self->peer_cert);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001057 if (self->ssl)
Thomas Woutersed03b412007-08-28 21:37:11 +00001058 SSL_free(self->ssl);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001059 if (self->ctx)
Thomas Woutersed03b412007-08-28 21:37:11 +00001060 SSL_CTX_free(self->ctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001061 Py_XDECREF(self->Socket);
1062 PyObject_Del(self);
1063}
1064
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001065/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001066 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001067 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001068 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001069
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001070static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001071check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001072{
1073 fd_set fds;
1074 struct timeval tv;
1075 int rc;
1076
1077 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001078 if (s->sock_timeout < 0.0)
1079 return SOCKET_IS_BLOCKING;
1080 else if (s->sock_timeout == 0.0)
1081 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001082
1083 /* Guard against closed socket */
1084 if (s->sock_fd < 0)
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001085 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001086
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001087 /* Prefer poll, if available, since you can poll() any fd
1088 * which can't be done with select(). */
1089#ifdef HAVE_POLL
1090 {
1091 struct pollfd pollfd;
1092 int timeout;
1093
1094 pollfd.fd = s->sock_fd;
1095 pollfd.events = writing ? POLLOUT : POLLIN;
1096
1097 /* s->sock_timeout is in seconds, timeout in ms */
1098 timeout = (int)(s->sock_timeout * 1000 + 0.5);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001099 PySSL_BEGIN_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001100 rc = poll(&pollfd, 1, timeout);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001101 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001102
1103 goto normal_return;
1104 }
1105#endif
1106
Neal Norwitz082b2df2006-02-07 07:04:46 +00001107 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001108#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Neal Norwitz082b2df2006-02-07 07:04:46 +00001109 if (s->sock_fd >= FD_SETSIZE)
Neal Norwitz389cea82006-02-13 00:35:21 +00001110 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001111#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001112
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001113 /* Construct the arguments to select */
1114 tv.tv_sec = (int)s->sock_timeout;
1115 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1116 FD_ZERO(&fds);
1117 FD_SET(s->sock_fd, &fds);
1118
1119 /* See if the socket is ready */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001120 PySSL_BEGIN_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001121 if (writing)
1122 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1123 else
1124 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001125 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001126
Bill Janssen6e027db2007-11-15 22:23:56 +00001127#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001128normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001129#endif
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001130 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1131 (when we are able to write or when there's something to read) */
1132 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001133}
1134
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001135static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1136{
1137 char *data;
1138 int len;
Martin v. Löwis405a7952003-10-27 14:24:37 +00001139 int count;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001140 int sockstate;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001141 int err;
Bill Janssen6e027db2007-11-15 22:23:56 +00001142 int nonblocking;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001143
Bill Janssen6e027db2007-11-15 22:23:56 +00001144 if (!PyArg_ParseTuple(args, "y#:write", &data, &count))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001145 return NULL;
1146
Bill Janssen6e027db2007-11-15 22:23:56 +00001147 /* just in case the blocking state of the socket has been changed */
1148 nonblocking = (self->Socket->sock_timeout >= 0.0);
1149 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1150 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1151
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001152 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1153 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001154 PyErr_SetString(PySSLErrorObject,
1155 "The write operation timed out");
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001156 return NULL;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001157 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001158 PyErr_SetString(PySSLErrorObject,
1159 "Underlying socket has been closed.");
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001160 return NULL;
Neal Norwitz389cea82006-02-13 00:35:21 +00001161 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001162 PyErr_SetString(PySSLErrorObject,
1163 "Underlying socket too large for select().");
Neal Norwitz082b2df2006-02-07 07:04:46 +00001164 return NULL;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001165 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001166 do {
1167 err = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001168 PySSL_BEGIN_ALLOW_THREADS
Martin v. Löwis405a7952003-10-27 14:24:37 +00001169 len = SSL_write(self->ssl, data, count);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001170 err = SSL_get_error(self->ssl, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001171 PySSL_END_ALLOW_THREADS
Martin v. Löwisafec8e32003-06-28 07:40:23 +00001172 if(PyErr_CheckSignals()) {
1173 return NULL;
1174 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001175 if (err == SSL_ERROR_WANT_READ) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001176 sockstate =
1177 check_socket_and_wait_for_timeout(self->Socket, 0);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001178 } else if (err == SSL_ERROR_WANT_WRITE) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001179 sockstate =
1180 check_socket_and_wait_for_timeout(self->Socket, 1);
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001181 } else {
1182 sockstate = SOCKET_OPERATION_OK;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001183 }
Thomas Woutersed03b412007-08-28 21:37:11 +00001184 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1185 PyErr_SetString(PySSLErrorObject,
1186 "The write operation timed out");
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001187 return NULL;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001188 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001189 PyErr_SetString(PySSLErrorObject,
1190 "Underlying socket has been closed.");
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001191 return NULL;
1192 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1193 break;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001194 }
1195 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001196 if (len > 0)
1197 return PyInt_FromLong(len);
1198 else
Thomas Woutersed03b412007-08-28 21:37:11 +00001199 return PySSL_SetError(self, len, __FILE__, __LINE__);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001200}
1201
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001202PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001203"write(s) -> len\n\
1204\n\
1205Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001206of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001207
Bill Janssen6e027db2007-11-15 22:23:56 +00001208static PyObject *PySSL_SSLpending(PySSLObject *self)
1209{
1210 int count = 0;
1211
1212 PySSL_BEGIN_ALLOW_THREADS
1213 count = SSL_pending(self->ssl);
1214 PySSL_END_ALLOW_THREADS
1215 if (count < 0)
1216 return PySSL_SetError(self, count, __FILE__, __LINE__);
1217 else
1218 return PyInt_FromLong(count);
1219}
1220
1221PyDoc_STRVAR(PySSL_SSLpending_doc,
1222"pending() -> count\n\
1223\n\
1224Returns the number of already decrypted bytes available for read,\n\
1225pending on the connection.\n");
1226
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001227static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1228{
Bill Janssen6e027db2007-11-15 22:23:56 +00001229 PyObject *buf = NULL;
1230 int buf_passed = 0;
1231 int count = -1;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001232 int len = 1024;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001233 int sockstate;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001234 int err;
Bill Janssen6e027db2007-11-15 22:23:56 +00001235 int nonblocking;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001236
Bill Janssen6e027db2007-11-15 22:23:56 +00001237 if (!PyArg_ParseTuple(args, "|Oi:read", &buf, &count))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001238 return NULL;
1239
Bill Janssen6e027db2007-11-15 22:23:56 +00001240 if ((buf == NULL) || (buf == Py_None)) {
1241 if (!(buf = PyBytes_FromStringAndSize((char *) 0, len)))
1242 return NULL;
1243 } else if (PyInt_Check(buf)) {
1244 len = PyInt_AS_LONG(buf);
1245 if (!(buf = PyBytes_FromStringAndSize((char *) 0, len)))
1246 return NULL;
1247 } else {
1248 if (!PyBytes_Check(buf))
1249 return NULL;
1250 len = PyBytes_Size(buf);
1251 if ((count > 0) && (count <= len))
1252 len = count;
1253 buf_passed = 1;
1254 }
1255
1256 /* just in case the blocking state of the socket has been changed */
1257 nonblocking = (self->Socket->sock_timeout >= 0.0);
1258 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1259 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Thomas Woutersed03b412007-08-28 21:37:11 +00001260
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001261 /* first check if there are bytes ready to be read */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001262 PySSL_BEGIN_ALLOW_THREADS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001263 count = SSL_pending(self->ssl);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001264 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001265
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001266 if (!count) {
1267 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1268 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001269 PyErr_SetString(PySSLErrorObject,
1270 "The read operation timed out");
Bill Janssen6e027db2007-11-15 22:23:56 +00001271 if (!buf_passed) {
1272 Py_DECREF(buf);
1273 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001274 return NULL;
1275 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001276 PyErr_SetString(PySSLErrorObject,
1277 "Underlying socket too large for select().");
Bill Janssen6e027db2007-11-15 22:23:56 +00001278 if (!buf_passed) {
1279 Py_DECREF(buf);
1280 }
Thomas Woutersed03b412007-08-28 21:37:11 +00001281 Py_DECREF(buf);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001282 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001283 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001284 /* should contain a zero-length string */
Bill Janssen6e027db2007-11-15 22:23:56 +00001285 if (!buf_passed) {
1286 PyBytes_Resize(buf, 0);
1287 return buf;
1288 } else {
1289 return PyInt_FromLong(0);
1290 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001291 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001292 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001293 do {
1294 err = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001295 PySSL_BEGIN_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001296 count = SSL_read(self->ssl, PyBytes_AsString(buf), len);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001297 err = SSL_get_error(self->ssl, count);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001298 PySSL_END_ALLOW_THREADS
Martin v. Löwisafec8e32003-06-28 07:40:23 +00001299 if(PyErr_CheckSignals()) {
Bill Janssen6e027db2007-11-15 22:23:56 +00001300 if (!buf_passed) {
1301 Py_DECREF(buf);
1302 }
Martin v. Löwisafec8e32003-06-28 07:40:23 +00001303 return NULL;
1304 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001305 if (err == SSL_ERROR_WANT_READ) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001306 sockstate =
1307 check_socket_and_wait_for_timeout(self->Socket, 0);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001308 } else if (err == SSL_ERROR_WANT_WRITE) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001309 sockstate =
1310 check_socket_and_wait_for_timeout(self->Socket, 1);
1311 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1312 (SSL_get_shutdown(self->ssl) ==
1313 SSL_RECEIVED_SHUTDOWN))
1314 {
Bill Janssen6e027db2007-11-15 22:23:56 +00001315 if (!buf_passed) {
1316 PyBytes_Resize(buf, 0);
1317 return buf;
1318 } else {
1319 return PyInt_FromLong(0);
1320 }
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001321 } else {
1322 sockstate = SOCKET_OPERATION_OK;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001323 }
Thomas Woutersed03b412007-08-28 21:37:11 +00001324 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1325 PyErr_SetString(PySSLErrorObject,
1326 "The read operation timed out");
Bill Janssen6e027db2007-11-15 22:23:56 +00001327 if (!buf_passed) {
1328 Py_DECREF(buf);
1329 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001330 return NULL;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001331 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1332 break;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001333 }
1334 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Thomas Woutersed03b412007-08-28 21:37:11 +00001335 if (count <= 0) {
Bill Janssen6e027db2007-11-15 22:23:56 +00001336 if (!buf_passed) {
1337 Py_DECREF(buf);
1338 }
Thomas Woutersed03b412007-08-28 21:37:11 +00001339 return PySSL_SetError(self, count, __FILE__, __LINE__);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001340 }
Bill Janssen6e027db2007-11-15 22:23:56 +00001341 if (!buf_passed) {
1342 if (count != len) {
1343 PyBytes_Resize(buf, count);
1344 }
1345 return buf;
1346 } else {
1347 return PyInt_FromLong(count);
1348 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001349}
1350
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001351PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001352"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001353\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001354Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001355
1356static PyMethodDef PySSLMethods[] = {
Bill Janssen6e027db2007-11-15 22:23:56 +00001357 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001358 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001359 PySSL_SSLwrite_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001360 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001361 PySSL_SSLread_doc},
Bill Janssen6e027db2007-11-15 22:23:56 +00001362 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1363 PySSL_SSLpending_doc},
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001364 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1365 PySSL_peercert_doc},
1366 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001367 {NULL, NULL}
1368};
1369
1370static PyObject *PySSL_getattr(PySSLObject *self, char *name)
1371{
1372 return Py_FindMethod(PySSLMethods, (PyObject *)self, name);
1373}
1374
Jeremy Hylton938ace62002-07-17 16:30:39 +00001375static PyTypeObject PySSL_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001376 PyVarObject_HEAD_INIT(NULL, 0)
Thomas Woutersed03b412007-08-28 21:37:11 +00001377 "ssl.SSLContext", /*tp_name*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001378 sizeof(PySSLObject), /*tp_basicsize*/
1379 0, /*tp_itemsize*/
1380 /* methods */
1381 (destructor)PySSL_dealloc, /*tp_dealloc*/
1382 0, /*tp_print*/
1383 (getattrfunc)PySSL_getattr, /*tp_getattr*/
1384 0, /*tp_setattr*/
1385 0, /*tp_compare*/
1386 0, /*tp_repr*/
1387 0, /*tp_as_number*/
1388 0, /*tp_as_sequence*/
1389 0, /*tp_as_mapping*/
1390 0, /*tp_hash*/
1391};
1392
1393#ifdef HAVE_OPENSSL_RAND
1394
1395/* helper routines for seeding the SSL PRNG */
1396static PyObject *
1397PySSL_RAND_add(PyObject *self, PyObject *args)
1398{
1399 char *buf;
1400 int len;
1401 double entropy;
1402
1403 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
1404 return NULL;
1405 RAND_add(buf, len, entropy);
1406 Py_INCREF(Py_None);
1407 return Py_None;
1408}
1409
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001410PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001411"RAND_add(string, entropy)\n\
1412\n\
1413Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001414bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001415
1416static PyObject *
1417PySSL_RAND_status(PyObject *self)
1418{
Bill Janssen6e027db2007-11-15 22:23:56 +00001419 return PyInt_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001420}
1421
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001422PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001423"RAND_status() -> 0 or 1\n\
1424\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001425Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1426It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1427using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001428
1429static PyObject *
1430PySSL_RAND_egd(PyObject *self, PyObject *arg)
1431{
1432 int bytes;
1433
Bill Janssen6e027db2007-11-15 22:23:56 +00001434 if (!PyUnicode_Check(arg))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001435 return PyErr_Format(PyExc_TypeError,
1436 "RAND_egd() expected string, found %s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001437 Py_Type(arg)->tp_name);
Bill Janssen6e027db2007-11-15 22:23:56 +00001438 bytes = RAND_egd(PyUnicode_AsString(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001439 if (bytes == -1) {
1440 PyErr_SetString(PySSLErrorObject,
1441 "EGD connection failed or EGD did not return "
1442 "enough data to seed the PRNG");
1443 return NULL;
1444 }
1445 return PyInt_FromLong(bytes);
1446}
1447
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001448PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001449"RAND_egd(path) -> bytes\n\
1450\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001451Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1452Returns number of bytes read. Raises SSLError if connection to EGD\n\
1453fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001454
1455#endif
1456
1457/* List of functions exported by this module. */
1458
1459static PyMethodDef PySSL_methods[] = {
Thomas Woutersed03b412007-08-28 21:37:11 +00001460 {"sslwrap", PySSL_sslwrap,
1461 METH_VARARGS, ssl_doc},
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001462 {"_test_decode_cert", PySSL_test_decode_certificate,
1463 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001464#ifdef HAVE_OPENSSL_RAND
Thomas Woutersed03b412007-08-28 21:37:11 +00001465 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001466 PySSL_RAND_add_doc},
1467 {"RAND_egd", PySSL_RAND_egd, METH_O,
1468 PySSL_RAND_egd_doc},
1469 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1470 PySSL_RAND_status_doc},
1471#endif
Thomas Woutersed03b412007-08-28 21:37:11 +00001472 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001473};
1474
1475
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001476#ifdef WITH_THREAD
1477
1478/* an implementation of OpenSSL threading operations in terms
1479 of the Python C thread library */
1480
1481static PyThread_type_lock *_ssl_locks = NULL;
1482
1483static unsigned long _ssl_thread_id_function (void) {
1484 return PyThread_get_thread_ident();
1485}
1486
Bill Janssen6e027db2007-11-15 22:23:56 +00001487static void _ssl_thread_locking_function
1488 (int mode, int n, const char *file, int line) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001489 /* this function is needed to perform locking on shared data
1490 structures. (Note that OpenSSL uses a number of global data
Bill Janssen6e027db2007-11-15 22:23:56 +00001491 structures that will be implicitly shared whenever multiple
1492 threads use OpenSSL.) Multi-threaded applications will
1493 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001494
Bill Janssen6e027db2007-11-15 22:23:56 +00001495 locking_function() must be able to handle up to
1496 CRYPTO_num_locks() different mutex locks. It sets the n-th
1497 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001498
1499 file and line are the file number of the function setting the
1500 lock. They can be useful for debugging.
1501 */
1502
1503 if ((_ssl_locks == NULL) ||
1504 (n < 0) || (n >= _ssl_locks_count))
1505 return;
1506
1507 if (mode & CRYPTO_LOCK) {
1508 PyThread_acquire_lock(_ssl_locks[n], 1);
1509 } else {
1510 PyThread_release_lock(_ssl_locks[n]);
1511 }
1512}
1513
1514static int _setup_ssl_threads(void) {
1515
1516 int i;
1517
1518 if (_ssl_locks == NULL) {
1519 _ssl_locks_count = CRYPTO_num_locks();
1520 _ssl_locks = (PyThread_type_lock *)
1521 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1522 if (_ssl_locks == NULL)
1523 return 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001524 memset(_ssl_locks, 0,
1525 sizeof(PyThread_type_lock) * _ssl_locks_count);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001526 for (i = 0; i < _ssl_locks_count; i++) {
1527 _ssl_locks[i] = PyThread_allocate_lock();
1528 if (_ssl_locks[i] == NULL) {
1529 int j;
1530 for (j = 0; j < i; j++) {
1531 PyThread_free_lock(_ssl_locks[j]);
1532 }
1533 free(_ssl_locks);
1534 return 0;
1535 }
1536 }
1537 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1538 CRYPTO_set_id_callback(_ssl_thread_id_function);
1539 }
1540 return 1;
1541}
1542
1543#endif /* def HAVE_THREAD */
1544
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001545PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001546"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001547for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001548
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001549PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001550init_ssl(void)
1551{
1552 PyObject *m, *d;
1553
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001554 Py_Type(&PySSL_Type) = &PyType_Type;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001555
1556 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001557 if (m == NULL)
1558 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001559 d = PyModule_GetDict(m);
1560
1561 /* Load _socket module and its C API */
1562 if (PySocketModule_ImportModuleAndAPI())
Thomas Woutersed03b412007-08-28 21:37:11 +00001563 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001564
1565 /* Init OpenSSL */
1566 SSL_load_error_strings();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001567#ifdef WITH_THREAD
1568 /* note that this will start threading if not already started */
1569 if (!_setup_ssl_threads()) {
1570 return;
1571 }
1572#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001573 SSLeay_add_ssl_algorithms();
1574
1575 /* Add symbols to module dict */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001576 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
Thomas Woutersed03b412007-08-28 21:37:11 +00001577 PySocketModule.error,
1578 NULL);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001579 if (PySSLErrorObject == NULL)
1580 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001581 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
Thomas Woutersed03b412007-08-28 21:37:11 +00001582 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001583 if (PyDict_SetItemString(d, "SSLType",
1584 (PyObject *)&PySSL_Type) != 0)
1585 return;
1586 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001587 PY_SSL_ERROR_ZERO_RETURN);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001588 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001589 PY_SSL_ERROR_WANT_READ);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001590 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001591 PY_SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001592 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001593 PY_SSL_ERROR_WANT_X509_LOOKUP);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001594 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001595 PY_SSL_ERROR_SYSCALL);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001596 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001597 PY_SSL_ERROR_SSL);
1598 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1599 PY_SSL_ERROR_WANT_CONNECT);
1600 /* non ssl.h errorcodes */
1601 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1602 PY_SSL_ERROR_EOF);
1603 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1604 PY_SSL_ERROR_INVALID_ERROR_CODE);
Thomas Woutersed03b412007-08-28 21:37:11 +00001605 /* cert requirements */
1606 PyModule_AddIntConstant(m, "CERT_NONE",
1607 PY_SSL_CERT_NONE);
1608 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1609 PY_SSL_CERT_OPTIONAL);
1610 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1611 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001612
Thomas Woutersed03b412007-08-28 21:37:11 +00001613 /* protocol versions */
1614 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1615 PY_SSL_VERSION_SSL2);
1616 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1617 PY_SSL_VERSION_SSL3);
1618 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1619 PY_SSL_VERSION_SSL23);
1620 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1621 PY_SSL_VERSION_TLS1);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001622}