blob: 45a5490d4cee700a2531157ebef17b3af3d29103 [file] [log] [blame]
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Bill Janssen98d19da2007-09-10 21:51:02 +00004 Re-worked a bit by Bill Janssen to add server-side support and
5 certificate decoding.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006
Bill Janssen98d19da2007-09-10 21:51:02 +00007 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00008 directly.
9
Bill Janssen98d19da2007-09-10 21:51:02 +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"
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000016
Bill Janssen98d19da2007-09-10 21:51:02 +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 */
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +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 */
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000044 PY_SSL_ERROR_ZERO_RETURN,
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000045 PY_SSL_ERROR_WANT_CONNECT,
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +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
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +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
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000072#if defined(HAVE_POLL_H)
Anthony Baxter93ab5fa2006-07-11 02:04:09 +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"
Bill Janssen98d19da2007-09-10 21:51:02 +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
Bill Janssen98d19da2007-09-10 21:51:02 +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 */
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +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);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000125static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000126 int writing);
Bill Janssen98d19da2007-09-10 21:51:02 +0000127static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args);
128static PyObject *PySSL_cipher(PySSLObject *self);
129static PyObject *PySSL_SSLshutdown(PySSLObject *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000130
Martin v. Löwis68192102007-07-21 06:55:02 +0000131#define PySSLObject_Check(v) (Py_Type(v) == &PySSL_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000132
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000133typedef enum {
134 SOCKET_IS_NONBLOCKING,
135 SOCKET_IS_BLOCKING,
136 SOCKET_HAS_TIMED_OUT,
137 SOCKET_HAS_BEEN_CLOSED,
Neal Norwitz389cea82006-02-13 00:35:21 +0000138 SOCKET_TOO_LARGE_FOR_SELECT,
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000139 SOCKET_OPERATION_OK
140} timeout_state;
141
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000142/* Wrap error strings with filename and line # */
143#define STRINGIFY1(x) #x
144#define STRINGIFY2(x) STRINGIFY1(x)
145#define ERRSTR1(x,y,z) (x ":" y ": " z)
146#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
147
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000148/* XXX It might be helpful to augment the error message generated
149 below with the name of the SSL function that generated the error.
150 I expect it's obvious most of the time.
151*/
152
153static PyObject *
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000154PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000155{
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000156 PyObject *v;
Neal Norwitz049da9e2007-08-25 16:41:36 +0000157 char buf[2048];
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000158 char *errstr;
159 int err;
Guido van Rossum780b80d2007-08-27 18:42:23 +0000160 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000161
162 assert(ret <= 0);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000163
Bill Janssen98d19da2007-09-10 21:51:02 +0000164 if (obj->ssl != NULL) {
Guido van Rossum780b80d2007-08-27 18:42:23 +0000165 err = SSL_get_error(obj->ssl, ret);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000166
Guido van Rossum780b80d2007-08-27 18:42:23 +0000167 switch (err) {
168 case SSL_ERROR_ZERO_RETURN:
169 errstr = "TLS/SSL connection has been closed";
170 p = PY_SSL_ERROR_ZERO_RETURN;
171 break;
172 case SSL_ERROR_WANT_READ:
173 errstr = "The operation did not complete (read)";
174 p = PY_SSL_ERROR_WANT_READ;
175 break;
176 case SSL_ERROR_WANT_WRITE:
177 p = PY_SSL_ERROR_WANT_WRITE;
178 errstr = "The operation did not complete (write)";
179 break;
180 case SSL_ERROR_WANT_X509_LOOKUP:
181 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
182 errstr =
183 "The operation did not complete (X509 lookup)";
184 break;
185 case SSL_ERROR_WANT_CONNECT:
186 p = PY_SSL_ERROR_WANT_CONNECT;
187 errstr = "The operation did not complete (connect)";
188 break;
189 case SSL_ERROR_SYSCALL:
190 {
191 unsigned long e = ERR_get_error();
192 if (e == 0) {
193 if (ret == 0 || !obj->Socket) {
194 p = PY_SSL_ERROR_EOF;
195 errstr =
196 "EOF occurred in violation of protocol";
197 } else if (ret == -1) {
198 /* underlying BIO reported an I/O error */
199 return obj->Socket->errorhandler();
200 } else { /* possible? */
201 p = PY_SSL_ERROR_SYSCALL;
202 errstr = "Some I/O error occurred";
203 }
204 } else {
Jeremy Hylton4e547302002-07-02 18:25:00 +0000205 p = PY_SSL_ERROR_SYSCALL;
Guido van Rossum780b80d2007-08-27 18:42:23 +0000206 /* XXX Protected by global interpreter lock */
207 errstr = ERR_error_string(e, NULL);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000208 }
Guido van Rossum780b80d2007-08-27 18:42:23 +0000209 break;
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000210 }
Guido van Rossum780b80d2007-08-27 18:42:23 +0000211 case SSL_ERROR_SSL:
212 {
213 unsigned long e = ERR_get_error();
214 p = PY_SSL_ERROR_SSL;
215 if (e != 0)
216 /* XXX Protected by global interpreter lock */
217 errstr = ERR_error_string(e, NULL);
218 else { /* possible? */
219 errstr =
220 "A failure in the SSL library occurred";
221 }
222 break;
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000223 }
Guido van Rossum780b80d2007-08-27 18:42:23 +0000224 default:
225 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
226 errstr = "Invalid error code";
227 }
228 } else {
229 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000230 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000231 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
232 v = Py_BuildValue("(is)", p, buf);
233 if (v != NULL) {
234 PyErr_SetObject(PySSLErrorObject, v);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000235 Py_DECREF(v);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000236 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000237 return NULL;
238}
239
Bill Janssen98d19da2007-09-10 21:51:02 +0000240static PyObject *
241_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
242
243 char buf[2048];
244 PyObject *v;
245
246 if (errstr == NULL) {
247 errcode = ERR_peek_last_error();
248 errstr = ERR_error_string(errcode, NULL);
249 }
250 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
251 v = Py_BuildValue("(is)", errcode, buf);
252 if (v != NULL) {
253 PyErr_SetObject(PySSLErrorObject, v);
254 Py_DECREF(v);
255 }
256 return NULL;
257}
258
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000259static PySSLObject *
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000260newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file,
261 enum py_ssl_server_or_client socket_type,
262 enum py_ssl_cert_requirements certreq,
263 enum py_ssl_version proto_version,
264 char *cacerts_file)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000265{
266 PySSLObject *self;
267 char *errstr = NULL;
268 int ret;
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000269 int err;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000270 int sockstate;
Neal Norwitz049da9e2007-08-25 16:41:36 +0000271 int verification_mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000272
273 self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */
Neal Norwitz38e3b7d2006-05-11 07:51:59 +0000274 if (self == NULL)
Neal Norwitzc6a989a2006-05-10 06:57:58 +0000275 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000276 memset(self->server, '\0', sizeof(char) * X509_NAME_MAXLEN);
277 memset(self->issuer, '\0', sizeof(char) * X509_NAME_MAXLEN);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000278 self->peer_cert = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000279 self->ssl = NULL;
280 self->ctx = NULL;
281 self->Socket = NULL;
282
Bill Janssen98d19da2007-09-10 21:51:02 +0000283 /* Make sure the SSL error state is initialized */
284 (void) ERR_get_state();
285 ERR_clear_error();
286
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000287 if ((key_file && !cert_file) || (!key_file && cert_file)) {
Guido van Rossum780b80d2007-08-27 18:42:23 +0000288 errstr = ERRSTR("Both the key & certificate files "
289 "must be specified");
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000290 goto fail;
291 }
292
293 if ((socket_type == PY_SSL_SERVER) &&
294 ((key_file == NULL) || (cert_file == NULL))) {
Guido van Rossum780b80d2007-08-27 18:42:23 +0000295 errstr = ERRSTR("Both the key & certificate files "
296 "must be specified for server-side operation");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000297 goto fail;
298 }
299
Bill Janssen98d19da2007-09-10 21:51:02 +0000300 PySSL_BEGIN_ALLOW_THREADS
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000301 if (proto_version == PY_SSL_VERSION_TLS1)
302 self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */
303 else if (proto_version == PY_SSL_VERSION_SSL3)
304 self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */
305 else if (proto_version == PY_SSL_VERSION_SSL2)
306 self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */
Bill Janssen98d19da2007-09-10 21:51:02 +0000307 else if (proto_version == PY_SSL_VERSION_SSL23)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000308 self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
Bill Janssen98d19da2007-09-10 21:51:02 +0000309 PySSL_END_ALLOW_THREADS
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000310
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000311 if (self->ctx == NULL) {
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000312 errstr = ERRSTR("Invalid SSL protocol variant specified.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000313 goto fail;
314 }
315
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000316 if (certreq != PY_SSL_CERT_NONE) {
317 if (cacerts_file == NULL) {
Guido van Rossum780b80d2007-08-27 18:42:23 +0000318 errstr = ERRSTR("No root certificates specified for "
319 "verification of other-side certificates.");
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000320 goto fail;
321 } else {
Bill Janssen98d19da2007-09-10 21:51:02 +0000322 PySSL_BEGIN_ALLOW_THREADS
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000323 ret = SSL_CTX_load_verify_locations(self->ctx,
Guido van Rossum780b80d2007-08-27 18:42:23 +0000324 cacerts_file,
325 NULL);
Bill Janssen98d19da2007-09-10 21:51:02 +0000326 PySSL_END_ALLOW_THREADS
Guido van Rossum780b80d2007-08-27 18:42:23 +0000327 if (ret != 1) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000328 _setSSLError(NULL, 0, __FILE__, __LINE__);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000329 goto fail;
330 }
331 }
332 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000333 if (key_file) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000334 PySSL_BEGIN_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000335 ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000336 SSL_FILETYPE_PEM);
Bill Janssen98d19da2007-09-10 21:51:02 +0000337 PySSL_END_ALLOW_THREADS
Guido van Rossum780b80d2007-08-27 18:42:23 +0000338 if (ret != 1) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000339 _setSSLError(NULL, ret, __FILE__, __LINE__);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000340 goto fail;
341 }
342
Bill Janssen98d19da2007-09-10 21:51:02 +0000343 PySSL_BEGIN_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000344 ret = SSL_CTX_use_certificate_chain_file(self->ctx,
Bill Janssen98d19da2007-09-10 21:51:02 +0000345 cert_file);
346 PySSL_END_ALLOW_THREADS
Guido van Rossum780b80d2007-08-27 18:42:23 +0000347 if (ret != 1) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000348 /*
349 fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
350 ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
351 */
352 if (ERR_peek_last_error() != 0) {
353 _setSSLError(NULL, ret, __FILE__, __LINE__);
354 goto fail;
355 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000356 }
357 }
358
Bill Janssen98d19da2007-09-10 21:51:02 +0000359 /* ssl compatibility */
360 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
361
Neal Norwitz049da9e2007-08-25 16:41:36 +0000362 verification_mode = SSL_VERIFY_NONE;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000363 if (certreq == PY_SSL_CERT_OPTIONAL)
364 verification_mode = SSL_VERIFY_PEER;
365 else if (certreq == PY_SSL_CERT_REQUIRED)
366 verification_mode = (SSL_VERIFY_PEER |
367 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
368 SSL_CTX_set_verify(self->ctx, verification_mode,
369 NULL); /* set verify lvl */
370
Bill Janssen98d19da2007-09-10 21:51:02 +0000371 PySSL_BEGIN_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000372 self->ssl = SSL_new(self->ctx); /* New ssl struct */
Bill Janssen98d19da2007-09-10 21:51:02 +0000373 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000374 SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000375
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000376 /* If the socket is in non-blocking mode or timeout mode, set the BIO
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000377 * to non-blocking mode (blocking is the default)
378 */
379 if (Sock->sock_timeout >= 0.0) {
380 /* Set both the read and write BIO's to non-blocking mode */
381 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
382 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
383 }
384
Bill Janssen98d19da2007-09-10 21:51:02 +0000385 PySSL_BEGIN_ALLOW_THREADS
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000386 if (socket_type == PY_SSL_CLIENT)
387 SSL_set_connect_state(self->ssl);
388 else
389 SSL_set_accept_state(self->ssl);
Bill Janssen98d19da2007-09-10 21:51:02 +0000390 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000391
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000392 /* Actually negotiate SSL connection */
393 /* XXX If SSL_connect() returns 0, it's also a failure. */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000394 sockstate = 0;
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000395 do {
Bill Janssen98d19da2007-09-10 21:51:02 +0000396 PySSL_BEGIN_ALLOW_THREADS
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000397 if (socket_type == PY_SSL_CLIENT)
398 ret = SSL_connect(self->ssl);
399 else
400 ret = SSL_accept(self->ssl);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000401 err = SSL_get_error(self->ssl, ret);
Bill Janssen98d19da2007-09-10 21:51:02 +0000402 PySSL_END_ALLOW_THREADS
Martin v. Löwisafec8e32003-06-28 07:40:23 +0000403 if(PyErr_CheckSignals()) {
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000404 goto fail;
Martin v. Löwisafec8e32003-06-28 07:40:23 +0000405 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000406 if (err == SSL_ERROR_WANT_READ) {
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000407 sockstate = check_socket_and_wait_for_timeout(Sock, 0);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000408 } else if (err == SSL_ERROR_WANT_WRITE) {
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000409 sockstate = check_socket_and_wait_for_timeout(Sock, 1);
410 } else {
411 sockstate = SOCKET_OPERATION_OK;
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000412 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000413 if (sockstate == SOCKET_HAS_TIMED_OUT) {
414 PyErr_SetString(PySSLErrorObject,
415 ERRSTR("The connect operation timed out"));
Martin v. Löwisafec8e32003-06-28 07:40:23 +0000416 goto fail;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000417 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000418 PyErr_SetString(PySSLErrorObject,
419 ERRSTR("Underlying socket has been closed."));
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000420 goto fail;
Neal Norwitz389cea82006-02-13 00:35:21 +0000421 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000422 PyErr_SetString(PySSLErrorObject,
423 ERRSTR("Underlying socket too large for select()."));
Neal Norwitz082b2df2006-02-07 07:04:46 +0000424 goto fail;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000425 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
426 break;
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000427 }
428 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000429 if (ret < 1) {
430 PySSL_SetError(self, ret, __FILE__, __LINE__);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000431 goto fail;
432 }
433 self->ssl->debug = 1;
434
Bill Janssen98d19da2007-09-10 21:51:02 +0000435 PySSL_BEGIN_ALLOW_THREADS
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000436 if ((self->peer_cert = SSL_get_peer_certificate(self->ssl))) {
437 X509_NAME_oneline(X509_get_subject_name(self->peer_cert),
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000438 self->server, X509_NAME_MAXLEN);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000439 X509_NAME_oneline(X509_get_issuer_name(self->peer_cert),
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000440 self->issuer, X509_NAME_MAXLEN);
441 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000442 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000443 self->Socket = Sock;
444 Py_INCREF(self->Socket);
445 return self;
446 fail:
447 if (errstr)
448 PyErr_SetString(PySSLErrorObject, errstr);
449 Py_DECREF(self);
450 return NULL;
451}
452
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000453static PyObject *
Guido van Rossum780b80d2007-08-27 18:42:23 +0000454PySSL_sslwrap(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000455{
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000456 PySocketSockObject *Sock;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000457 int server_side = 0;
458 int verification_mode = PY_SSL_CERT_NONE;
459 int protocol = PY_SSL_VERSION_SSL23;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000460 char *key_file = NULL;
461 char *cert_file = NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000462 char *cacerts_file = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000463
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000464 if (!PyArg_ParseTuple(args, "O!i|zziiz:sslwrap",
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000465 PySocketModule.Sock_Type,
Martin v. Löwisa811c382006-10-19 11:00:37 +0000466 &Sock,
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000467 &server_side,
468 &key_file, &cert_file,
469 &verification_mode, &protocol,
470 &cacerts_file))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000471 return NULL;
472
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000473 /*
474 fprintf(stderr,
475 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
476 "protocol %d, certs %p\n",
477 server_side, key_file, cert_file, verification_mode,
478 protocol, cacerts_file);
479 */
480
481 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
482 server_side, verification_mode,
483 protocol, cacerts_file);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000484}
485
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000486PyDoc_STRVAR(ssl_doc,
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000487"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
488" cacertsfile]) -> sslobject");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000489
490/* SSL object methods */
491
492static PyObject *
493PySSL_server(PySSLObject *self)
494{
495 return PyString_FromString(self->server);
496}
497
498static PyObject *
499PySSL_issuer(PySSLObject *self)
500{
501 return PyString_FromString(self->issuer);
502}
503
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000504static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000505_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000506
Bill Janssen98d19da2007-09-10 21:51:02 +0000507 char namebuf[X509_NAME_MAXLEN];
508 int buflen;
509 PyObject *name_obj;
510 PyObject *value_obj;
511 PyObject *attr;
512 unsigned char *valuebuf = NULL;
Guido van Rossum780b80d2007-08-27 18:42:23 +0000513
Bill Janssen98d19da2007-09-10 21:51:02 +0000514 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
515 if (buflen < 0) {
516 _setSSLError(NULL, 0, __FILE__, __LINE__);
517 goto fail;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000518 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000519 name_obj = PyString_FromStringAndSize(namebuf, buflen);
520 if (name_obj == NULL)
521 goto fail;
522
523 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
524 if (buflen < 0) {
525 _setSSLError(NULL, 0, __FILE__, __LINE__);
526 Py_DECREF(name_obj);
527 goto fail;
528 }
529 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
530 buflen, "strict");
531 OPENSSL_free(valuebuf);
532 if (value_obj == NULL) {
533 Py_DECREF(name_obj);
534 goto fail;
535 }
536 attr = PyTuple_New(2);
537 if (attr == NULL) {
538 Py_DECREF(name_obj);
539 Py_DECREF(value_obj);
540 goto fail;
541 }
542 PyTuple_SET_ITEM(attr, 0, name_obj);
543 PyTuple_SET_ITEM(attr, 1, value_obj);
544 return attr;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000545
Bill Janssen98d19da2007-09-10 21:51:02 +0000546 fail:
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000547 return NULL;
548}
549
550static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000551_create_tuple_for_X509_NAME (X509_NAME *xname)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000552{
Bill Janssen98d19da2007-09-10 21:51:02 +0000553 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
554 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
555 PyObject *rdnt;
556 PyObject *attr = NULL; /* tuple to hold an attribute */
557 int entry_count = X509_NAME_entry_count(xname);
558 X509_NAME_ENTRY *entry;
559 ASN1_OBJECT *name;
560 ASN1_STRING *value;
561 int index_counter;
562 int rdn_level = -1;
563 int retcode;
564
565 dn = PyList_New(0);
566 if (dn == NULL)
567 return NULL;
568 /* now create another tuple to hold the top-level RDN */
569 rdn = PyList_New(0);
570 if (rdn == NULL)
571 goto fail0;
572
573 for (index_counter = 0;
574 index_counter < entry_count;
575 index_counter++)
576 {
577 entry = X509_NAME_get_entry(xname, index_counter);
578
579 /* check to see if we've gotten to a new RDN */
580 if (rdn_level >= 0) {
581 if (rdn_level != entry->set) {
582 /* yes, new RDN */
583 /* add old RDN to DN */
584 rdnt = PyList_AsTuple(rdn);
585 Py_DECREF(rdn);
586 if (rdnt == NULL)
587 goto fail0;
588 retcode = PyList_Append(dn, rdnt);
589 Py_DECREF(rdnt);
590 if (retcode < 0)
591 goto fail0;
592 /* create new RDN */
593 rdn = PyList_New(0);
594 if (rdn == NULL)
595 goto fail0;
596 }
597 }
598 rdn_level = entry->set;
599
600 /* now add this attribute to the current RDN */
601 name = X509_NAME_ENTRY_get_object(entry);
602 value = X509_NAME_ENTRY_get_data(entry);
603 attr = _create_tuple_for_attribute(name, value);
604 /*
605 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
606 entry->set,
607 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
608 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
609 */
610 if (attr == NULL)
611 goto fail1;
612 retcode = PyList_Append(rdn, attr);
613 Py_DECREF(attr);
614 if (retcode < 0)
615 goto fail1;
616 }
617 /* now, there's typically a dangling RDN */
618 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
619 rdnt = PyList_AsTuple(rdn);
620 Py_DECREF(rdn);
621 if (rdnt == NULL)
622 goto fail0;
623 retcode = PyList_Append(dn, rdnt);
624 Py_DECREF(rdnt);
625 if (retcode < 0)
626 goto fail0;
627 }
628
629 /* convert list to tuple */
630 rdnt = PyList_AsTuple(dn);
631 Py_DECREF(dn);
632 if (rdnt == NULL)
633 return NULL;
634 return rdnt;
635
636 fail1:
637 Py_XDECREF(rdn);
638
639 fail0:
640 Py_XDECREF(dn);
641 return NULL;
642}
643
644static PyObject *
645_get_peer_alt_names (X509 *certificate) {
646
647 /* this code follows the procedure outlined in
648 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
649 function to extract the STACK_OF(GENERAL_NAME),
650 then iterates through the stack to add the
651 names. */
652
653 int i, j;
654 PyObject *peer_alt_names = Py_None;
655 PyObject *v, *t;
656 X509_EXTENSION *ext = NULL;
657 GENERAL_NAMES *names = NULL;
658 GENERAL_NAME *name;
659 X509V3_EXT_METHOD *method;
660 BIO *biobuf = NULL;
661 char buf[2048];
662 char *vptr;
663 int len;
664 const unsigned char *p;
665
666 if (certificate == NULL)
667 return peer_alt_names;
668
669 /* get a memory buffer */
670 biobuf = BIO_new(BIO_s_mem());
671
672 i = 0;
673 while ((i = X509_get_ext_by_NID(
674 certificate, NID_subject_alt_name, i)) >= 0) {
675
676 if (peer_alt_names == Py_None) {
677 peer_alt_names = PyList_New(0);
678 if (peer_alt_names == NULL)
679 goto fail;
680 }
681
682 /* now decode the altName */
683 ext = X509_get_ext(certificate, i);
684 if(!(method = X509V3_EXT_get(ext))) {
685 PyErr_SetString(PySSLErrorObject,
686 ERRSTR("No method for internalizing subjectAltName!"));
687 goto fail;
688 }
689
690 p = ext->value->data;
691 if(method->it)
692 names = (GENERAL_NAMES*) (ASN1_item_d2i(NULL,
693 &p,
694 ext->value->length,
695 ASN1_ITEM_ptr(method->it)));
696 else
697 names = (GENERAL_NAMES*) (method->d2i(NULL,
698 &p,
699 ext->value->length));
700
701 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
702
703 /* get a rendering of each name in the set of names */
704
705 name = sk_GENERAL_NAME_value(names, j);
706 if (name->type == GEN_DIRNAME) {
707
708 /* we special-case DirName as a tuple of tuples of attributes */
709
710 t = PyTuple_New(2);
711 if (t == NULL) {
712 goto fail;
713 }
714
715 v = PyString_FromString("DirName");
716 if (v == NULL) {
717 Py_DECREF(t);
718 goto fail;
719 }
720 PyTuple_SET_ITEM(t, 0, v);
721
722 v = _create_tuple_for_X509_NAME (name->d.dirn);
723 if (v == NULL) {
724 Py_DECREF(t);
725 goto fail;
726 }
727 PyTuple_SET_ITEM(t, 1, v);
728
729 } else {
730
731 /* for everything else, we use the OpenSSL print form */
732
733 (void) BIO_reset(biobuf);
734 GENERAL_NAME_print(biobuf, name);
735 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
736 if (len < 0) {
737 _setSSLError(NULL, 0, __FILE__, __LINE__);
738 goto fail;
739 }
740 vptr = strchr(buf, ':');
741 if (vptr == NULL)
742 goto fail;
743 t = PyTuple_New(2);
744 if (t == NULL)
745 goto fail;
746 v = PyString_FromStringAndSize(buf, (vptr - buf));
747 if (v == NULL) {
748 Py_DECREF(t);
749 goto fail;
750 }
751 PyTuple_SET_ITEM(t, 0, v);
752 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
753 if (v == NULL) {
754 Py_DECREF(t);
755 goto fail;
756 }
757 PyTuple_SET_ITEM(t, 1, v);
758 }
759
760 /* and add that rendering to the list */
761
762 if (PyList_Append(peer_alt_names, t) < 0) {
763 Py_DECREF(t);
764 goto fail;
765 }
766 Py_DECREF(t);
767 }
768 }
769 BIO_free(biobuf);
770 if (peer_alt_names != Py_None) {
771 v = PyList_AsTuple(peer_alt_names);
772 Py_DECREF(peer_alt_names);
773 return v;
774 } else {
775 return peer_alt_names;
776 }
777
778
779 fail:
780 if (biobuf != NULL)
781 BIO_free(biobuf);
782
783 if (peer_alt_names != Py_None) {
784 Py_XDECREF(peer_alt_names);
785 }
786
787 return NULL;
788}
789
790static PyObject *
791_decode_certificate (X509 *certificate, int verbose) {
792
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000793 PyObject *retval = NULL;
794 BIO *biobuf = NULL;
Neal Norwitz049da9e2007-08-25 16:41:36 +0000795 PyObject *peer;
Bill Janssen98d19da2007-09-10 21:51:02 +0000796 PyObject *peer_alt_names = NULL;
Neal Norwitz049da9e2007-08-25 16:41:36 +0000797 PyObject *issuer;
798 PyObject *version;
Bill Janssen98d19da2007-09-10 21:51:02 +0000799 PyObject *sn_obj;
800 ASN1_INTEGER *serialNumber;
Neal Norwitz049da9e2007-08-25 16:41:36 +0000801 char buf[2048];
802 int len;
803 ASN1_TIME *notBefore, *notAfter;
804 PyObject *pnotBefore, *pnotAfter;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000805
806 retval = PyDict_New();
807 if (retval == NULL)
808 return NULL;
809
Bill Janssenffe576d2007-09-05 00:46:27 +0000810 peer = _create_tuple_for_X509_NAME(
Bill Janssen98d19da2007-09-10 21:51:02 +0000811 X509_get_subject_name(certificate));
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000812 if (peer == NULL)
813 goto fail0;
814 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
815 Py_DECREF(peer);
816 goto fail0;
817 }
818 Py_DECREF(peer);
819
Bill Janssen98d19da2007-09-10 21:51:02 +0000820 if (verbose) {
821 issuer = _create_tuple_for_X509_NAME(
822 X509_get_issuer_name(certificate));
823 if (issuer == NULL)
824 goto fail0;
825 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
826 Py_DECREF(issuer);
827 goto fail0;
828 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000829 Py_DECREF(issuer);
Bill Janssen98d19da2007-09-10 21:51:02 +0000830
831 version = PyInt_FromLong(X509_get_version(certificate) + 1);
832 if (PyDict_SetItemString(retval, "version", version) < 0) {
833 Py_DECREF(version);
834 goto fail0;
835 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000836 Py_DECREF(version);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000837 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000838
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000839 /* get a memory buffer */
840 biobuf = BIO_new(BIO_s_mem());
Bill Janssen98d19da2007-09-10 21:51:02 +0000841
842 if (verbose) {
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000843
Bill Janssen98d19da2007-09-10 21:51:02 +0000844 (void) BIO_reset(biobuf);
845 serialNumber = X509_get_serialNumber(certificate);
846 /* should not exceed 20 octets, 160 bits, so buf is big enough */
847 i2a_ASN1_INTEGER(biobuf, serialNumber);
848 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
849 if (len < 0) {
850 _setSSLError(NULL, 0, __FILE__, __LINE__);
851 goto fail1;
852 }
853 sn_obj = PyString_FromStringAndSize(buf, len);
854 if (sn_obj == NULL)
855 goto fail1;
856 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
857 Py_DECREF(sn_obj);
858 goto fail1;
859 }
860 Py_DECREF(sn_obj);
861
862 (void) BIO_reset(biobuf);
863 notBefore = X509_get_notBefore(certificate);
864 ASN1_TIME_print(biobuf, notBefore);
865 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
866 if (len < 0) {
867 _setSSLError(NULL, 0, __FILE__, __LINE__);
868 goto fail1;
869 }
870 pnotBefore = PyString_FromStringAndSize(buf, len);
871 if (pnotBefore == NULL)
872 goto fail1;
873 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
874 Py_DECREF(pnotBefore);
875 goto fail1;
876 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000877 Py_DECREF(pnotBefore);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000878 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000879
Guido van Rossum780b80d2007-08-27 18:42:23 +0000880 (void) BIO_reset(biobuf);
Bill Janssen98d19da2007-09-10 21:51:02 +0000881 notAfter = X509_get_notAfter(certificate);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000882 ASN1_TIME_print(biobuf, notAfter);
883 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
Bill Janssen98d19da2007-09-10 21:51:02 +0000884 if (len < 0) {
885 _setSSLError(NULL, 0, __FILE__, __LINE__);
886 goto fail1;
887 }
Neal Norwitz049da9e2007-08-25 16:41:36 +0000888 pnotAfter = PyString_FromStringAndSize(buf, len);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000889 if (pnotAfter == NULL)
Bill Janssen98d19da2007-09-10 21:51:02 +0000890 goto fail1;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000891 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
892 Py_DECREF(pnotAfter);
Bill Janssen98d19da2007-09-10 21:51:02 +0000893 goto fail1;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000894 }
895 Py_DECREF(pnotAfter);
Bill Janssen98d19da2007-09-10 21:51:02 +0000896
897 /* Now look for subjectAltName */
898
899 peer_alt_names = _get_peer_alt_names(certificate);
900 if (peer_alt_names == NULL)
901 goto fail1;
902 else if (peer_alt_names != Py_None) {
903 if (PyDict_SetItemString(retval, "subjectAltName",
904 peer_alt_names) < 0) {
905 Py_DECREF(peer_alt_names);
906 goto fail1;
907 }
908 Py_DECREF(peer_alt_names);
909 }
910
911 BIO_free(biobuf);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000912 return retval;
913
914 fail1:
915 if (biobuf != NULL)
916 BIO_free(biobuf);
917 fail0:
918 Py_XDECREF(retval);
919 return NULL;
920}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000921
Bill Janssen98d19da2007-09-10 21:51:02 +0000922
923static PyObject *
924PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
925
926 PyObject *retval = NULL;
927 char *filename = NULL;
928 X509 *x=NULL;
929 BIO *cert;
930 int verbose = 1;
931
932 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", &filename, &verbose))
933 return NULL;
934
935 if ((cert=BIO_new(BIO_s_file())) == NULL) {
936 PyErr_SetString(PySSLErrorObject, "Can't malloc memory to read file");
937 goto fail0;
938 }
939
940 if (BIO_read_filename(cert,filename) <= 0) {
941 PyErr_SetString(PySSLErrorObject, "Can't open file");
942 goto fail0;
943 }
944
945 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
946 if (x == NULL) {
947 PyErr_SetString(PySSLErrorObject, "Error decoding PEM-encoded file");
948 goto fail0;
949 }
950
951 retval = _decode_certificate(x, verbose);
952
953 fail0:
954
955 if (cert != NULL) BIO_free(cert);
956 return retval;
957}
958
959
960static PyObject *
961PySSL_peercert(PySSLObject *self, PyObject *args)
962{
963 PyObject *retval = NULL;
964 int len;
965 int verification;
966 PyObject *binary_mode = Py_None;
967
968 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
969 return NULL;
970
971 if (!self->peer_cert)
972 Py_RETURN_NONE;
973
974 if (PyObject_IsTrue(binary_mode)) {
975 /* return cert in DER-encoded format */
976
977 unsigned char *bytes_buf = NULL;
978
979 bytes_buf = NULL;
980 len = i2d_X509(self->peer_cert, &bytes_buf);
981 if (len < 0) {
982 PySSL_SetError(self, len, __FILE__, __LINE__);
983 return NULL;
984 }
985 retval = PyString_FromStringAndSize((const char *) bytes_buf, len);
986 OPENSSL_free(bytes_buf);
987 return retval;
988
989 } else {
990
991 verification = SSL_CTX_get_verify_mode(self->ctx);
992 if ((verification & SSL_VERIFY_PEER) == 0)
993 return PyDict_New();
994 else
995 return _decode_certificate (self->peer_cert, 0);
996 }
997}
998
999PyDoc_STRVAR(PySSL_peercert_doc,
1000"peer_certificate([der=False]) -> certificate\n\
1001\n\
1002Returns the certificate for the peer. If no certificate was provided,\n\
1003returns None. If a certificate was provided, but not validated, returns\n\
1004an empty dictionary. Otherwise returns a dict containing information\n\
1005about the peer certificate.\n\
1006\n\
1007If the optional argument is True, returns a DER-encoded copy of the\n\
1008peer certificate, or None if no certificate was provided. This will\n\
1009return the certificate even if it wasn't validated.");
1010
1011static PyObject *PySSL_cipher (PySSLObject *self) {
1012
1013 PyObject *retval, *v;
1014 SSL_CIPHER *current;
1015 char *cipher_name;
1016 char *cipher_protocol;
1017
1018 if (self->ssl == NULL)
1019 return Py_None;
1020 current = SSL_get_current_cipher(self->ssl);
1021 if (current == NULL)
1022 return Py_None;
1023
1024 retval = PyTuple_New(3);
1025 if (retval == NULL)
1026 return NULL;
1027
1028 cipher_name = (char *) SSL_CIPHER_get_name(current);
1029 if (cipher_name == NULL) {
1030 PyTuple_SET_ITEM(retval, 0, Py_None);
1031 } else {
1032 v = PyString_FromString(cipher_name);
1033 if (v == NULL)
1034 goto fail0;
1035 PyTuple_SET_ITEM(retval, 0, v);
1036 }
1037 cipher_protocol = SSL_CIPHER_get_version(current);
1038 if (cipher_protocol == NULL) {
1039 PyTuple_SET_ITEM(retval, 1, Py_None);
1040 } else {
1041 v = PyString_FromString(cipher_protocol);
1042 if (v == NULL)
1043 goto fail0;
1044 PyTuple_SET_ITEM(retval, 1, v);
1045 }
1046 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1047 if (v == NULL)
1048 goto fail0;
1049 PyTuple_SET_ITEM(retval, 2, v);
1050 return retval;
1051
1052 fail0:
1053 Py_DECREF(retval);
1054 return NULL;
1055}
1056
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001057static void PySSL_dealloc(PySSLObject *self)
1058{
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001059 if (self->peer_cert) /* Possible not to have one? */
1060 X509_free (self->peer_cert);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001061 if (self->ssl)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001062 SSL_free(self->ssl);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001063 if (self->ctx)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001064 SSL_CTX_free(self->ctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001065 Py_XDECREF(self->Socket);
1066 PyObject_Del(self);
1067}
1068
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001069/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001070 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001071 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001072 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001073
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001074static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001075check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001076{
1077 fd_set fds;
1078 struct timeval tv;
1079 int rc;
1080
1081 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001082 if (s->sock_timeout < 0.0)
1083 return SOCKET_IS_BLOCKING;
1084 else if (s->sock_timeout == 0.0)
1085 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001086
1087 /* Guard against closed socket */
1088 if (s->sock_fd < 0)
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001089 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001090
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001091 /* Prefer poll, if available, since you can poll() any fd
1092 * which can't be done with select(). */
1093#ifdef HAVE_POLL
1094 {
1095 struct pollfd pollfd;
1096 int timeout;
1097
1098 pollfd.fd = s->sock_fd;
1099 pollfd.events = writing ? POLLOUT : POLLIN;
1100
1101 /* s->sock_timeout is in seconds, timeout in ms */
1102 timeout = (int)(s->sock_timeout * 1000 + 0.5);
Bill Janssen98d19da2007-09-10 21:51:02 +00001103 PySSL_BEGIN_ALLOW_THREADS
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001104 rc = poll(&pollfd, 1, timeout);
Bill Janssen98d19da2007-09-10 21:51:02 +00001105 PySSL_END_ALLOW_THREADS
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001106
1107 goto normal_return;
1108 }
1109#endif
1110
Neal Norwitz082b2df2006-02-07 07:04:46 +00001111 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001112#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Neal Norwitz082b2df2006-02-07 07:04:46 +00001113 if (s->sock_fd >= FD_SETSIZE)
Neal Norwitz389cea82006-02-13 00:35:21 +00001114 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001115#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001116
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001117 /* Construct the arguments to select */
1118 tv.tv_sec = (int)s->sock_timeout;
1119 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1120 FD_ZERO(&fds);
1121 FD_SET(s->sock_fd, &fds);
1122
1123 /* See if the socket is ready */
Bill Janssen98d19da2007-09-10 21:51:02 +00001124 PySSL_BEGIN_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001125 if (writing)
1126 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1127 else
1128 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
Bill Janssen98d19da2007-09-10 21:51:02 +00001129 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001130
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001131normal_return:
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001132 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1133 (when we are able to write or when there's something to read) */
1134 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001135}
1136
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001137static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1138{
1139 char *data;
1140 int len;
Martin v. Löwis405a7952003-10-27 14:24:37 +00001141 int count;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001142 int sockstate;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001143 int err;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001144
Martin v. Löwis405a7952003-10-27 14:24:37 +00001145 if (!PyArg_ParseTuple(args, "s#:write", &data, &count))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001146 return NULL;
1147
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001148 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1149 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Guido van Rossum780b80d2007-08-27 18:42:23 +00001150 PyErr_SetString(PySSLErrorObject,
1151 "The write operation timed out");
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001152 return NULL;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001153 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Guido van Rossum780b80d2007-08-27 18:42:23 +00001154 PyErr_SetString(PySSLErrorObject,
1155 "Underlying socket has been closed.");
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001156 return NULL;
Neal Norwitz389cea82006-02-13 00:35:21 +00001157 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Guido van Rossum780b80d2007-08-27 18:42:23 +00001158 PyErr_SetString(PySSLErrorObject,
1159 "Underlying socket too large for select().");
Neal Norwitz082b2df2006-02-07 07:04:46 +00001160 return NULL;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001161 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001162 do {
1163 err = 0;
Bill Janssen98d19da2007-09-10 21:51:02 +00001164 PySSL_BEGIN_ALLOW_THREADS
Martin v. Löwis405a7952003-10-27 14:24:37 +00001165 len = SSL_write(self->ssl, data, count);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001166 err = SSL_get_error(self->ssl, len);
Bill Janssen98d19da2007-09-10 21:51:02 +00001167 PySSL_END_ALLOW_THREADS
Martin v. Löwisafec8e32003-06-28 07:40:23 +00001168 if(PyErr_CheckSignals()) {
1169 return NULL;
1170 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001171 if (err == SSL_ERROR_WANT_READ) {
Guido van Rossum780b80d2007-08-27 18:42:23 +00001172 sockstate =
1173 check_socket_and_wait_for_timeout(self->Socket, 0);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001174 } else if (err == SSL_ERROR_WANT_WRITE) {
Guido van Rossum780b80d2007-08-27 18:42:23 +00001175 sockstate =
1176 check_socket_and_wait_for_timeout(self->Socket, 1);
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001177 } else {
1178 sockstate = SOCKET_OPERATION_OK;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001179 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001180 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Guido van Rossum780b80d2007-08-27 18:42:23 +00001181 PyErr_SetString(PySSLErrorObject,
1182 "The write operation timed out");
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001183 return NULL;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001184 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Guido van Rossum780b80d2007-08-27 18:42:23 +00001185 PyErr_SetString(PySSLErrorObject,
1186 "Underlying socket has been closed.");
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001187 return NULL;
1188 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1189 break;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001190 }
1191 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001192 if (len > 0)
1193 return PyInt_FromLong(len);
1194 else
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001195 return PySSL_SetError(self, len, __FILE__, __LINE__);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001196}
1197
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001198PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001199"write(s) -> len\n\
1200\n\
1201Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001202of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001203
1204static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1205{
1206 PyObject *buf;
1207 int count = 0;
1208 int len = 1024;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001209 int sockstate;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001210 int err;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001211
1212 if (!PyArg_ParseTuple(args, "|i:read", &len))
1213 return NULL;
1214
1215 if (!(buf = PyString_FromStringAndSize((char *) 0, len)))
1216 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001217
Georg Brandl43f08a82006-03-31 18:01:16 +00001218 /* first check if there are bytes ready to be read */
Bill Janssen98d19da2007-09-10 21:51:02 +00001219 PySSL_BEGIN_ALLOW_THREADS
Georg Brandl43f08a82006-03-31 18:01:16 +00001220 count = SSL_pending(self->ssl);
Bill Janssen98d19da2007-09-10 21:51:02 +00001221 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001222
Georg Brandl43f08a82006-03-31 18:01:16 +00001223 if (!count) {
1224 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1225 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001226 PyErr_SetString(PySSLErrorObject,
1227 "The read operation timed out");
Georg Brandl43f08a82006-03-31 18:01:16 +00001228 Py_DECREF(buf);
1229 return NULL;
1230 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001231 PyErr_SetString(PySSLErrorObject,
1232 "Underlying socket too large for select().");
1233 Py_DECREF(buf);
Georg Brandl43f08a82006-03-31 18:01:16 +00001234 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001235 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1236 if (SSL_get_shutdown(self->ssl) !=
1237 SSL_RECEIVED_SHUTDOWN)
1238 {
Guido van Rossum780b80d2007-08-27 18:42:23 +00001239 Py_DECREF(buf);
1240 PyErr_SetString(PySSLErrorObject,
1241 "Socket closed without SSL shutdown handshake");
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001242 return NULL;
1243 } else {
1244 /* should contain a zero-length string */
1245 _PyString_Resize(&buf, 0);
1246 return buf;
1247 }
Georg Brandl43f08a82006-03-31 18:01:16 +00001248 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001249 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001250 do {
1251 err = 0;
Bill Janssen98d19da2007-09-10 21:51:02 +00001252 PySSL_BEGIN_ALLOW_THREADS
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001253 count = SSL_read(self->ssl, PyString_AsString(buf), len);
1254 err = SSL_get_error(self->ssl, count);
Bill Janssen98d19da2007-09-10 21:51:02 +00001255 PySSL_END_ALLOW_THREADS
Martin v. Löwisafec8e32003-06-28 07:40:23 +00001256 if(PyErr_CheckSignals()) {
1257 Py_DECREF(buf);
1258 return NULL;
1259 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001260 if (err == SSL_ERROR_WANT_READ) {
Guido van Rossum780b80d2007-08-27 18:42:23 +00001261 sockstate =
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001262 check_socket_and_wait_for_timeout(self->Socket, 0);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001263 } else if (err == SSL_ERROR_WANT_WRITE) {
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001264 sockstate =
1265 check_socket_and_wait_for_timeout(self->Socket, 1);
1266 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1267 (SSL_get_shutdown(self->ssl) ==
Guido van Rossum780b80d2007-08-27 18:42:23 +00001268 SSL_RECEIVED_SHUTDOWN))
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001269 {
1270 _PyString_Resize(&buf, 0);
1271 return buf;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001272 } else {
1273 sockstate = SOCKET_OPERATION_OK;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001274 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001275 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1276 PyErr_SetString(PySSLErrorObject,
1277 "The read operation timed out");
Martin v. Löwisafec8e32003-06-28 07:40:23 +00001278 Py_DECREF(buf);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001279 return NULL;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001280 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1281 break;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001282 }
1283 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001284 if (count <= 0) {
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001285 Py_DECREF(buf);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001286 return PySSL_SetError(self, count, __FILE__, __LINE__);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001287 }
Tim Peters5de98422002-04-27 18:44:32 +00001288 if (count != len)
1289 _PyString_Resize(&buf, count);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001290 return buf;
1291}
1292
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001293PyDoc_STRVAR(PySSL_SSLread_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001294"read([len]) -> string\n\
1295\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001296Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001297
Bill Janssen98d19da2007-09-10 21:51:02 +00001298static PyObject *PySSL_SSLshutdown(PySSLObject *self)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001299{
1300 int err;
1301
1302 /* Guard against closed socket */
1303 if (self->Socket->sock_fd < 0) {
1304 PyErr_SetString(PySSLErrorObject,
1305 "Underlying socket has been closed.");
1306 return NULL;
1307 }
1308
Bill Janssen98d19da2007-09-10 21:51:02 +00001309 PySSL_BEGIN_ALLOW_THREADS
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001310 err = SSL_shutdown(self->ssl);
1311 if (err == 0) {
1312 /* we need to call it again to finish the shutdown */
1313 err = SSL_shutdown(self->ssl);
1314 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001315 PySSL_END_ALLOW_THREADS
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001316
1317 if (err < 0)
1318 return PySSL_SetError(self, err, __FILE__, __LINE__);
1319 else {
1320 Py_INCREF(self->Socket);
1321 return (PyObject *) (self->Socket);
1322 }
1323}
1324
1325PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1326"shutdown(s) -> socket\n\
1327\n\
1328Does the SSL shutdown handshake with the remote end, and returns\n\
1329the underlying socket object.");
1330
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001331static PyMethodDef PySSLMethods[] = {
1332 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
Bill Janssen98d19da2007-09-10 21:51:02 +00001333 PySSL_SSLwrite_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001334 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
Bill Janssen98d19da2007-09-10 21:51:02 +00001335 PySSL_SSLread_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001336 {"server", (PyCFunction)PySSL_server, METH_NOARGS},
1337 {"issuer", (PyCFunction)PySSL_issuer, METH_NOARGS},
Bill Janssen98d19da2007-09-10 21:51:02 +00001338 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1339 PySSL_peercert_doc},
1340 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Guido van Rossum780b80d2007-08-27 18:42:23 +00001341 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1342 PySSL_SSLshutdown_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001343 {NULL, NULL}
1344};
1345
1346static PyObject *PySSL_getattr(PySSLObject *self, char *name)
1347{
1348 return Py_FindMethod(PySSLMethods, (PyObject *)self, name);
1349}
1350
Jeremy Hylton938ace62002-07-17 16:30:39 +00001351static PyTypeObject PySSL_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001352 PyVarObject_HEAD_INIT(NULL, 0)
Guido van Rossum780b80d2007-08-27 18:42:23 +00001353 "ssl.SSLContext", /*tp_name*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001354 sizeof(PySSLObject), /*tp_basicsize*/
1355 0, /*tp_itemsize*/
1356 /* methods */
1357 (destructor)PySSL_dealloc, /*tp_dealloc*/
1358 0, /*tp_print*/
1359 (getattrfunc)PySSL_getattr, /*tp_getattr*/
1360 0, /*tp_setattr*/
1361 0, /*tp_compare*/
1362 0, /*tp_repr*/
1363 0, /*tp_as_number*/
1364 0, /*tp_as_sequence*/
1365 0, /*tp_as_mapping*/
1366 0, /*tp_hash*/
1367};
1368
1369#ifdef HAVE_OPENSSL_RAND
1370
1371/* helper routines for seeding the SSL PRNG */
1372static PyObject *
1373PySSL_RAND_add(PyObject *self, PyObject *args)
1374{
1375 char *buf;
1376 int len;
1377 double entropy;
1378
1379 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
1380 return NULL;
1381 RAND_add(buf, len, entropy);
1382 Py_INCREF(Py_None);
1383 return Py_None;
1384}
1385
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001386PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001387"RAND_add(string, entropy)\n\
1388\n\
1389Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00001390bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001391
1392static PyObject *
1393PySSL_RAND_status(PyObject *self)
1394{
1395 return PyInt_FromLong(RAND_status());
1396}
1397
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001398PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001399"RAND_status() -> 0 or 1\n\
1400\n\
1401Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1402It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001403using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001404
1405static PyObject *
1406PySSL_RAND_egd(PyObject *self, PyObject *arg)
1407{
1408 int bytes;
1409
1410 if (!PyString_Check(arg))
1411 return PyErr_Format(PyExc_TypeError,
1412 "RAND_egd() expected string, found %s",
Martin v. Löwis68192102007-07-21 06:55:02 +00001413 Py_Type(arg)->tp_name);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001414 bytes = RAND_egd(PyString_AS_STRING(arg));
1415 if (bytes == -1) {
1416 PyErr_SetString(PySSLErrorObject,
1417 "EGD connection failed or EGD did not return "
1418 "enough data to seed the PRNG");
1419 return NULL;
1420 }
1421 return PyInt_FromLong(bytes);
1422}
1423
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001424PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001425"RAND_egd(path) -> bytes\n\
1426\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00001427Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1428Returns number of bytes read. Raises SSLError if connection to EGD\n\
1429fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001430
1431#endif
1432
1433/* List of functions exported by this module. */
1434
1435static PyMethodDef PySSL_methods[] = {
Guido van Rossum780b80d2007-08-27 18:42:23 +00001436 {"sslwrap", PySSL_sslwrap,
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001437 METH_VARARGS, ssl_doc},
Bill Janssen98d19da2007-09-10 21:51:02 +00001438 {"_test_decode_cert", PySSL_test_decode_certificate,
1439 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001440#ifdef HAVE_OPENSSL_RAND
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001441 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001442 PySSL_RAND_add_doc},
1443 {"RAND_egd", PySSL_RAND_egd, METH_O,
1444 PySSL_RAND_egd_doc},
1445 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1446 PySSL_RAND_status_doc},
1447#endif
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001448 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001449};
1450
1451
Bill Janssen98d19da2007-09-10 21:51:02 +00001452#ifdef WITH_THREAD
1453
1454/* an implementation of OpenSSL threading operations in terms
1455 of the Python C thread library */
1456
1457static PyThread_type_lock *_ssl_locks = NULL;
1458
1459static unsigned long _ssl_thread_id_function (void) {
1460 return PyThread_get_thread_ident();
1461}
1462
1463static void _ssl_thread_locking_function (int mode, int n, const char *file, int line) {
1464 /* this function is needed to perform locking on shared data
1465 structures. (Note that OpenSSL uses a number of global data
1466 structures that will be implicitly shared whenever multiple threads
1467 use OpenSSL.) Multi-threaded applications will crash at random if
1468 it is not set.
1469
1470 locking_function() must be able to handle up to CRYPTO_num_locks()
1471 different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and
1472 releases it otherwise.
1473
1474 file and line are the file number of the function setting the
1475 lock. They can be useful for debugging.
1476 */
1477
1478 if ((_ssl_locks == NULL) ||
1479 (n < 0) || (n >= _ssl_locks_count))
1480 return;
1481
1482 if (mode & CRYPTO_LOCK) {
1483 PyThread_acquire_lock(_ssl_locks[n], 1);
1484 } else {
1485 PyThread_release_lock(_ssl_locks[n]);
1486 }
1487}
1488
1489static int _setup_ssl_threads(void) {
1490
1491 int i;
1492
1493 if (_ssl_locks == NULL) {
1494 _ssl_locks_count = CRYPTO_num_locks();
1495 _ssl_locks = (PyThread_type_lock *)
1496 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1497 if (_ssl_locks == NULL)
1498 return 0;
1499 memset(_ssl_locks, 0, sizeof(PyThread_type_lock) * _ssl_locks_count);
1500 for (i = 0; i < _ssl_locks_count; i++) {
1501 _ssl_locks[i] = PyThread_allocate_lock();
1502 if (_ssl_locks[i] == NULL) {
1503 int j;
1504 for (j = 0; j < i; j++) {
1505 PyThread_free_lock(_ssl_locks[j]);
1506 }
1507 free(_ssl_locks);
1508 return 0;
1509 }
1510 }
1511 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1512 CRYPTO_set_id_callback(_ssl_thread_id_function);
1513 }
1514 return 1;
1515}
1516
1517#endif /* def HAVE_THREAD */
1518
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001519PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001520"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001521for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001522
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001523PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001524init_ssl(void)
1525{
1526 PyObject *m, *d;
1527
Martin v. Löwis68192102007-07-21 06:55:02 +00001528 Py_Type(&PySSL_Type) = &PyType_Type;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001529
1530 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001531 if (m == NULL)
1532 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001533 d = PyModule_GetDict(m);
1534
1535 /* Load _socket module and its C API */
1536 if (PySocketModule_ImportModuleAndAPI())
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001537 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001538
1539 /* Init OpenSSL */
1540 SSL_load_error_strings();
Bill Janssen98d19da2007-09-10 21:51:02 +00001541#ifdef WITH_THREAD
1542 /* note that this will start threading if not already started */
1543 if (!_setup_ssl_threads()) {
1544 return;
1545 }
1546#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001547 SSLeay_add_ssl_algorithms();
1548
1549 /* Add symbols to module dict */
Bill Janssen98d19da2007-09-10 21:51:02 +00001550 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001551 PySocketModule.error,
1552 NULL);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001553 if (PySSLErrorObject == NULL)
1554 return;
Bill Janssen98d19da2007-09-10 21:51:02 +00001555 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001556 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001557 if (PyDict_SetItemString(d, "SSLType",
1558 (PyObject *)&PySSL_Type) != 0)
1559 return;
1560 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001561 PY_SSL_ERROR_ZERO_RETURN);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001562 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001563 PY_SSL_ERROR_WANT_READ);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001564 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001565 PY_SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001566 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001567 PY_SSL_ERROR_WANT_X509_LOOKUP);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001568 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001569 PY_SSL_ERROR_SYSCALL);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001570 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001571 PY_SSL_ERROR_SSL);
1572 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1573 PY_SSL_ERROR_WANT_CONNECT);
1574 /* non ssl.h errorcodes */
1575 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1576 PY_SSL_ERROR_EOF);
1577 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1578 PY_SSL_ERROR_INVALID_ERROR_CODE);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001579 /* cert requirements */
1580 PyModule_AddIntConstant(m, "CERT_NONE",
1581 PY_SSL_CERT_NONE);
1582 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1583 PY_SSL_CERT_OPTIONAL);
1584 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1585 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001586
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001587 /* protocol versions */
1588 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1589 PY_SSL_VERSION_SSL2);
1590 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1591 PY_SSL_VERSION_SSL3);
1592 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1593 PY_SSL_VERSION_SSL23);
1594 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1595 PY_SSL_VERSION_TLS1);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001596}