blob: b680c411bec692309eb6dec58066dd7fec45e20a [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
5 certificate decoding.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006
Thomas Wouters1b7f8912007-09-19 03:06:30 +00007 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00008 directly.
9
Thomas Wouters1b7f8912007-09-19 03:06:30 +000010 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
11
12 XXX what about SSL_MODE_AUTO_RETRY
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000013*/
14
15#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000016
Thomas Wouters1b7f8912007-09-19 03:06:30 +000017#ifdef WITH_THREAD
18#include "pythread.h"
19#define PySSL_BEGIN_ALLOW_THREADS { \
20 PyThreadState *_save; \
21 if (_ssl_locks_count>0) {_save = PyEval_SaveThread();}
22#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)};
23#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()};
24#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \
25 }
26
27#else /* no WITH_THREAD */
28
29#define PySSL_BEGIN_ALLOW_THREADS
30#define PySSL_BLOCK_THREADS
31#define PySSL_UNBLOCK_THREADS
32#define PySSL_END_ALLOW_THREADS
33
34#endif
35
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000036enum py_ssl_error {
37 /* these mirror ssl.h */
Thomas Woutersed03b412007-08-28 21:37:11 +000038 PY_SSL_ERROR_NONE,
39 PY_SSL_ERROR_SSL,
40 PY_SSL_ERROR_WANT_READ,
41 PY_SSL_ERROR_WANT_WRITE,
42 PY_SSL_ERROR_WANT_X509_LOOKUP,
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000043 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
Thomas Woutersed03b412007-08-28 21:37:11 +000044 PY_SSL_ERROR_ZERO_RETURN,
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000045 PY_SSL_ERROR_WANT_CONNECT,
Thomas Woutersed03b412007-08-28 21:37:11 +000046 /* start of non ssl.h errorcodes */
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000047 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
48 PY_SSL_ERROR_INVALID_ERROR_CODE
49};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000050
Thomas Woutersed03b412007-08-28 21:37:11 +000051enum py_ssl_server_or_client {
52 PY_SSL_CLIENT,
53 PY_SSL_SERVER
54};
55
56enum py_ssl_cert_requirements {
57 PY_SSL_CERT_NONE,
58 PY_SSL_CERT_OPTIONAL,
59 PY_SSL_CERT_REQUIRED
60};
61
62enum py_ssl_version {
63 PY_SSL_VERSION_SSL2,
64 PY_SSL_VERSION_SSL3,
65 PY_SSL_VERSION_SSL23,
66 PY_SSL_VERSION_TLS1,
67};
68
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000069/* Include symbols from _socket module */
70#include "socketmodule.h"
71
Thomas Woutersed03b412007-08-28 21:37:11 +000072#if defined(HAVE_POLL_H)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000073#include <poll.h>
74#elif defined(HAVE_SYS_POLL_H)
75#include <sys/poll.h>
76#endif
77
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000078/* Include OpenSSL header files */
79#include "openssl/rsa.h"
80#include "openssl/crypto.h"
81#include "openssl/x509.h"
Thomas Wouters1b7f8912007-09-19 03:06:30 +000082#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000083#include "openssl/pem.h"
84#include "openssl/ssl.h"
85#include "openssl/err.h"
86#include "openssl/rand.h"
87
88/* SSL error object */
89static PyObject *PySSLErrorObject;
90
Thomas Wouters1b7f8912007-09-19 03:06:30 +000091#ifdef WITH_THREAD
92
93/* serves as a flag to see whether we've initialized the SSL thread support. */
94/* 0 means no, greater than 0 means yes */
95
96static unsigned int _ssl_locks_count = 0;
97
98#endif /* def WITH_THREAD */
99
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000100/* SSL socket object */
101
102#define X509_NAME_MAXLEN 256
103
104/* RAND_* APIs got added to OpenSSL in 0.9.5 */
105#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
106# define HAVE_OPENSSL_RAND 1
107#else
108# undef HAVE_OPENSSL_RAND
109#endif
110
111typedef struct {
112 PyObject_HEAD
113 PySocketSockObject *Socket; /* Socket on which we're layered */
Thomas Woutersed03b412007-08-28 21:37:11 +0000114 SSL_CTX* ctx;
115 SSL* ssl;
116 X509* peer_cert;
117 char server[X509_NAME_MAXLEN];
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000118 char issuer[X509_NAME_MAXLEN];
119
120} PySSLObject;
121
Jeremy Hylton938ace62002-07-17 16:30:39 +0000122static PyTypeObject PySSL_Type;
123static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args);
124static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000125static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000126 int writing);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000127static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args);
128static PyObject *PySSL_cipher(PySSLObject *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000129
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000130#define PySSLObject_Check(v) (Py_Type(v) == &PySSL_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000131
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000132typedef enum {
133 SOCKET_IS_NONBLOCKING,
134 SOCKET_IS_BLOCKING,
135 SOCKET_HAS_TIMED_OUT,
136 SOCKET_HAS_BEEN_CLOSED,
Neal Norwitz389cea82006-02-13 00:35:21 +0000137 SOCKET_TOO_LARGE_FOR_SELECT,
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000138 SOCKET_OPERATION_OK
139} timeout_state;
140
Thomas Woutersed03b412007-08-28 21:37:11 +0000141/* Wrap error strings with filename and line # */
142#define STRINGIFY1(x) #x
143#define STRINGIFY2(x) STRINGIFY1(x)
144#define ERRSTR1(x,y,z) (x ":" y ": " z)
145#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
146
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000147/* XXX It might be helpful to augment the error message generated
148 below with the name of the SSL function that generated the error.
149 I expect it's obvious most of the time.
150*/
151
152static PyObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000153PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000154{
Thomas Woutersed03b412007-08-28 21:37:11 +0000155 PyObject *v;
156 char buf[2048];
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000157 char *errstr;
158 int err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000159 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000160
161 assert(ret <= 0);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000162
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000163 if (obj->ssl != NULL) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000164 err = SSL_get_error(obj->ssl, ret);
165
166 switch (err) {
167 case SSL_ERROR_ZERO_RETURN:
168 errstr = "TLS/SSL connection has been closed";
169 p = PY_SSL_ERROR_ZERO_RETURN;
170 break;
171 case SSL_ERROR_WANT_READ:
172 errstr = "The operation did not complete (read)";
173 p = PY_SSL_ERROR_WANT_READ;
174 break;
175 case SSL_ERROR_WANT_WRITE:
176 p = PY_SSL_ERROR_WANT_WRITE;
177 errstr = "The operation did not complete (write)";
178 break;
179 case SSL_ERROR_WANT_X509_LOOKUP:
180 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
181 errstr =
182 "The operation did not complete (X509 lookup)";
183 break;
184 case SSL_ERROR_WANT_CONNECT:
185 p = PY_SSL_ERROR_WANT_CONNECT;
186 errstr = "The operation did not complete (connect)";
187 break;
188 case SSL_ERROR_SYSCALL:
189 {
190 unsigned long e = ERR_get_error();
191 if (e == 0) {
192 if (ret == 0 || !obj->Socket) {
193 p = PY_SSL_ERROR_EOF;
194 errstr =
195 "EOF occurred in violation of protocol";
196 } else if (ret == -1) {
197 /* underlying BIO reported an I/O error */
198 return obj->Socket->errorhandler();
199 } else { /* possible? */
200 p = PY_SSL_ERROR_SYSCALL;
201 errstr = "Some I/O error occurred";
202 }
203 } else {
Jeremy Hylton4e547302002-07-02 18:25:00 +0000204 p = PY_SSL_ERROR_SYSCALL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000205 /* XXX Protected by global interpreter lock */
206 errstr = ERR_error_string(e, NULL);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000207 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000208 break;
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000209 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000210 case SSL_ERROR_SSL:
211 {
212 unsigned long e = ERR_get_error();
213 p = PY_SSL_ERROR_SSL;
214 if (e != 0)
215 /* XXX Protected by global interpreter lock */
216 errstr = ERR_error_string(e, NULL);
217 else { /* possible? */
218 errstr =
219 "A failure in the SSL library occurred";
220 }
221 break;
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000222 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000223 default:
224 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
225 errstr = "Invalid error code";
226 }
227 } else {
228 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000229 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000230 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
231 v = Py_BuildValue("(is)", p, buf);
232 if (v != NULL) {
233 PyErr_SetObject(PySSLErrorObject, v);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000234 Py_DECREF(v);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000235 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000236 return NULL;
237}
238
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000239static PyObject *
240_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
241
242 char buf[2048];
243 PyObject *v;
244
245 if (errstr == NULL) {
246 errcode = ERR_peek_last_error();
247 errstr = ERR_error_string(errcode, NULL);
248 }
249 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
250 v = Py_BuildValue("(is)", errcode, buf);
251 if (v != NULL) {
252 PyErr_SetObject(PySSLErrorObject, v);
253 Py_DECREF(v);
254 }
255 return NULL;
256}
257
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000258static PySSLObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000259newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file,
260 enum py_ssl_server_or_client socket_type,
261 enum py_ssl_cert_requirements certreq,
262 enum py_ssl_version proto_version,
263 char *cacerts_file)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000264{
265 PySSLObject *self;
266 char *errstr = NULL;
267 int ret;
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000268 int err;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000269 int sockstate;
Thomas Woutersed03b412007-08-28 21:37:11 +0000270 int verification_mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000271
272 self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000273 if (self == NULL)
274 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000275 memset(self->server, '\0', sizeof(char) * X509_NAME_MAXLEN);
276 memset(self->issuer, '\0', sizeof(char) * X509_NAME_MAXLEN);
Thomas Woutersed03b412007-08-28 21:37:11 +0000277 self->peer_cert = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000278 self->ssl = NULL;
279 self->ctx = NULL;
280 self->Socket = NULL;
281
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000282 /* Make sure the SSL error state is initialized */
283 (void) ERR_get_state();
284 ERR_clear_error();
285
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000286 if ((key_file && !cert_file) || (!key_file && cert_file)) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000287 errstr = ERRSTR("Both the key & certificate files "
288 "must be specified");
289 goto fail;
290 }
291
292 if ((socket_type == PY_SSL_SERVER) &&
293 ((key_file == NULL) || (cert_file == NULL))) {
294 errstr = ERRSTR("Both the key & certificate files "
295 "must be specified for server-side operation");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000296 goto fail;
297 }
298
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000299 PySSL_BEGIN_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000300 if (proto_version == PY_SSL_VERSION_TLS1)
301 self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */
302 else if (proto_version == PY_SSL_VERSION_SSL3)
303 self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */
304 else if (proto_version == PY_SSL_VERSION_SSL2)
305 self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000306 else if (proto_version == PY_SSL_VERSION_SSL23)
Thomas Woutersed03b412007-08-28 21:37:11 +0000307 self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000308 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000309
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000310 if (self->ctx == NULL) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000311 errstr = ERRSTR("Invalid SSL protocol variant specified.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000312 goto fail;
313 }
314
Thomas Woutersed03b412007-08-28 21:37:11 +0000315 if (certreq != PY_SSL_CERT_NONE) {
316 if (cacerts_file == NULL) {
317 errstr = ERRSTR("No root certificates specified for "
318 "verification of other-side certificates.");
319 goto fail;
320 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000321 PySSL_BEGIN_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000322 ret = SSL_CTX_load_verify_locations(self->ctx,
323 cacerts_file,
324 NULL);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000325 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000326 if (ret != 1) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000327 _setSSLError(NULL, 0, __FILE__, __LINE__);
Thomas Woutersed03b412007-08-28 21:37:11 +0000328 goto fail;
329 }
330 }
331 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000332 if (key_file) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000333 PySSL_BEGIN_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000334 ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
Thomas Woutersed03b412007-08-28 21:37:11 +0000335 SSL_FILETYPE_PEM);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000336 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000337 if (ret != 1) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000338 _setSSLError(NULL, ret, __FILE__, __LINE__);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000339 goto fail;
340 }
341
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000342 PySSL_BEGIN_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000343 ret = SSL_CTX_use_certificate_chain_file(self->ctx,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000344 cert_file);
345 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000346 if (ret != 1) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000347 /*
348 fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
349 ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
350 */
351 if (ERR_peek_last_error() != 0) {
352 _setSSLError(NULL, ret, __FILE__, __LINE__);
353 goto fail;
354 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000355 }
356 }
357
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000358 /* ssl compatibility */
359 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
360
Thomas Woutersed03b412007-08-28 21:37:11 +0000361 verification_mode = SSL_VERIFY_NONE;
362 if (certreq == PY_SSL_CERT_OPTIONAL)
363 verification_mode = SSL_VERIFY_PEER;
364 else if (certreq == PY_SSL_CERT_REQUIRED)
365 verification_mode = (SSL_VERIFY_PEER |
366 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
367 SSL_CTX_set_verify(self->ctx, verification_mode,
368 NULL); /* set verify lvl */
369
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000370 PySSL_BEGIN_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000371 self->ssl = SSL_new(self->ctx); /* New ssl struct */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000372 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000373 SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000374
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000375 /* If the socket is in non-blocking mode or timeout mode, set the BIO
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000376 * to non-blocking mode (blocking is the default)
377 */
378 if (Sock->sock_timeout >= 0.0) {
379 /* Set both the read and write BIO's to non-blocking mode */
380 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
381 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
382 }
383
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000384 PySSL_BEGIN_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000385 if (socket_type == PY_SSL_CLIENT)
386 SSL_set_connect_state(self->ssl);
387 else
388 SSL_set_accept_state(self->ssl);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000389 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000390
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000391 /* Actually negotiate SSL connection */
392 /* XXX If SSL_connect() returns 0, it's also a failure. */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000393 sockstate = 0;
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000394 do {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000395 PySSL_BEGIN_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000396 if (socket_type == PY_SSL_CLIENT)
397 ret = SSL_connect(self->ssl);
398 else
399 ret = SSL_accept(self->ssl);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000400 err = SSL_get_error(self->ssl, ret);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000401 PySSL_END_ALLOW_THREADS
Martin v. Löwisafec8e32003-06-28 07:40:23 +0000402 if(PyErr_CheckSignals()) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000403 goto fail;
Martin v. Löwisafec8e32003-06-28 07:40:23 +0000404 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000405 if (err == SSL_ERROR_WANT_READ) {
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000406 sockstate = check_socket_and_wait_for_timeout(Sock, 0);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000407 } else if (err == SSL_ERROR_WANT_WRITE) {
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000408 sockstate = check_socket_and_wait_for_timeout(Sock, 1);
409 } else {
410 sockstate = SOCKET_OPERATION_OK;
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000411 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000412 if (sockstate == SOCKET_HAS_TIMED_OUT) {
413 PyErr_SetString(PySSLErrorObject,
414 ERRSTR("The connect operation timed out"));
Martin v. Löwisafec8e32003-06-28 07:40:23 +0000415 goto fail;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000416 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000417 PyErr_SetString(PySSLErrorObject,
418 ERRSTR("Underlying socket has been closed."));
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000419 goto fail;
Neal Norwitz389cea82006-02-13 00:35:21 +0000420 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000421 PyErr_SetString(PySSLErrorObject,
422 ERRSTR("Underlying socket too large for select()."));
Neal Norwitz082b2df2006-02-07 07:04:46 +0000423 goto fail;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000424 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
425 break;
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000426 }
427 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Thomas Woutersed03b412007-08-28 21:37:11 +0000428 if (ret < 1) {
429 PySSL_SetError(self, ret, __FILE__, __LINE__);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000430 goto fail;
431 }
432 self->ssl->debug = 1;
433
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000434 PySSL_BEGIN_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000435 if ((self->peer_cert = SSL_get_peer_certificate(self->ssl))) {
436 X509_NAME_oneline(X509_get_subject_name(self->peer_cert),
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000437 self->server, X509_NAME_MAXLEN);
Thomas Woutersed03b412007-08-28 21:37:11 +0000438 X509_NAME_oneline(X509_get_issuer_name(self->peer_cert),
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000439 self->issuer, X509_NAME_MAXLEN);
440 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000441 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000442 self->Socket = Sock;
443 Py_INCREF(self->Socket);
444 return self;
445 fail:
446 if (errstr)
447 PyErr_SetString(PySSLErrorObject, errstr);
448 Py_DECREF(self);
449 return NULL;
450}
451
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000452static PyObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000453PySSL_sslwrap(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000454{
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000455 PySocketSockObject *Sock;
Thomas Woutersed03b412007-08-28 21:37:11 +0000456 int server_side = 0;
457 int verification_mode = PY_SSL_CERT_NONE;
458 int protocol = PY_SSL_VERSION_SSL23;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000459 char *key_file = NULL;
460 char *cert_file = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000461 char *cacerts_file = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000462
Thomas Woutersed03b412007-08-28 21:37:11 +0000463 if (!PyArg_ParseTuple(args, "O!i|zziiz:sslwrap",
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000464 PySocketModule.Sock_Type,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000465 &Sock,
Thomas Woutersed03b412007-08-28 21:37:11 +0000466 &server_side,
467 &key_file, &cert_file,
468 &verification_mode, &protocol,
469 &cacerts_file))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000470 return NULL;
471
Thomas Woutersed03b412007-08-28 21:37:11 +0000472 /*
473 fprintf(stderr,
474 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
475 "protocol %d, certs %p\n",
476 server_side, key_file, cert_file, verification_mode,
477 protocol, cacerts_file);
478 */
479
480 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
481 server_side, verification_mode,
482 protocol, cacerts_file);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000483}
484
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000485PyDoc_STRVAR(ssl_doc,
Thomas Woutersed03b412007-08-28 21:37:11 +0000486"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
487" cacertsfile]) -> sslobject");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000488
489/* SSL object methods */
490
491static PyObject *
492PySSL_server(PySSLObject *self)
493{
Neal Norwitzae2c8762007-08-25 17:03:03 +0000494 return PyUnicode_FromString(self->server);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000495}
496
497static PyObject *
498PySSL_issuer(PySSLObject *self)
499{
Neal Norwitzae2c8762007-08-25 17:03:03 +0000500 return PyUnicode_FromString(self->issuer);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000501}
502
Thomas Woutersed03b412007-08-28 21:37:11 +0000503static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000504_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000505
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000506 char namebuf[X509_NAME_MAXLEN];
507 int buflen;
508 PyObject *name_obj;
509 PyObject *value_obj;
510 PyObject *attr;
511 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000512
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000513 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
514 if (buflen < 0) {
515 _setSSLError(NULL, 0, __FILE__, __LINE__);
516 goto fail;
Thomas Woutersed03b412007-08-28 21:37:11 +0000517 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000518 name_obj = PyString_FromStringAndSize(namebuf, buflen);
519 if (name_obj == NULL)
520 goto fail;
521
522 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
523 if (buflen < 0) {
524 _setSSLError(NULL, 0, __FILE__, __LINE__);
525 Py_DECREF(name_obj);
526 goto fail;
527 }
528 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
529 buflen, "strict");
530 OPENSSL_free(valuebuf);
531 if (value_obj == NULL) {
532 Py_DECREF(name_obj);
533 goto fail;
534 }
535 attr = PyTuple_New(2);
536 if (attr == NULL) {
537 Py_DECREF(name_obj);
538 Py_DECREF(value_obj);
539 goto fail;
540 }
541 PyTuple_SET_ITEM(attr, 0, name_obj);
542 PyTuple_SET_ITEM(attr, 1, value_obj);
543 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000544
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000545 fail:
Thomas Woutersed03b412007-08-28 21:37:11 +0000546 return NULL;
547}
548
549static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000550_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000551{
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000552 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
553 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
554 PyObject *rdnt;
555 PyObject *attr = NULL; /* tuple to hold an attribute */
556 int entry_count = X509_NAME_entry_count(xname);
557 X509_NAME_ENTRY *entry;
558 ASN1_OBJECT *name;
559 ASN1_STRING *value;
560 int index_counter;
561 int rdn_level = -1;
562 int retcode;
563
564 dn = PyList_New(0);
565 if (dn == NULL)
566 return NULL;
567 /* now create another tuple to hold the top-level RDN */
568 rdn = PyList_New(0);
569 if (rdn == NULL)
570 goto fail0;
571
572 for (index_counter = 0;
573 index_counter < entry_count;
574 index_counter++)
575 {
576 entry = X509_NAME_get_entry(xname, index_counter);
577
578 /* check to see if we've gotten to a new RDN */
579 if (rdn_level >= 0) {
580 if (rdn_level != entry->set) {
581 /* yes, new RDN */
582 /* add old RDN to DN */
583 rdnt = PyList_AsTuple(rdn);
584 Py_DECREF(rdn);
585 if (rdnt == NULL)
586 goto fail0;
587 retcode = PyList_Append(dn, rdnt);
588 Py_DECREF(rdnt);
589 if (retcode < 0)
590 goto fail0;
591 /* create new RDN */
592 rdn = PyList_New(0);
593 if (rdn == NULL)
594 goto fail0;
595 }
596 }
597 rdn_level = entry->set;
598
599 /* now add this attribute to the current RDN */
600 name = X509_NAME_ENTRY_get_object(entry);
601 value = X509_NAME_ENTRY_get_data(entry);
602 attr = _create_tuple_for_attribute(name, value);
603 /*
604 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
605 entry->set,
606 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
607 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
608 */
609 if (attr == NULL)
610 goto fail1;
611 retcode = PyList_Append(rdn, attr);
612 Py_DECREF(attr);
613 if (retcode < 0)
614 goto fail1;
615 }
616 /* now, there's typically a dangling RDN */
617 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
618 rdnt = PyList_AsTuple(rdn);
619 Py_DECREF(rdn);
620 if (rdnt == NULL)
621 goto fail0;
622 retcode = PyList_Append(dn, rdnt);
623 Py_DECREF(rdnt);
624 if (retcode < 0)
625 goto fail0;
626 }
627
628 /* convert list to tuple */
629 rdnt = PyList_AsTuple(dn);
630 Py_DECREF(dn);
631 if (rdnt == NULL)
632 return NULL;
633 return rdnt;
634
635 fail1:
636 Py_XDECREF(rdn);
637
638 fail0:
639 Py_XDECREF(dn);
640 return NULL;
641}
642
643static PyObject *
644_get_peer_alt_names (X509 *certificate) {
645
646 /* this code follows the procedure outlined in
647 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
648 function to extract the STACK_OF(GENERAL_NAME),
649 then iterates through the stack to add the
650 names. */
651
652 int i, j;
653 PyObject *peer_alt_names = Py_None;
654 PyObject *v, *t;
655 X509_EXTENSION *ext = NULL;
656 GENERAL_NAMES *names = NULL;
657 GENERAL_NAME *name;
658 X509V3_EXT_METHOD *method;
659 BIO *biobuf = NULL;
660 char buf[2048];
661 char *vptr;
662 int len;
663 unsigned char *p;
664
665 if (certificate == NULL)
666 return peer_alt_names;
667
668 /* get a memory buffer */
669 biobuf = BIO_new(BIO_s_mem());
670
671 i = 0;
672 while ((i = X509_get_ext_by_NID(
673 certificate, NID_subject_alt_name, i)) >= 0) {
674
675 if (peer_alt_names == Py_None) {
676 peer_alt_names = PyList_New(0);
677 if (peer_alt_names == NULL)
678 goto fail;
679 }
680
681 /* now decode the altName */
682 ext = X509_get_ext(certificate, i);
683 if(!(method = X509V3_EXT_get(ext))) {
684 PyErr_SetString(PySSLErrorObject,
685 ERRSTR("No method for internalizing subjectAltName!"));
686 goto fail;
687 }
688
689 p = ext->value->data;
690 if(method->it)
691 names = (GENERAL_NAMES*) (ASN1_item_d2i(NULL,
692 &p,
693 ext->value->length,
694 ASN1_ITEM_ptr(method->it)));
695 else
696 names = (GENERAL_NAMES*) (method->d2i(NULL,
697 &p,
698 ext->value->length));
699
700 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
701
702 /* get a rendering of each name in the set of names */
703
704 name = sk_GENERAL_NAME_value(names, j);
705 if (name->type == GEN_DIRNAME) {
706
707 /* we special-case DirName as a tuple of tuples of attributes */
708
709 t = PyTuple_New(2);
710 if (t == NULL) {
711 goto fail;
712 }
713
714 v = PyString_FromString("DirName");
715 if (v == NULL) {
716 Py_DECREF(t);
717 goto fail;
718 }
719 PyTuple_SET_ITEM(t, 0, v);
720
721 v = _create_tuple_for_X509_NAME (name->d.dirn);
722 if (v == NULL) {
723 Py_DECREF(t);
724 goto fail;
725 }
726 PyTuple_SET_ITEM(t, 1, v);
727
728 } else {
729
730 /* for everything else, we use the OpenSSL print form */
731
732 (void) BIO_reset(biobuf);
733 GENERAL_NAME_print(biobuf, name);
734 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
735 if (len < 0) {
736 _setSSLError(NULL, 0, __FILE__, __LINE__);
737 goto fail;
738 }
739 vptr = strchr(buf, ':');
740 if (vptr == NULL)
741 goto fail;
742 t = PyTuple_New(2);
743 if (t == NULL)
744 goto fail;
745 v = PyString_FromStringAndSize(buf, (vptr - buf));
746 if (v == NULL) {
747 Py_DECREF(t);
748 goto fail;
749 }
750 PyTuple_SET_ITEM(t, 0, v);
751 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
752 if (v == NULL) {
753 Py_DECREF(t);
754 goto fail;
755 }
756 PyTuple_SET_ITEM(t, 1, v);
757 }
758
759 /* and add that rendering to the list */
760
761 if (PyList_Append(peer_alt_names, t) < 0) {
762 Py_DECREF(t);
763 goto fail;
764 }
765 Py_DECREF(t);
766 }
767 }
768 BIO_free(biobuf);
769 if (peer_alt_names != Py_None) {
770 v = PyList_AsTuple(peer_alt_names);
771 Py_DECREF(peer_alt_names);
772 return v;
773 } else {
774 return peer_alt_names;
775 }
776
777
778 fail:
779 if (biobuf != NULL)
780 BIO_free(biobuf);
781
782 if (peer_alt_names != Py_None) {
783 Py_XDECREF(peer_alt_names);
784 }
785
786 return NULL;
787}
788
789static PyObject *
790_decode_certificate (X509 *certificate, int verbose) {
791
Thomas Woutersed03b412007-08-28 21:37:11 +0000792 PyObject *retval = NULL;
793 BIO *biobuf = NULL;
794 PyObject *peer;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000795 PyObject *peer_alt_names = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000796 PyObject *issuer;
797 PyObject *version;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000798 PyObject *sn_obj;
799 ASN1_INTEGER *serialNumber;
Thomas Woutersed03b412007-08-28 21:37:11 +0000800 char buf[2048];
801 int len;
802 ASN1_TIME *notBefore, *notAfter;
803 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000804
805 retval = PyDict_New();
806 if (retval == NULL)
807 return NULL;
808
Thomas Wouters89d996e2007-09-08 17:39:28 +0000809 peer = _create_tuple_for_X509_NAME(
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000810 X509_get_subject_name(certificate));
Thomas Woutersed03b412007-08-28 21:37:11 +0000811 if (peer == NULL)
812 goto fail0;
813 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
814 Py_DECREF(peer);
815 goto fail0;
816 }
817 Py_DECREF(peer);
818
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000819 if (verbose) {
820 issuer = _create_tuple_for_X509_NAME(
821 X509_get_issuer_name(certificate));
822 if (issuer == NULL)
823 goto fail0;
824 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
825 Py_DECREF(issuer);
826 goto fail0;
827 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000828 Py_DECREF(issuer);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000829
830 version = PyInt_FromLong(X509_get_version(certificate) + 1);
831 if (PyDict_SetItemString(retval, "version", version) < 0) {
832 Py_DECREF(version);
833 goto fail0;
834 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000835 Py_DECREF(version);
Thomas Woutersed03b412007-08-28 21:37:11 +0000836 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000837
Thomas Woutersed03b412007-08-28 21:37:11 +0000838 /* get a memory buffer */
839 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000840
841 if (verbose) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000842
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000843 (void) BIO_reset(biobuf);
844 serialNumber = X509_get_serialNumber(certificate);
845 /* should not exceed 20 octets, 160 bits, so buf is big enough */
846 i2a_ASN1_INTEGER(biobuf, serialNumber);
847 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
848 if (len < 0) {
849 _setSSLError(NULL, 0, __FILE__, __LINE__);
850 goto fail1;
851 }
852 sn_obj = PyString_FromStringAndSize(buf, len);
853 if (sn_obj == NULL)
854 goto fail1;
855 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
856 Py_DECREF(sn_obj);
857 goto fail1;
858 }
859 Py_DECREF(sn_obj);
860
861 (void) BIO_reset(biobuf);
862 notBefore = X509_get_notBefore(certificate);
863 ASN1_TIME_print(biobuf, notBefore);
864 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
865 if (len < 0) {
866 _setSSLError(NULL, 0, __FILE__, __LINE__);
867 goto fail1;
868 }
869 pnotBefore = PyString_FromStringAndSize(buf, len);
870 if (pnotBefore == NULL)
871 goto fail1;
872 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
873 Py_DECREF(pnotBefore);
874 goto fail1;
875 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000876 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000877 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000878
879 (void) BIO_reset(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000880 notAfter = X509_get_notAfter(certificate);
Thomas Woutersed03b412007-08-28 21:37:11 +0000881 ASN1_TIME_print(biobuf, notAfter);
882 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000883 if (len < 0) {
884 _setSSLError(NULL, 0, __FILE__, __LINE__);
885 goto fail1;
886 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000887 pnotAfter = PyString_FromStringAndSize(buf, len);
888 if (pnotAfter == NULL)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000889 goto fail1;
Thomas Woutersed03b412007-08-28 21:37:11 +0000890 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
891 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000892 goto fail1;
Thomas Woutersed03b412007-08-28 21:37:11 +0000893 }
894 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000895
896 /* Now look for subjectAltName */
897
898 peer_alt_names = _get_peer_alt_names(certificate);
899 if (peer_alt_names == NULL)
900 goto fail1;
901 else if (peer_alt_names != Py_None) {
902 if (PyDict_SetItemString(retval, "subjectAltName",
903 peer_alt_names) < 0) {
904 Py_DECREF(peer_alt_names);
905 goto fail1;
906 }
907 Py_DECREF(peer_alt_names);
908 }
909
910 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000911 return retval;
912
913 fail1:
914 if (biobuf != NULL)
915 BIO_free(biobuf);
916 fail0:
917 Py_XDECREF(retval);
918 return NULL;
919}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000920
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000921
922static PyObject *
923PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
924
925 PyObject *retval = NULL;
926 char *filename = NULL;
927 X509 *x=NULL;
928 BIO *cert;
929 int verbose = 1;
930
931 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", &filename, &verbose))
932 return NULL;
933
934 if ((cert=BIO_new(BIO_s_file())) == NULL) {
935 PyErr_SetString(PySSLErrorObject, "Can't malloc memory to read file");
936 goto fail0;
937 }
938
939 if (BIO_read_filename(cert,filename) <= 0) {
940 PyErr_SetString(PySSLErrorObject, "Can't open file");
941 goto fail0;
942 }
943
944 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
945 if (x == NULL) {
946 PyErr_SetString(PySSLErrorObject, "Error decoding PEM-encoded file");
947 goto fail0;
948 }
949
950 retval = _decode_certificate(x, verbose);
951
952 fail0:
953
954 if (cert != NULL) BIO_free(cert);
955 return retval;
956}
957
958
959static PyObject *
960PySSL_peercert(PySSLObject *self, PyObject *args)
961{
962 PyObject *retval = NULL;
963 int len;
964 int verification;
965 PyObject *binary_mode = Py_None;
966
967 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
968 return NULL;
969
970 if (!self->peer_cert)
971 Py_RETURN_NONE;
972
973 if (PyObject_IsTrue(binary_mode)) {
974 /* return cert in DER-encoded format */
975
976 unsigned char *bytes_buf = NULL;
977
978 bytes_buf = NULL;
979 len = i2d_X509(self->peer_cert, &bytes_buf);
980 if (len < 0) {
981 PySSL_SetError(self, len, __FILE__, __LINE__);
982 return NULL;
983 }
984 retval = PyString_FromStringAndSize((const char *) bytes_buf, len);
985 OPENSSL_free(bytes_buf);
986 return retval;
987
988 } else {
989
990 verification = SSL_CTX_get_verify_mode(self->ctx);
991 if ((verification & SSL_VERIFY_PEER) == 0)
992 return PyDict_New();
993 else
994 return _decode_certificate (self->peer_cert, 0);
995 }
996}
997
998PyDoc_STRVAR(PySSL_peercert_doc,
999"peer_certificate([der=False]) -> certificate\n\
1000\n\
1001Returns the certificate for the peer. If no certificate was provided,\n\
1002returns None. If a certificate was provided, but not validated, returns\n\
1003an empty dictionary. Otherwise returns a dict containing information\n\
1004about the peer certificate.\n\
1005\n\
1006If the optional argument is True, returns a DER-encoded copy of the\n\
1007peer certificate, or None if no certificate was provided. This will\n\
1008return the certificate even if it wasn't validated.");
1009
1010static PyObject *PySSL_cipher (PySSLObject *self) {
1011
1012 PyObject *retval, *v;
1013 SSL_CIPHER *current;
1014 char *cipher_name;
1015 char *cipher_protocol;
1016
1017 if (self->ssl == NULL)
1018 return Py_None;
1019 current = SSL_get_current_cipher(self->ssl);
1020 if (current == NULL)
1021 return Py_None;
1022
1023 retval = PyTuple_New(3);
1024 if (retval == NULL)
1025 return NULL;
1026
1027 cipher_name = (char *) SSL_CIPHER_get_name(current);
1028 if (cipher_name == NULL) {
1029 PyTuple_SET_ITEM(retval, 0, Py_None);
1030 } else {
1031 v = PyString_FromString(cipher_name);
1032 if (v == NULL)
1033 goto fail0;
1034 PyTuple_SET_ITEM(retval, 0, v);
1035 }
1036 cipher_protocol = SSL_CIPHER_get_version(current);
1037 if (cipher_protocol == NULL) {
1038 PyTuple_SET_ITEM(retval, 1, Py_None);
1039 } else {
1040 v = PyString_FromString(cipher_protocol);
1041 if (v == NULL)
1042 goto fail0;
1043 PyTuple_SET_ITEM(retval, 1, v);
1044 }
1045 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1046 if (v == NULL)
1047 goto fail0;
1048 PyTuple_SET_ITEM(retval, 2, v);
1049 return retval;
1050
1051 fail0:
1052 Py_DECREF(retval);
1053 return NULL;
1054}
1055
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001056static void PySSL_dealloc(PySSLObject *self)
1057{
Thomas Woutersed03b412007-08-28 21:37:11 +00001058 if (self->peer_cert) /* Possible not to have one? */
1059 X509_free (self->peer_cert);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001060 if (self->ssl)
Thomas Woutersed03b412007-08-28 21:37:11 +00001061 SSL_free(self->ssl);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001062 if (self->ctx)
Thomas Woutersed03b412007-08-28 21:37:11 +00001063 SSL_CTX_free(self->ctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001064 Py_XDECREF(self->Socket);
1065 PyObject_Del(self);
1066}
1067
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001068/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001069 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001070 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001071 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001072
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001073static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001074check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001075{
1076 fd_set fds;
1077 struct timeval tv;
1078 int rc;
1079
1080 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001081 if (s->sock_timeout < 0.0)
1082 return SOCKET_IS_BLOCKING;
1083 else if (s->sock_timeout == 0.0)
1084 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001085
1086 /* Guard against closed socket */
1087 if (s->sock_fd < 0)
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001088 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001089
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001090 /* Prefer poll, if available, since you can poll() any fd
1091 * which can't be done with select(). */
1092#ifdef HAVE_POLL
1093 {
1094 struct pollfd pollfd;
1095 int timeout;
1096
1097 pollfd.fd = s->sock_fd;
1098 pollfd.events = writing ? POLLOUT : POLLIN;
1099
1100 /* s->sock_timeout is in seconds, timeout in ms */
1101 timeout = (int)(s->sock_timeout * 1000 + 0.5);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001102 PySSL_BEGIN_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001103 rc = poll(&pollfd, 1, timeout);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001104 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001105
1106 goto normal_return;
1107 }
1108#endif
1109
Neal Norwitz082b2df2006-02-07 07:04:46 +00001110 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001111#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Neal Norwitz082b2df2006-02-07 07:04:46 +00001112 if (s->sock_fd >= FD_SETSIZE)
Neal Norwitz389cea82006-02-13 00:35:21 +00001113 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001114#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001115
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001116 /* Construct the arguments to select */
1117 tv.tv_sec = (int)s->sock_timeout;
1118 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1119 FD_ZERO(&fds);
1120 FD_SET(s->sock_fd, &fds);
1121
1122 /* See if the socket is ready */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001123 PySSL_BEGIN_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001124 if (writing)
1125 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1126 else
1127 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001128 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001129
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001130normal_return:
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001131 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1132 (when we are able to write or when there's something to read) */
1133 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001134}
1135
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001136static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1137{
1138 char *data;
1139 int len;
Martin v. Löwis405a7952003-10-27 14:24:37 +00001140 int count;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001141 int sockstate;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001142 int err;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001143
Martin v. Löwis405a7952003-10-27 14:24:37 +00001144 if (!PyArg_ParseTuple(args, "s#:write", &data, &count))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001145 return NULL;
1146
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001147 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1148 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001149 PyErr_SetString(PySSLErrorObject,
1150 "The write operation timed out");
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001151 return NULL;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001152 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001153 PyErr_SetString(PySSLErrorObject,
1154 "Underlying socket has been closed.");
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001155 return NULL;
Neal Norwitz389cea82006-02-13 00:35:21 +00001156 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001157 PyErr_SetString(PySSLErrorObject,
1158 "Underlying socket too large for select().");
Neal Norwitz082b2df2006-02-07 07:04:46 +00001159 return NULL;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001160 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001161 do {
1162 err = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001163 PySSL_BEGIN_ALLOW_THREADS
Martin v. Löwis405a7952003-10-27 14:24:37 +00001164 len = SSL_write(self->ssl, data, count);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001165 err = SSL_get_error(self->ssl, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001166 PySSL_END_ALLOW_THREADS
Martin v. Löwisafec8e32003-06-28 07:40:23 +00001167 if(PyErr_CheckSignals()) {
1168 return NULL;
1169 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001170 if (err == SSL_ERROR_WANT_READ) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001171 sockstate =
1172 check_socket_and_wait_for_timeout(self->Socket, 0);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001173 } else if (err == SSL_ERROR_WANT_WRITE) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001174 sockstate =
1175 check_socket_and_wait_for_timeout(self->Socket, 1);
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001176 } else {
1177 sockstate = SOCKET_OPERATION_OK;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001178 }
Thomas Woutersed03b412007-08-28 21:37:11 +00001179 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1180 PyErr_SetString(PySSLErrorObject,
1181 "The write operation timed out");
Guido van Rossum4f707ac2003-01-31 18:13:18 +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;
1187 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1188 break;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001189 }
1190 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001191 if (len > 0)
1192 return PyInt_FromLong(len);
1193 else
Thomas Woutersed03b412007-08-28 21:37:11 +00001194 return PySSL_SetError(self, len, __FILE__, __LINE__);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001195}
1196
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001197PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001198"write(s) -> len\n\
1199\n\
1200Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001201of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001202
1203static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1204{
1205 PyObject *buf;
1206 int count = 0;
1207 int len = 1024;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001208 int sockstate;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001209 int err;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001210
1211 if (!PyArg_ParseTuple(args, "|i:read", &len))
1212 return NULL;
1213
Jeremy Hylton62520832007-08-04 02:58:42 +00001214 if (!(buf = PyBytes_FromStringAndSize((char *) 0, len)))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001215 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001216
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001217 /* first check if there are bytes ready to be read */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001218 PySSL_BEGIN_ALLOW_THREADS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001219 count = SSL_pending(self->ssl);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001220 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001221
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001222 if (!count) {
1223 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1224 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001225 PyErr_SetString(PySSLErrorObject,
1226 "The read operation timed out");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001227 Py_DECREF(buf);
1228 return NULL;
1229 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001230 PyErr_SetString(PySSLErrorObject,
1231 "Underlying socket too large for select().");
1232 Py_DECREF(buf);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001233 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001234 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001235 /* should contain a zero-length string */
1236 _PyString_Resize(&buf, 0);
1237 return buf;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001238 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001239 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001240 do {
1241 err = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001242 PySSL_BEGIN_ALLOW_THREADS
Jeremy Hylton62520832007-08-04 02:58:42 +00001243 count = SSL_read(self->ssl, PyBytes_AS_STRING(buf), len);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001244 err = SSL_get_error(self->ssl, count);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001245 PySSL_END_ALLOW_THREADS
Martin v. Löwisafec8e32003-06-28 07:40:23 +00001246 if(PyErr_CheckSignals()) {
1247 Py_DECREF(buf);
1248 return NULL;
1249 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001250 if (err == SSL_ERROR_WANT_READ) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001251 sockstate =
1252 check_socket_and_wait_for_timeout(self->Socket, 0);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001253 } else if (err == SSL_ERROR_WANT_WRITE) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001254 sockstate =
1255 check_socket_and_wait_for_timeout(self->Socket, 1);
1256 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1257 (SSL_get_shutdown(self->ssl) ==
1258 SSL_RECEIVED_SHUTDOWN))
1259 {
1260 _PyString_Resize(&buf, 0);
1261 return buf;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001262 } else {
1263 sockstate = SOCKET_OPERATION_OK;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001264 }
Thomas Woutersed03b412007-08-28 21:37:11 +00001265 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1266 PyErr_SetString(PySSLErrorObject,
1267 "The read operation timed out");
Martin v. Löwisafec8e32003-06-28 07:40:23 +00001268 Py_DECREF(buf);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001269 return NULL;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001270 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1271 break;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001272 }
1273 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Thomas Woutersed03b412007-08-28 21:37:11 +00001274 if (count <= 0) {
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001275 Py_DECREF(buf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001276 return PySSL_SetError(self, count, __FILE__, __LINE__);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001277 }
Tim Peters5de98422002-04-27 18:44:32 +00001278 if (count != len)
Jeremy Hylton62520832007-08-04 02:58:42 +00001279 if (PyBytes_Resize(buf, count) < 0) {
1280 Py_DECREF(buf);
1281 return NULL;
1282 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001283 return buf;
1284}
1285
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001286PyDoc_STRVAR(PySSL_SSLread_doc,
Jeremy Hylton62520832007-08-04 02:58:42 +00001287"read([len]) -> bytes\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001288\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001289Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001290
1291static PyMethodDef PySSLMethods[] = {
1292 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001293 PySSL_SSLwrite_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001294 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001295 PySSL_SSLread_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001296 {"server", (PyCFunction)PySSL_server, METH_NOARGS},
1297 {"issuer", (PyCFunction)PySSL_issuer, METH_NOARGS},
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001298 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1299 PySSL_peercert_doc},
1300 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001301 {NULL, NULL}
1302};
1303
1304static PyObject *PySSL_getattr(PySSLObject *self, char *name)
1305{
1306 return Py_FindMethod(PySSLMethods, (PyObject *)self, name);
1307}
1308
Jeremy Hylton938ace62002-07-17 16:30:39 +00001309static PyTypeObject PySSL_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001310 PyVarObject_HEAD_INIT(NULL, 0)
Thomas Woutersed03b412007-08-28 21:37:11 +00001311 "ssl.SSLContext", /*tp_name*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001312 sizeof(PySSLObject), /*tp_basicsize*/
1313 0, /*tp_itemsize*/
1314 /* methods */
1315 (destructor)PySSL_dealloc, /*tp_dealloc*/
1316 0, /*tp_print*/
1317 (getattrfunc)PySSL_getattr, /*tp_getattr*/
1318 0, /*tp_setattr*/
1319 0, /*tp_compare*/
1320 0, /*tp_repr*/
1321 0, /*tp_as_number*/
1322 0, /*tp_as_sequence*/
1323 0, /*tp_as_mapping*/
1324 0, /*tp_hash*/
1325};
1326
1327#ifdef HAVE_OPENSSL_RAND
1328
1329/* helper routines for seeding the SSL PRNG */
1330static PyObject *
1331PySSL_RAND_add(PyObject *self, PyObject *args)
1332{
1333 char *buf;
1334 int len;
1335 double entropy;
1336
1337 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
1338 return NULL;
1339 RAND_add(buf, len, entropy);
1340 Py_INCREF(Py_None);
1341 return Py_None;
1342}
1343
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001344PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001345"RAND_add(string, entropy)\n\
1346\n\
1347Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001348bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001349
1350static PyObject *
1351PySSL_RAND_status(PyObject *self)
1352{
Neal Norwitz1ccfa902007-08-26 02:26:31 +00001353 return PyBool_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001354}
1355
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001356PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001357"RAND_status() -> 0 or 1\n\
1358\n\
Neal Norwitz1ccfa902007-08-26 02:26:31 +00001359Returns True if the OpenSSL PRNG has been seeded with enough data and\n\
1360False if not. It is necessary to seed the PRNG with RAND_add()\n\
1361on some platforms before using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001362
1363static PyObject *
1364PySSL_RAND_egd(PyObject *self, PyObject *arg)
1365{
1366 int bytes;
1367
1368 if (!PyString_Check(arg))
1369 return PyErr_Format(PyExc_TypeError,
1370 "RAND_egd() expected string, found %s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001371 Py_Type(arg)->tp_name);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001372 bytes = RAND_egd(PyString_AS_STRING(arg));
1373 if (bytes == -1) {
1374 PyErr_SetString(PySSLErrorObject,
1375 "EGD connection failed or EGD did not return "
1376 "enough data to seed the PRNG");
1377 return NULL;
1378 }
1379 return PyInt_FromLong(bytes);
1380}
1381
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001382PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001383"RAND_egd(path) -> bytes\n\
1384\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001385Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1386Returns number of bytes read. Raises SSLError if connection to EGD\n\
1387fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001388
1389#endif
1390
1391/* List of functions exported by this module. */
1392
1393static PyMethodDef PySSL_methods[] = {
Thomas Woutersed03b412007-08-28 21:37:11 +00001394 {"sslwrap", PySSL_sslwrap,
1395 METH_VARARGS, ssl_doc},
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001396 {"_test_decode_cert", PySSL_test_decode_certificate,
1397 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001398#ifdef HAVE_OPENSSL_RAND
Thomas Woutersed03b412007-08-28 21:37:11 +00001399 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001400 PySSL_RAND_add_doc},
1401 {"RAND_egd", PySSL_RAND_egd, METH_O,
1402 PySSL_RAND_egd_doc},
1403 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1404 PySSL_RAND_status_doc},
1405#endif
Thomas Woutersed03b412007-08-28 21:37:11 +00001406 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001407};
1408
1409
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001410#ifdef WITH_THREAD
1411
1412/* an implementation of OpenSSL threading operations in terms
1413 of the Python C thread library */
1414
1415static PyThread_type_lock *_ssl_locks = NULL;
1416
1417static unsigned long _ssl_thread_id_function (void) {
1418 return PyThread_get_thread_ident();
1419}
1420
1421static void _ssl_thread_locking_function (int mode, int n, const char *file, int line) {
1422 /* this function is needed to perform locking on shared data
1423 structures. (Note that OpenSSL uses a number of global data
1424 structures that will be implicitly shared whenever multiple threads
1425 use OpenSSL.) Multi-threaded applications will crash at random if
1426 it is not set.
1427
1428 locking_function() must be able to handle up to CRYPTO_num_locks()
1429 different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and
1430 releases it otherwise.
1431
1432 file and line are the file number of the function setting the
1433 lock. They can be useful for debugging.
1434 */
1435
1436 if ((_ssl_locks == NULL) ||
1437 (n < 0) || (n >= _ssl_locks_count))
1438 return;
1439
1440 if (mode & CRYPTO_LOCK) {
1441 PyThread_acquire_lock(_ssl_locks[n], 1);
1442 } else {
1443 PyThread_release_lock(_ssl_locks[n]);
1444 }
1445}
1446
1447static int _setup_ssl_threads(void) {
1448
1449 int i;
1450
1451 if (_ssl_locks == NULL) {
1452 _ssl_locks_count = CRYPTO_num_locks();
1453 _ssl_locks = (PyThread_type_lock *)
1454 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1455 if (_ssl_locks == NULL)
1456 return 0;
1457 memset(_ssl_locks, 0, sizeof(PyThread_type_lock) * _ssl_locks_count);
1458 for (i = 0; i < _ssl_locks_count; i++) {
1459 _ssl_locks[i] = PyThread_allocate_lock();
1460 if (_ssl_locks[i] == NULL) {
1461 int j;
1462 for (j = 0; j < i; j++) {
1463 PyThread_free_lock(_ssl_locks[j]);
1464 }
1465 free(_ssl_locks);
1466 return 0;
1467 }
1468 }
1469 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1470 CRYPTO_set_id_callback(_ssl_thread_id_function);
1471 }
1472 return 1;
1473}
1474
1475#endif /* def HAVE_THREAD */
1476
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001477PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001478"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001479for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001480
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001481PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001482init_ssl(void)
1483{
1484 PyObject *m, *d;
1485
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001486 Py_Type(&PySSL_Type) = &PyType_Type;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001487
1488 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001489 if (m == NULL)
1490 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001491 d = PyModule_GetDict(m);
1492
1493 /* Load _socket module and its C API */
1494 if (PySocketModule_ImportModuleAndAPI())
Thomas Woutersed03b412007-08-28 21:37:11 +00001495 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001496
1497 /* Init OpenSSL */
1498 SSL_load_error_strings();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001499#ifdef WITH_THREAD
1500 /* note that this will start threading if not already started */
1501 if (!_setup_ssl_threads()) {
1502 return;
1503 }
1504#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001505 SSLeay_add_ssl_algorithms();
1506
1507 /* Add symbols to module dict */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001508 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
Thomas Woutersed03b412007-08-28 21:37:11 +00001509 PySocketModule.error,
1510 NULL);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001511 if (PySSLErrorObject == NULL)
1512 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001513 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
Thomas Woutersed03b412007-08-28 21:37:11 +00001514 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001515 if (PyDict_SetItemString(d, "SSLType",
1516 (PyObject *)&PySSL_Type) != 0)
1517 return;
1518 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001519 PY_SSL_ERROR_ZERO_RETURN);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001520 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001521 PY_SSL_ERROR_WANT_READ);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001522 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001523 PY_SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001524 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001525 PY_SSL_ERROR_WANT_X509_LOOKUP);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001526 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001527 PY_SSL_ERROR_SYSCALL);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001528 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001529 PY_SSL_ERROR_SSL);
1530 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1531 PY_SSL_ERROR_WANT_CONNECT);
1532 /* non ssl.h errorcodes */
1533 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1534 PY_SSL_ERROR_EOF);
1535 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1536 PY_SSL_ERROR_INVALID_ERROR_CODE);
Thomas Woutersed03b412007-08-28 21:37:11 +00001537 /* cert requirements */
1538 PyModule_AddIntConstant(m, "CERT_NONE",
1539 PY_SSL_CERT_NONE);
1540 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1541 PY_SSL_CERT_OPTIONAL);
1542 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1543 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001544
Thomas Woutersed03b412007-08-28 21:37:11 +00001545 /* protocol versions */
1546 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1547 PY_SSL_VERSION_SSL2);
1548 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1549 PY_SSL_VERSION_SSL3);
1550 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1551 PY_SSL_VERSION_SSL23);
1552 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1553 PY_SSL_VERSION_TLS1);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001554}