blob: e89e5b776a9d5716c76eee1ce7652a9e7b102ff5 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
17#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000018
Thomas Wouters1b7f8912007-09-19 03:06:30 +000019#ifdef WITH_THREAD
20#include "pythread.h"
21#define PySSL_BEGIN_ALLOW_THREADS { \
Bill Janssen6e027db2007-11-15 22:23:56 +000022 PyThreadState *_save = NULL; \
Thomas Wouters1b7f8912007-09-19 03:06:30 +000023 if (_ssl_locks_count>0) {_save = PyEval_SaveThread();}
24#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)};
25#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()};
26#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \
27 }
28
29#else /* no WITH_THREAD */
30
31#define PySSL_BEGIN_ALLOW_THREADS
32#define PySSL_BLOCK_THREADS
33#define PySSL_UNBLOCK_THREADS
34#define PySSL_END_ALLOW_THREADS
35
36#endif
37
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000038enum py_ssl_error {
39 /* these mirror ssl.h */
Thomas Woutersed03b412007-08-28 21:37:11 +000040 PY_SSL_ERROR_NONE,
41 PY_SSL_ERROR_SSL,
42 PY_SSL_ERROR_WANT_READ,
43 PY_SSL_ERROR_WANT_WRITE,
44 PY_SSL_ERROR_WANT_X509_LOOKUP,
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000045 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
Thomas Woutersed03b412007-08-28 21:37:11 +000046 PY_SSL_ERROR_ZERO_RETURN,
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000047 PY_SSL_ERROR_WANT_CONNECT,
Thomas Woutersed03b412007-08-28 21:37:11 +000048 /* start of non ssl.h errorcodes */
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000049 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
Bill Janssen54cc54c2007-12-14 22:08:56 +000050 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000051 PY_SSL_ERROR_INVALID_ERROR_CODE
52};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000053
Thomas Woutersed03b412007-08-28 21:37:11 +000054enum py_ssl_server_or_client {
55 PY_SSL_CLIENT,
56 PY_SSL_SERVER
57};
58
59enum py_ssl_cert_requirements {
60 PY_SSL_CERT_NONE,
61 PY_SSL_CERT_OPTIONAL,
62 PY_SSL_CERT_REQUIRED
63};
64
65enum py_ssl_version {
66 PY_SSL_VERSION_SSL2,
67 PY_SSL_VERSION_SSL3,
68 PY_SSL_VERSION_SSL23,
69 PY_SSL_VERSION_TLS1,
70};
71
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000072/* Include symbols from _socket module */
73#include "socketmodule.h"
74
Benjamin Petersonb173f782009-05-05 22:31:58 +000075static PySocketModule_APIObject PySocketModule;
76
Thomas Woutersed03b412007-08-28 21:37:11 +000077#if defined(HAVE_POLL_H)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000078#include <poll.h>
79#elif defined(HAVE_SYS_POLL_H)
80#include <sys/poll.h>
81#endif
82
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000083/* Include OpenSSL header files */
84#include "openssl/rsa.h"
85#include "openssl/crypto.h"
86#include "openssl/x509.h"
Thomas Wouters1b7f8912007-09-19 03:06:30 +000087#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000088#include "openssl/pem.h"
89#include "openssl/ssl.h"
90#include "openssl/err.h"
91#include "openssl/rand.h"
92
93/* SSL error object */
94static PyObject *PySSLErrorObject;
95
Thomas Wouters1b7f8912007-09-19 03:06:30 +000096#ifdef WITH_THREAD
97
98/* serves as a flag to see whether we've initialized the SSL thread support. */
99/* 0 means no, greater than 0 means yes */
100
101static unsigned int _ssl_locks_count = 0;
102
103#endif /* def WITH_THREAD */
104
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000105/* SSL socket object */
106
107#define X509_NAME_MAXLEN 256
108
109/* RAND_* APIs got added to OpenSSL in 0.9.5 */
110#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
111# define HAVE_OPENSSL_RAND 1
112#else
113# undef HAVE_OPENSSL_RAND
114#endif
115
116typedef struct {
117 PyObject_HEAD
Bill Janssen54cc54c2007-12-14 22:08:56 +0000118 PyObject *Socket; /* weakref to socket on which we're layered */
Thomas Woutersed03b412007-08-28 21:37:11 +0000119 SSL_CTX* ctx;
120 SSL* ssl;
121 X509* peer_cert;
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +0000122 int shutdown_seen_zero;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000123
124} PySSLObject;
125
Jeremy Hylton938ace62002-07-17 16:30:39 +0000126static PyTypeObject PySSL_Type;
127static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args);
128static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000129static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000130 int writing);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000131static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args);
132static PyObject *PySSL_cipher(PySSLObject *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000133
Christian Heimes90aa7642007-12-19 02:45:37 +0000134#define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000135
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000136typedef enum {
137 SOCKET_IS_NONBLOCKING,
138 SOCKET_IS_BLOCKING,
139 SOCKET_HAS_TIMED_OUT,
140 SOCKET_HAS_BEEN_CLOSED,
Neal Norwitz389cea82006-02-13 00:35:21 +0000141 SOCKET_TOO_LARGE_FOR_SELECT,
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000142 SOCKET_OPERATION_OK
143} timeout_state;
144
Thomas Woutersed03b412007-08-28 21:37:11 +0000145/* Wrap error strings with filename and line # */
146#define STRINGIFY1(x) #x
147#define STRINGIFY2(x) STRINGIFY1(x)
148#define ERRSTR1(x,y,z) (x ":" y ": " z)
149#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
150
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000151/* XXX It might be helpful to augment the error message generated
152 below with the name of the SSL function that generated the error.
153 I expect it's obvious most of the time.
154*/
155
156static PyObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000157PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000158{
Thomas Woutersed03b412007-08-28 21:37:11 +0000159 PyObject *v;
160 char buf[2048];
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000161 char *errstr;
162 int err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000163 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000164
165 assert(ret <= 0);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000166
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000167 if (obj->ssl != NULL) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000168 err = SSL_get_error(obj->ssl, ret);
169
170 switch (err) {
171 case SSL_ERROR_ZERO_RETURN:
172 errstr = "TLS/SSL connection has been closed";
173 p = PY_SSL_ERROR_ZERO_RETURN;
174 break;
175 case SSL_ERROR_WANT_READ:
176 errstr = "The operation did not complete (read)";
177 p = PY_SSL_ERROR_WANT_READ;
178 break;
179 case SSL_ERROR_WANT_WRITE:
180 p = PY_SSL_ERROR_WANT_WRITE;
181 errstr = "The operation did not complete (write)";
182 break;
183 case SSL_ERROR_WANT_X509_LOOKUP:
184 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
185 errstr =
186 "The operation did not complete (X509 lookup)";
187 break;
188 case SSL_ERROR_WANT_CONNECT:
189 p = PY_SSL_ERROR_WANT_CONNECT;
190 errstr = "The operation did not complete (connect)";
191 break;
192 case SSL_ERROR_SYSCALL:
193 {
194 unsigned long e = ERR_get_error();
195 if (e == 0) {
Bill Janssen54cc54c2007-12-14 22:08:56 +0000196 PySocketSockObject *s
197 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
198 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000199 p = PY_SSL_ERROR_EOF;
200 errstr =
201 "EOF occurred in violation of protocol";
202 } else if (ret == -1) {
203 /* underlying BIO reported an I/O error */
Bill Janssen54cc54c2007-12-14 22:08:56 +0000204 return s->errorhandler();
Thomas Woutersed03b412007-08-28 21:37:11 +0000205 } else { /* possible? */
206 p = PY_SSL_ERROR_SYSCALL;
207 errstr = "Some I/O error occurred";
208 }
209 } else {
Jeremy Hylton4e547302002-07-02 18:25:00 +0000210 p = PY_SSL_ERROR_SYSCALL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000211 /* XXX Protected by global interpreter lock */
212 errstr = ERR_error_string(e, NULL);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000213 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000214 break;
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000215 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000216 case SSL_ERROR_SSL:
217 {
218 unsigned long e = ERR_get_error();
219 p = PY_SSL_ERROR_SSL;
220 if (e != 0)
221 /* XXX Protected by global interpreter lock */
222 errstr = ERR_error_string(e, NULL);
223 else { /* possible? */
224 errstr =
225 "A failure in the SSL library occurred";
226 }
227 break;
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000228 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000229 default:
230 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
231 errstr = "Invalid error code";
232 }
233 } else {
234 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000235 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000236 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
237 v = Py_BuildValue("(is)", p, buf);
238 if (v != NULL) {
239 PyErr_SetObject(PySSLErrorObject, v);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000240 Py_DECREF(v);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000241 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000242 return NULL;
243}
244
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000245static PyObject *
246_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
247
248 char buf[2048];
249 PyObject *v;
250
251 if (errstr == NULL) {
252 errcode = ERR_peek_last_error();
253 errstr = ERR_error_string(errcode, NULL);
254 }
255 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
256 v = Py_BuildValue("(is)", errcode, buf);
257 if (v != NULL) {
258 PyErr_SetObject(PySSLErrorObject, v);
259 Py_DECREF(v);
260 }
261 return NULL;
262}
263
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000264static PySSLObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000265newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file,
266 enum py_ssl_server_or_client socket_type,
267 enum py_ssl_cert_requirements certreq,
268 enum py_ssl_version proto_version,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000269 char *cacerts_file, char *ciphers)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000270{
271 PySSLObject *self;
272 char *errstr = NULL;
273 int ret;
Thomas Woutersed03b412007-08-28 21:37:11 +0000274 int verification_mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000275
Guido van Rossume6650f92007-12-06 19:05:55 +0000276 self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000277 if (self == NULL)
278 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000279 self->peer_cert = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000280 self->ssl = NULL;
281 self->ctx = NULL;
282 self->Socket = NULL;
283
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000284 /* Make sure the SSL error state is initialized */
285 (void) ERR_get_state();
286 ERR_clear_error();
287
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000288 if ((key_file && !cert_file) || (!key_file && cert_file)) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000289 errstr = ERRSTR("Both the key & certificate files "
290 "must be specified");
291 goto fail;
292 }
293
294 if ((socket_type == PY_SSL_SERVER) &&
295 ((key_file == NULL) || (cert_file == NULL))) {
296 errstr = ERRSTR("Both the key & certificate files "
297 "must be specified for server-side operation");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000298 goto fail;
299 }
300
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000301 PySSL_BEGIN_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000302 if (proto_version == PY_SSL_VERSION_TLS1)
303 self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */
304 else if (proto_version == PY_SSL_VERSION_SSL3)
305 self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */
306 else if (proto_version == PY_SSL_VERSION_SSL2)
307 self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000308 else if (proto_version == PY_SSL_VERSION_SSL23)
Thomas Woutersed03b412007-08-28 21:37:11 +0000309 self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000310 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000311
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000312 if (self->ctx == NULL) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000313 errstr = ERRSTR("Invalid SSL protocol variant specified.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000314 goto fail;
315 }
316
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000317 if (ciphers != NULL) {
318 ret = SSL_CTX_set_cipher_list(self->ctx, ciphers);
319 if (ret == 0) {
320 errstr = ERRSTR("No cipher can be selected.");
321 goto fail;
322 }
323 }
324
Thomas Woutersed03b412007-08-28 21:37:11 +0000325 if (certreq != PY_SSL_CERT_NONE) {
326 if (cacerts_file == NULL) {
327 errstr = ERRSTR("No root certificates specified for "
328 "verification of other-side certificates.");
329 goto fail;
330 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000331 PySSL_BEGIN_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000332 ret = SSL_CTX_load_verify_locations(self->ctx,
333 cacerts_file,
334 NULL);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000335 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000336 if (ret != 1) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000337 _setSSLError(NULL, 0, __FILE__, __LINE__);
Thomas Woutersed03b412007-08-28 21:37:11 +0000338 goto fail;
339 }
340 }
341 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000342 if (key_file) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000343 PySSL_BEGIN_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000344 ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
Thomas Woutersed03b412007-08-28 21:37:11 +0000345 SSL_FILETYPE_PEM);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000346 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000347 if (ret != 1) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000348 _setSSLError(NULL, ret, __FILE__, __LINE__);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000349 goto fail;
350 }
351
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000352 PySSL_BEGIN_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000353 ret = SSL_CTX_use_certificate_chain_file(self->ctx,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000354 cert_file);
355 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000356 if (ret != 1) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000357 /*
358 fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
359 ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
360 */
361 if (ERR_peek_last_error() != 0) {
362 _setSSLError(NULL, ret, __FILE__, __LINE__);
363 goto fail;
364 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000365 }
366 }
367
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000368 /* ssl compatibility */
369 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
370
Thomas Woutersed03b412007-08-28 21:37:11 +0000371 verification_mode = SSL_VERIFY_NONE;
372 if (certreq == PY_SSL_CERT_OPTIONAL)
373 verification_mode = SSL_VERIFY_PEER;
374 else if (certreq == PY_SSL_CERT_REQUIRED)
375 verification_mode = (SSL_VERIFY_PEER |
376 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
377 SSL_CTX_set_verify(self->ctx, verification_mode,
378 NULL); /* set verify lvl */
379
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000380 PySSL_BEGIN_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000381 self->ssl = SSL_new(self->ctx); /* New ssl struct */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000382 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000383 SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000384#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou5f1c38f2010-03-26 19:32:24 +0000385 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000386#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000387
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000388 /* If the socket is in non-blocking mode or timeout mode, set the BIO
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000389 * to non-blocking mode (blocking is the default)
390 */
391 if (Sock->sock_timeout >= 0.0) {
392 /* Set both the read and write BIO's to non-blocking mode */
393 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
394 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
395 }
396
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000397 PySSL_BEGIN_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000398 if (socket_type == PY_SSL_CLIENT)
399 SSL_set_connect_state(self->ssl);
400 else
401 SSL_set_accept_state(self->ssl);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000402 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000403
Bill Janssen54cc54c2007-12-14 22:08:56 +0000404 self->Socket = PyWeakref_NewRef((PyObject *) Sock, Py_None);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000405 return self;
406 fail:
407 if (errstr)
408 PyErr_SetString(PySSLErrorObject, errstr);
409 Py_DECREF(self);
410 return NULL;
411}
412
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000413static PyObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000414PySSL_sslwrap(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000415{
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000416 PySocketSockObject *Sock;
Thomas Woutersed03b412007-08-28 21:37:11 +0000417 int server_side = 0;
418 int verification_mode = PY_SSL_CERT_NONE;
419 int protocol = PY_SSL_VERSION_SSL23;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000420 char *key_file = NULL;
421 char *cert_file = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000422 char *cacerts_file = NULL;
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000423 char *ciphers = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000424
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000425 if (!PyArg_ParseTuple(args, "O!i|zziizz:sslwrap",
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000426 PySocketModule.Sock_Type,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000427 &Sock,
Thomas Woutersed03b412007-08-28 21:37:11 +0000428 &server_side,
429 &key_file, &cert_file,
430 &verification_mode, &protocol,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000431 &cacerts_file, &ciphers))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000432 return NULL;
433
Thomas Woutersed03b412007-08-28 21:37:11 +0000434 /*
435 fprintf(stderr,
436 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
437 "protocol %d, certs %p\n",
438 server_side, key_file, cert_file, verification_mode,
439 protocol, cacerts_file);
440 */
441
442 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
443 server_side, verification_mode,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000444 protocol, cacerts_file,
445 ciphers);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000446}
447
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000448PyDoc_STRVAR(ssl_doc,
Thomas Woutersed03b412007-08-28 21:37:11 +0000449"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000450" cacertsfile, ciphers]) -> sslobject");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000451
452/* SSL object methods */
453
Bill Janssen6e027db2007-11-15 22:23:56 +0000454static PyObject *PySSL_SSLdo_handshake(PySSLObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000455{
Bill Janssen6e027db2007-11-15 22:23:56 +0000456 int ret;
457 int err;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000458 int sockstate, nonblocking;
459 PySocketSockObject *sock
460 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
461
462 if (((PyObject*)sock) == Py_None) {
463 _setSSLError("Underlying socket connection gone",
464 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
465 return NULL;
466 }
467
468 /* just in case the blocking state of the socket has been changed */
469 nonblocking = (sock->sock_timeout >= 0.0);
470 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
471 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000472
Bill Janssen6e027db2007-11-15 22:23:56 +0000473 /* Actually negotiate SSL connection */
474 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
475 sockstate = 0;
476 do {
477 PySSL_BEGIN_ALLOW_THREADS
478 ret = SSL_do_handshake(self->ssl);
479 err = SSL_get_error(self->ssl, ret);
480 PySSL_END_ALLOW_THREADS
481 if(PyErr_CheckSignals()) {
482 return NULL;
483 }
484 if (err == SSL_ERROR_WANT_READ) {
Bill Janssen54cc54c2007-12-14 22:08:56 +0000485 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Bill Janssen6e027db2007-11-15 22:23:56 +0000486 } else if (err == SSL_ERROR_WANT_WRITE) {
Bill Janssen54cc54c2007-12-14 22:08:56 +0000487 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Bill Janssen6e027db2007-11-15 22:23:56 +0000488 } else {
489 sockstate = SOCKET_OPERATION_OK;
490 }
491 if (sockstate == SOCKET_HAS_TIMED_OUT) {
492 PyErr_SetString(PySSLErrorObject,
493 ERRSTR("The handshake operation timed out"));
494 return NULL;
495 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
496 PyErr_SetString(PySSLErrorObject,
497 ERRSTR("Underlying socket has been closed."));
498 return NULL;
499 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
500 PyErr_SetString(PySSLErrorObject,
501 ERRSTR("Underlying socket too large for select()."));
502 return NULL;
503 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
504 break;
505 }
506 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
507 if (ret < 1)
508 return PySSL_SetError(self, ret, __FILE__, __LINE__);
509 self->ssl->debug = 1;
510
511 if (self->peer_cert)
512 X509_free (self->peer_cert);
513 PySSL_BEGIN_ALLOW_THREADS
514 self->peer_cert = SSL_get_peer_certificate(self->ssl);
515 PySSL_END_ALLOW_THREADS
516
517 Py_INCREF(Py_None);
518 return Py_None;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000519}
520
Thomas Woutersed03b412007-08-28 21:37:11 +0000521static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000522_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000523
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000524 char namebuf[X509_NAME_MAXLEN];
525 int buflen;
526 PyObject *name_obj;
527 PyObject *value_obj;
528 PyObject *attr;
529 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000530
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000531 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
532 if (buflen < 0) {
533 _setSSLError(NULL, 0, __FILE__, __LINE__);
534 goto fail;
Thomas Woutersed03b412007-08-28 21:37:11 +0000535 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000536 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000537 if (name_obj == NULL)
538 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000539
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000540 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
541 if (buflen < 0) {
542 _setSSLError(NULL, 0, __FILE__, __LINE__);
543 Py_DECREF(name_obj);
544 goto fail;
545 }
546 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
547 buflen, "strict");
548 OPENSSL_free(valuebuf);
549 if (value_obj == NULL) {
550 Py_DECREF(name_obj);
551 goto fail;
552 }
553 attr = PyTuple_New(2);
554 if (attr == NULL) {
555 Py_DECREF(name_obj);
556 Py_DECREF(value_obj);
557 goto fail;
558 }
559 PyTuple_SET_ITEM(attr, 0, name_obj);
560 PyTuple_SET_ITEM(attr, 1, value_obj);
561 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000562
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000563 fail:
Thomas Woutersed03b412007-08-28 21:37:11 +0000564 return NULL;
565}
566
567static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000568_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000569{
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000570 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
571 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
572 PyObject *rdnt;
573 PyObject *attr = NULL; /* tuple to hold an attribute */
574 int entry_count = X509_NAME_entry_count(xname);
575 X509_NAME_ENTRY *entry;
576 ASN1_OBJECT *name;
577 ASN1_STRING *value;
578 int index_counter;
579 int rdn_level = -1;
580 int retcode;
581
582 dn = PyList_New(0);
583 if (dn == NULL)
584 return NULL;
585 /* now create another tuple to hold the top-level RDN */
586 rdn = PyList_New(0);
587 if (rdn == NULL)
588 goto fail0;
589
590 for (index_counter = 0;
591 index_counter < entry_count;
592 index_counter++)
593 {
594 entry = X509_NAME_get_entry(xname, index_counter);
595
596 /* check to see if we've gotten to a new RDN */
597 if (rdn_level >= 0) {
598 if (rdn_level != entry->set) {
599 /* yes, new RDN */
600 /* add old RDN to DN */
601 rdnt = PyList_AsTuple(rdn);
602 Py_DECREF(rdn);
603 if (rdnt == NULL)
604 goto fail0;
605 retcode = PyList_Append(dn, rdnt);
606 Py_DECREF(rdnt);
607 if (retcode < 0)
608 goto fail0;
609 /* create new RDN */
610 rdn = PyList_New(0);
611 if (rdn == NULL)
612 goto fail0;
613 }
614 }
615 rdn_level = entry->set;
616
617 /* now add this attribute to the current RDN */
618 name = X509_NAME_ENTRY_get_object(entry);
619 value = X509_NAME_ENTRY_get_data(entry);
620 attr = _create_tuple_for_attribute(name, value);
621 /*
622 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
623 entry->set,
Christian Heimes72b710a2008-05-26 13:28:38 +0000624 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
625 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000626 */
627 if (attr == NULL)
628 goto fail1;
629 retcode = PyList_Append(rdn, attr);
630 Py_DECREF(attr);
631 if (retcode < 0)
632 goto fail1;
633 }
634 /* now, there's typically a dangling RDN */
635 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
636 rdnt = PyList_AsTuple(rdn);
637 Py_DECREF(rdn);
638 if (rdnt == NULL)
639 goto fail0;
640 retcode = PyList_Append(dn, rdnt);
641 Py_DECREF(rdnt);
642 if (retcode < 0)
643 goto fail0;
644 }
645
646 /* convert list to tuple */
647 rdnt = PyList_AsTuple(dn);
648 Py_DECREF(dn);
649 if (rdnt == NULL)
650 return NULL;
651 return rdnt;
652
653 fail1:
654 Py_XDECREF(rdn);
655
656 fail0:
657 Py_XDECREF(dn);
658 return NULL;
659}
660
661static PyObject *
662_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000663
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000664 /* this code follows the procedure outlined in
665 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
666 function to extract the STACK_OF(GENERAL_NAME),
667 then iterates through the stack to add the
668 names. */
669
670 int i, j;
671 PyObject *peer_alt_names = Py_None;
672 PyObject *v, *t;
673 X509_EXTENSION *ext = NULL;
674 GENERAL_NAMES *names = NULL;
675 GENERAL_NAME *name;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000676 X509V3_EXT_METHOD *method;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000677 BIO *biobuf = NULL;
678 char buf[2048];
679 char *vptr;
680 int len;
Victor Stinner7124a412010-03-02 22:48:17 +0000681 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
682#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
683 const unsigned char *p;
684#else
Benjamin Peterson0289b152009-06-28 17:22:03 +0000685 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000686#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000687
688 if (certificate == NULL)
689 return peer_alt_names;
690
691 /* get a memory buffer */
692 biobuf = BIO_new(BIO_s_mem());
693
694 i = 0;
695 while ((i = X509_get_ext_by_NID(
696 certificate, NID_subject_alt_name, i)) >= 0) {
697
698 if (peer_alt_names == Py_None) {
699 peer_alt_names = PyList_New(0);
700 if (peer_alt_names == NULL)
701 goto fail;
702 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000703
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000704 /* now decode the altName */
705 ext = X509_get_ext(certificate, i);
706 if(!(method = X509V3_EXT_get(ext))) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000707 PyErr_SetString
708 (PySSLErrorObject,
709 ERRSTR("No method for internalizing subjectAltName!"));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000710 goto fail;
711 }
712
713 p = ext->value->data;
Christian Heimes412dc9c2008-01-27 18:55:54 +0000714 if (method->it)
Bill Janssen6e027db2007-11-15 22:23:56 +0000715 names = (GENERAL_NAMES*)
716 (ASN1_item_d2i(NULL,
717 &p,
718 ext->value->length,
719 ASN1_ITEM_ptr(method->it)));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000720 else
Bill Janssen6e027db2007-11-15 22:23:56 +0000721 names = (GENERAL_NAMES*)
722 (method->d2i(NULL,
723 &p,
724 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000725
726 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
727
728 /* get a rendering of each name in the set of names */
729
730 name = sk_GENERAL_NAME_value(names, j);
731 if (name->type == GEN_DIRNAME) {
732
Bill Janssen6e027db2007-11-15 22:23:56 +0000733 /* we special-case DirName as a tuple of
734 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000735
736 t = PyTuple_New(2);
737 if (t == NULL) {
738 goto fail;
739 }
740
Bill Janssen6e027db2007-11-15 22:23:56 +0000741 v = PyUnicode_FromString("DirName");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000742 if (v == NULL) {
743 Py_DECREF(t);
744 goto fail;
745 }
746 PyTuple_SET_ITEM(t, 0, v);
747
748 v = _create_tuple_for_X509_NAME (name->d.dirn);
749 if (v == NULL) {
750 Py_DECREF(t);
751 goto fail;
752 }
753 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000754
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000755 } else {
756
757 /* for everything else, we use the OpenSSL print form */
758
759 (void) BIO_reset(biobuf);
760 GENERAL_NAME_print(biobuf, name);
761 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
762 if (len < 0) {
763 _setSSLError(NULL, 0, __FILE__, __LINE__);
764 goto fail;
765 }
766 vptr = strchr(buf, ':');
767 if (vptr == NULL)
768 goto fail;
769 t = PyTuple_New(2);
770 if (t == NULL)
771 goto fail;
Bill Janssen6e027db2007-11-15 22:23:56 +0000772 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000773 if (v == NULL) {
774 Py_DECREF(t);
775 goto fail;
776 }
777 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen6e027db2007-11-15 22:23:56 +0000778 v = PyUnicode_FromStringAndSize((vptr + 1),
779 (len - (vptr - buf + 1)));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000780 if (v == NULL) {
781 Py_DECREF(t);
782 goto fail;
783 }
784 PyTuple_SET_ITEM(t, 1, v);
785 }
786
787 /* and add that rendering to the list */
788
789 if (PyList_Append(peer_alt_names, t) < 0) {
790 Py_DECREF(t);
791 goto fail;
792 }
793 Py_DECREF(t);
794 }
795 }
796 BIO_free(biobuf);
797 if (peer_alt_names != Py_None) {
798 v = PyList_AsTuple(peer_alt_names);
799 Py_DECREF(peer_alt_names);
800 return v;
801 } else {
802 return peer_alt_names;
803 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000804
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000805
806 fail:
807 if (biobuf != NULL)
808 BIO_free(biobuf);
809
810 if (peer_alt_names != Py_None) {
811 Py_XDECREF(peer_alt_names);
812 }
813
814 return NULL;
815}
816
817static PyObject *
818_decode_certificate (X509 *certificate, int verbose) {
819
Thomas Woutersed03b412007-08-28 21:37:11 +0000820 PyObject *retval = NULL;
821 BIO *biobuf = NULL;
822 PyObject *peer;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000823 PyObject *peer_alt_names = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000824 PyObject *issuer;
825 PyObject *version;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000826 PyObject *sn_obj;
827 ASN1_INTEGER *serialNumber;
Thomas Woutersed03b412007-08-28 21:37:11 +0000828 char buf[2048];
829 int len;
830 ASN1_TIME *notBefore, *notAfter;
831 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000832
833 retval = PyDict_New();
834 if (retval == NULL)
835 return NULL;
836
Thomas Wouters89d996e2007-09-08 17:39:28 +0000837 peer = _create_tuple_for_X509_NAME(
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000838 X509_get_subject_name(certificate));
Thomas Woutersed03b412007-08-28 21:37:11 +0000839 if (peer == NULL)
840 goto fail0;
841 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
842 Py_DECREF(peer);
843 goto fail0;
844 }
845 Py_DECREF(peer);
846
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000847 if (verbose) {
848 issuer = _create_tuple_for_X509_NAME(
849 X509_get_issuer_name(certificate));
850 if (issuer == NULL)
851 goto fail0;
852 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
853 Py_DECREF(issuer);
854 goto fail0;
855 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000856 Py_DECREF(issuer);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000857
Christian Heimes217cfd12007-12-02 14:31:20 +0000858 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000859 if (PyDict_SetItemString(retval, "version", version) < 0) {
860 Py_DECREF(version);
861 goto fail0;
862 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000863 Py_DECREF(version);
Thomas Woutersed03b412007-08-28 21:37:11 +0000864 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000865
Thomas Woutersed03b412007-08-28 21:37:11 +0000866 /* get a memory buffer */
867 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000868
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000869 if (verbose) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000870
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000871 (void) BIO_reset(biobuf);
872 serialNumber = X509_get_serialNumber(certificate);
873 /* should not exceed 20 octets, 160 bits, so buf is big enough */
874 i2a_ASN1_INTEGER(biobuf, serialNumber);
875 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
876 if (len < 0) {
877 _setSSLError(NULL, 0, __FILE__, __LINE__);
878 goto fail1;
879 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000880 sn_obj = PyUnicode_FromStringAndSize(buf, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000881 if (sn_obj == NULL)
882 goto fail1;
883 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
884 Py_DECREF(sn_obj);
885 goto fail1;
886 }
887 Py_DECREF(sn_obj);
888
889 (void) BIO_reset(biobuf);
890 notBefore = X509_get_notBefore(certificate);
891 ASN1_TIME_print(biobuf, notBefore);
892 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
893 if (len < 0) {
894 _setSSLError(NULL, 0, __FILE__, __LINE__);
895 goto fail1;
896 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000897 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000898 if (pnotBefore == NULL)
899 goto fail1;
900 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
901 Py_DECREF(pnotBefore);
902 goto fail1;
903 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000904 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000905 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000906
907 (void) BIO_reset(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000908 notAfter = X509_get_notAfter(certificate);
Thomas Woutersed03b412007-08-28 21:37:11 +0000909 ASN1_TIME_print(biobuf, notAfter);
910 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000911 if (len < 0) {
912 _setSSLError(NULL, 0, __FILE__, __LINE__);
913 goto fail1;
914 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000915 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
Thomas Woutersed03b412007-08-28 21:37:11 +0000916 if (pnotAfter == NULL)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000917 goto fail1;
Thomas Woutersed03b412007-08-28 21:37:11 +0000918 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
919 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000920 goto fail1;
Thomas Woutersed03b412007-08-28 21:37:11 +0000921 }
922 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000923
924 /* Now look for subjectAltName */
925
926 peer_alt_names = _get_peer_alt_names(certificate);
927 if (peer_alt_names == NULL)
928 goto fail1;
929 else if (peer_alt_names != Py_None) {
930 if (PyDict_SetItemString(retval, "subjectAltName",
931 peer_alt_names) < 0) {
932 Py_DECREF(peer_alt_names);
933 goto fail1;
934 }
935 Py_DECREF(peer_alt_names);
936 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000937
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000938 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000939 return retval;
940
941 fail1:
942 if (biobuf != NULL)
943 BIO_free(biobuf);
944 fail0:
945 Py_XDECREF(retval);
946 return NULL;
947}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000948
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000949
950static PyObject *
951PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
952
953 PyObject *retval = NULL;
954 char *filename = NULL;
955 X509 *x=NULL;
956 BIO *cert;
957 int verbose = 1;
958
Bill Janssen6e027db2007-11-15 22:23:56 +0000959 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate",
960 &filename, &verbose))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000961 return NULL;
962
963 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000964 PyErr_SetString(PySSLErrorObject,
965 "Can't malloc memory to read file");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000966 goto fail0;
967 }
968
969 if (BIO_read_filename(cert,filename) <= 0) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000970 PyErr_SetString(PySSLErrorObject,
971 "Can't open file");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000972 goto fail0;
973 }
974
975 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
976 if (x == NULL) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000977 PyErr_SetString(PySSLErrorObject,
978 "Error decoding PEM-encoded file");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000979 goto fail0;
980 }
981
982 retval = _decode_certificate(x, verbose);
983
984 fail0:
Guido van Rossumf06628b2007-11-21 20:01:53 +0000985
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000986 if (cert != NULL) BIO_free(cert);
987 return retval;
988}
989
990
991static PyObject *
992PySSL_peercert(PySSLObject *self, PyObject *args)
993{
994 PyObject *retval = NULL;
995 int len;
996 int verification;
997 PyObject *binary_mode = Py_None;
998
999 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1000 return NULL;
1001
1002 if (!self->peer_cert)
1003 Py_RETURN_NONE;
1004
1005 if (PyObject_IsTrue(binary_mode)) {
1006 /* return cert in DER-encoded format */
1007
1008 unsigned char *bytes_buf = NULL;
1009
1010 bytes_buf = NULL;
1011 len = i2d_X509(self->peer_cert, &bytes_buf);
1012 if (len < 0) {
1013 PySSL_SetError(self, len, __FILE__, __LINE__);
1014 return NULL;
1015 }
Bill Janssen6e027db2007-11-15 22:23:56 +00001016 /* this is actually an immutable bytes sequence */
Christian Heimes72b710a2008-05-26 13:28:38 +00001017 retval = PyBytes_FromStringAndSize
Bill Janssen6e027db2007-11-15 22:23:56 +00001018 ((const char *) bytes_buf, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001019 OPENSSL_free(bytes_buf);
1020 return retval;
1021
1022 } else {
1023
1024 verification = SSL_CTX_get_verify_mode(self->ctx);
1025 if ((verification & SSL_VERIFY_PEER) == 0)
1026 return PyDict_New();
1027 else
1028 return _decode_certificate (self->peer_cert, 0);
1029 }
1030}
1031
1032PyDoc_STRVAR(PySSL_peercert_doc,
1033"peer_certificate([der=False]) -> certificate\n\
1034\n\
1035Returns the certificate for the peer. If no certificate was provided,\n\
1036returns None. If a certificate was provided, but not validated, returns\n\
1037an empty dictionary. Otherwise returns a dict containing information\n\
1038about the peer certificate.\n\
1039\n\
1040If the optional argument is True, returns a DER-encoded copy of the\n\
1041peer certificate, or None if no certificate was provided. This will\n\
1042return the certificate even if it wasn't validated.");
1043
1044static PyObject *PySSL_cipher (PySSLObject *self) {
1045
1046 PyObject *retval, *v;
1047 SSL_CIPHER *current;
1048 char *cipher_name;
1049 char *cipher_protocol;
1050
1051 if (self->ssl == NULL)
1052 return Py_None;
1053 current = SSL_get_current_cipher(self->ssl);
1054 if (current == NULL)
1055 return Py_None;
1056
1057 retval = PyTuple_New(3);
1058 if (retval == NULL)
1059 return NULL;
1060
1061 cipher_name = (char *) SSL_CIPHER_get_name(current);
1062 if (cipher_name == NULL) {
1063 PyTuple_SET_ITEM(retval, 0, Py_None);
1064 } else {
Bill Janssen6e027db2007-11-15 22:23:56 +00001065 v = PyUnicode_FromString(cipher_name);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001066 if (v == NULL)
1067 goto fail0;
1068 PyTuple_SET_ITEM(retval, 0, v);
1069 }
1070 cipher_protocol = SSL_CIPHER_get_version(current);
1071 if (cipher_protocol == NULL) {
1072 PyTuple_SET_ITEM(retval, 1, Py_None);
1073 } else {
Bill Janssen6e027db2007-11-15 22:23:56 +00001074 v = PyUnicode_FromString(cipher_protocol);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001075 if (v == NULL)
1076 goto fail0;
1077 PyTuple_SET_ITEM(retval, 1, v);
1078 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001079 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001080 if (v == NULL)
1081 goto fail0;
1082 PyTuple_SET_ITEM(retval, 2, v);
1083 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001084
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001085 fail0:
1086 Py_DECREF(retval);
1087 return NULL;
1088}
1089
Guido van Rossume6650f92007-12-06 19:05:55 +00001090static void PySSL_dealloc(PySSLObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001091{
Thomas Woutersed03b412007-08-28 21:37:11 +00001092 if (self->peer_cert) /* Possible not to have one? */
Guido van Rossume6650f92007-12-06 19:05:55 +00001093 X509_free (self->peer_cert);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001094 if (self->ssl)
Thomas Woutersed03b412007-08-28 21:37:11 +00001095 SSL_free(self->ssl);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001096 if (self->ctx)
Thomas Woutersed03b412007-08-28 21:37:11 +00001097 SSL_CTX_free(self->ctx);
Guido van Rossume6650f92007-12-06 19:05:55 +00001098 Py_XDECREF(self->Socket);
1099 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001100}
1101
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001102/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001103 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001104 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001105 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001106
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001107static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001108check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001109{
1110 fd_set fds;
1111 struct timeval tv;
1112 int rc;
1113
1114 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001115 if (s->sock_timeout < 0.0)
1116 return SOCKET_IS_BLOCKING;
1117 else if (s->sock_timeout == 0.0)
1118 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001119
1120 /* Guard against closed socket */
1121 if (s->sock_fd < 0)
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001122 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001123
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001124 /* Prefer poll, if available, since you can poll() any fd
1125 * which can't be done with select(). */
1126#ifdef HAVE_POLL
1127 {
1128 struct pollfd pollfd;
1129 int timeout;
1130
1131 pollfd.fd = s->sock_fd;
1132 pollfd.events = writing ? POLLOUT : POLLIN;
1133
1134 /* s->sock_timeout is in seconds, timeout in ms */
1135 timeout = (int)(s->sock_timeout * 1000 + 0.5);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001136 PySSL_BEGIN_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001137 rc = poll(&pollfd, 1, timeout);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001138 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001139
1140 goto normal_return;
1141 }
1142#endif
1143
Neal Norwitz082b2df2006-02-07 07:04:46 +00001144 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001145#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Neal Norwitz082b2df2006-02-07 07:04:46 +00001146 if (s->sock_fd >= FD_SETSIZE)
Neal Norwitz389cea82006-02-13 00:35:21 +00001147 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001148#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001149
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001150 /* Construct the arguments to select */
1151 tv.tv_sec = (int)s->sock_timeout;
1152 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1153 FD_ZERO(&fds);
1154 FD_SET(s->sock_fd, &fds);
1155
1156 /* See if the socket is ready */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001157 PySSL_BEGIN_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001158 if (writing)
1159 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1160 else
1161 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001162 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001163
Bill Janssen6e027db2007-11-15 22:23:56 +00001164#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001165normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001166#endif
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001167 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1168 (when we are able to write or when there's something to read) */
1169 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001170}
1171
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001172static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1173{
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001174 Py_buffer buf;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001175 int len;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001176 int sockstate;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001177 int err;
Bill Janssen6e027db2007-11-15 22:23:56 +00001178 int nonblocking;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001179 PySocketSockObject *sock
1180 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
1181
1182 if (((PyObject*)sock) == Py_None) {
1183 _setSSLError("Underlying socket connection gone",
1184 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1185 return NULL;
1186 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001187
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001188 if (!PyArg_ParseTuple(args, "y*:write", &buf))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001189 return NULL;
1190
Bill Janssen6e027db2007-11-15 22:23:56 +00001191 /* just in case the blocking state of the socket has been changed */
Bill Janssen54cc54c2007-12-14 22:08:56 +00001192 nonblocking = (sock->sock_timeout >= 0.0);
Bill Janssen6e027db2007-11-15 22:23:56 +00001193 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1194 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1195
Bill Janssen54cc54c2007-12-14 22:08:56 +00001196 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001197 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001198 PyErr_SetString(PySSLErrorObject,
1199 "The write operation timed out");
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001200 goto error;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001201 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001202 PyErr_SetString(PySSLErrorObject,
1203 "Underlying socket has been closed.");
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001204 goto error;
Neal Norwitz389cea82006-02-13 00:35:21 +00001205 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001206 PyErr_SetString(PySSLErrorObject,
1207 "Underlying socket too large for select().");
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001208 goto error;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001209 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001210 do {
1211 err = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001212 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001213 len = SSL_write(self->ssl, buf.buf, buf.len);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001214 err = SSL_get_error(self->ssl, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001215 PySSL_END_ALLOW_THREADS
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001216 if (PyErr_CheckSignals()) {
1217 goto error;
Martin v. Löwisafec8e32003-06-28 07:40:23 +00001218 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001219 if (err == SSL_ERROR_WANT_READ) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001220 sockstate =
Bill Janssen54cc54c2007-12-14 22:08:56 +00001221 check_socket_and_wait_for_timeout(sock, 0);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001222 } else if (err == SSL_ERROR_WANT_WRITE) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001223 sockstate =
Bill Janssen54cc54c2007-12-14 22:08:56 +00001224 check_socket_and_wait_for_timeout(sock, 1);
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001225 } else {
1226 sockstate = SOCKET_OPERATION_OK;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001227 }
Thomas Woutersed03b412007-08-28 21:37:11 +00001228 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1229 PyErr_SetString(PySSLErrorObject,
1230 "The write operation timed out");
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001231 goto error;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001232 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001233 PyErr_SetString(PySSLErrorObject,
1234 "Underlying socket has been closed.");
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001235 goto error;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001236 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1237 break;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001238 }
1239 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001240
1241 PyBuffer_Release(&buf);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001242 if (len > 0)
Christian Heimes217cfd12007-12-02 14:31:20 +00001243 return PyLong_FromLong(len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001244 else
Thomas Woutersed03b412007-08-28 21:37:11 +00001245 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001246
1247error:
1248 PyBuffer_Release(&buf);
1249 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001250}
1251
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001252PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001253"write(s) -> len\n\
1254\n\
1255Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001256of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001257
Bill Janssen6e027db2007-11-15 22:23:56 +00001258static PyObject *PySSL_SSLpending(PySSLObject *self)
1259{
1260 int count = 0;
1261
1262 PySSL_BEGIN_ALLOW_THREADS
1263 count = SSL_pending(self->ssl);
1264 PySSL_END_ALLOW_THREADS
1265 if (count < 0)
1266 return PySSL_SetError(self, count, __FILE__, __LINE__);
1267 else
Christian Heimes217cfd12007-12-02 14:31:20 +00001268 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001269}
1270
1271PyDoc_STRVAR(PySSL_SSLpending_doc,
1272"pending() -> count\n\
1273\n\
1274Returns the number of already decrypted bytes available for read,\n\
1275pending on the connection.\n");
1276
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001277static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1278{
Benjamin Peterson56420b42009-02-28 19:06:54 +00001279 PyObject *dest = NULL;
1280 Py_buffer buf;
Bill Janssen6e027db2007-11-15 22:23:56 +00001281 int buf_passed = 0;
1282 int count = -1;
Benjamin Peterson56420b42009-02-28 19:06:54 +00001283 char *mem;
1284 /* XXX this should use Py_ssize_t */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001285 int len = 1024;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001286 int sockstate;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001287 int err;
Bill Janssen6e027db2007-11-15 22:23:56 +00001288 int nonblocking;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001289 PySocketSockObject *sock
1290 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
1291
1292 if (((PyObject*)sock) == Py_None) {
1293 _setSSLError("Underlying socket connection gone",
1294 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1295 return NULL;
1296 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001297
Benjamin Peterson56420b42009-02-28 19:06:54 +00001298 if (!PyArg_ParseTuple(args, "|Oi:read", &dest, &count))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001299 return NULL;
Benjamin Peterson56420b42009-02-28 19:06:54 +00001300 if ((dest == NULL) || (dest == Py_None)) {
1301 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
Bill Janssen6e027db2007-11-15 22:23:56 +00001302 return NULL;
Benjamin Peterson56420b42009-02-28 19:06:54 +00001303 mem = PyByteArray_AS_STRING(dest);
1304 } else if (PyLong_Check(dest)) {
1305 len = PyLong_AS_LONG(dest);
1306 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
Bill Janssen6e027db2007-11-15 22:23:56 +00001307 return NULL;
Benjamin Peterson56420b42009-02-28 19:06:54 +00001308 mem = PyByteArray_AS_STRING(dest);
Bill Janssen6e027db2007-11-15 22:23:56 +00001309 } else {
Benjamin Peterson56420b42009-02-28 19:06:54 +00001310 if (PyObject_GetBuffer(dest, &buf, PyBUF_CONTIG) < 0)
Bill Janssen6e027db2007-11-15 22:23:56 +00001311 return NULL;
Benjamin Peterson56420b42009-02-28 19:06:54 +00001312 mem = buf.buf;
1313 len = buf.len;
Bill Janssen6e027db2007-11-15 22:23:56 +00001314 if ((count > 0) && (count <= len))
1315 len = count;
1316 buf_passed = 1;
1317 }
1318
1319 /* just in case the blocking state of the socket has been changed */
Bill Janssen54cc54c2007-12-14 22:08:56 +00001320 nonblocking = (sock->sock_timeout >= 0.0);
Bill Janssen6e027db2007-11-15 22:23:56 +00001321 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1322 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Thomas Woutersed03b412007-08-28 21:37:11 +00001323
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001324 /* first check if there are bytes ready to be read */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001325 PySSL_BEGIN_ALLOW_THREADS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001326 count = SSL_pending(self->ssl);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001327 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001328
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001329 if (!count) {
Bill Janssen54cc54c2007-12-14 22:08:56 +00001330 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001331 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001332 PyErr_SetString(PySSLErrorObject,
1333 "The read operation timed out");
Benjamin Peterson56420b42009-02-28 19:06:54 +00001334 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001335 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001336 PyErr_SetString(PySSLErrorObject,
1337 "Underlying socket too large for select().");
Benjamin Peterson56420b42009-02-28 19:06:54 +00001338 goto error;
Thomas Woutersed03b412007-08-28 21:37:11 +00001339 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001340 count = 0;
1341 goto done;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001342 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001343 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001344 do {
1345 err = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001346 PySSL_BEGIN_ALLOW_THREADS
Benjamin Peterson56420b42009-02-28 19:06:54 +00001347 count = SSL_read(self->ssl, mem, len);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001348 err = SSL_get_error(self->ssl, count);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001349 PySSL_END_ALLOW_THREADS
Benjamin Peterson56420b42009-02-28 19:06:54 +00001350 if (PyErr_CheckSignals())
1351 goto error;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001352 if (err == SSL_ERROR_WANT_READ) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001353 sockstate =
Bill Janssen54cc54c2007-12-14 22:08:56 +00001354 check_socket_and_wait_for_timeout(sock, 0);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001355 } else if (err == SSL_ERROR_WANT_WRITE) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001356 sockstate =
Bill Janssen54cc54c2007-12-14 22:08:56 +00001357 check_socket_and_wait_for_timeout(sock, 1);
Thomas Woutersed03b412007-08-28 21:37:11 +00001358 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1359 (SSL_get_shutdown(self->ssl) ==
1360 SSL_RECEIVED_SHUTDOWN))
1361 {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001362 count = 0;
1363 goto done;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001364 } else {
1365 sockstate = SOCKET_OPERATION_OK;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001366 }
Thomas Woutersed03b412007-08-28 21:37:11 +00001367 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1368 PyErr_SetString(PySSLErrorObject,
1369 "The read operation timed out");
Benjamin Peterson56420b42009-02-28 19:06:54 +00001370 goto error;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001371 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1372 break;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001373 }
1374 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Thomas Woutersed03b412007-08-28 21:37:11 +00001375 if (count <= 0) {
Benjamin Peterson56420b42009-02-28 19:06:54 +00001376 PySSL_SetError(self, count, __FILE__, __LINE__);
1377 goto error;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001378 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001379 done:
Bill Janssen6e027db2007-11-15 22:23:56 +00001380 if (!buf_passed) {
Benjamin Peterson56420b42009-02-28 19:06:54 +00001381 PyObject *res = PyBytes_FromStringAndSize(mem, count);
1382 Py_DECREF(dest);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001383 return res;
Bill Janssen6e027db2007-11-15 22:23:56 +00001384 } else {
Benjamin Peterson56420b42009-02-28 19:06:54 +00001385 PyBuffer_Release(&buf);
Christian Heimes217cfd12007-12-02 14:31:20 +00001386 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001387 }
Benjamin Peterson56420b42009-02-28 19:06:54 +00001388 error:
1389 if (!buf_passed) {
1390 Py_DECREF(dest);
1391 } else {
1392 PyBuffer_Release(&buf);
1393 }
1394 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001395}
1396
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001397PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001398"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001399\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001400Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001401
Bill Janssen40a0f662008-08-12 16:56:25 +00001402static PyObject *PySSL_SSLshutdown(PySSLObject *self)
1403{
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001404 int err, ssl_err, sockstate, nonblocking;
1405 int zeros = 0;
Bill Janssen40a0f662008-08-12 16:56:25 +00001406 PySocketSockObject *sock
1407 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
1408
1409 /* Guard against closed socket */
1410 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1411 _setSSLError("Underlying socket connection gone",
1412 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1413 return NULL;
1414 }
1415
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001416 /* Just in case the blocking state of the socket has been changed */
1417 nonblocking = (sock->sock_timeout >= 0.0);
1418 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1419 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1420
1421 while (1) {
1422 PySSL_BEGIN_ALLOW_THREADS
1423 /* Disable read-ahead so that unwrap can work correctly.
1424 * Otherwise OpenSSL might read in too much data,
1425 * eating clear text data that happens to be
1426 * transmitted after the SSL shutdown.
1427 * Should be safe to call repeatedly everytime this
1428 * function is used and the shutdown_seen_zero != 0
1429 * condition is met.
1430 */
1431 if (self->shutdown_seen_zero)
1432 SSL_set_read_ahead(self->ssl, 0);
Bill Janssen40a0f662008-08-12 16:56:25 +00001433 err = SSL_shutdown(self->ssl);
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001434 PySSL_END_ALLOW_THREADS
1435 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1436 if (err > 0)
1437 break;
1438 if (err == 0) {
1439 /* Don't loop endlessly; instead preserve legacy
1440 behaviour of trying SSL_shutdown() only twice.
1441 This looks necessary for OpenSSL < 0.9.8m */
1442 if (++zeros > 1)
1443 break;
1444 /* Shutdown was sent, now try receiving */
1445 self->shutdown_seen_zero = 1;
1446 continue;
1447 }
1448
1449 /* Possibly retry shutdown until timeout or failure */
1450 ssl_err = SSL_get_error(self->ssl, err);
1451 if (ssl_err == SSL_ERROR_WANT_READ)
1452 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1453 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1454 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1455 else
1456 break;
1457 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1458 if (ssl_err == SSL_ERROR_WANT_READ)
1459 PyErr_SetString(PySSLErrorObject,
1460 "The read operation timed out");
1461 else
1462 PyErr_SetString(PySSLErrorObject,
1463 "The write operation timed out");
1464 return NULL;
1465 }
1466 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1467 PyErr_SetString(PySSLErrorObject,
1468 "Underlying socket too large for select().");
1469 return NULL;
1470 }
1471 else if (sockstate != SOCKET_OPERATION_OK)
1472 /* Retain the SSL error code */
1473 break;
Bill Janssen40a0f662008-08-12 16:56:25 +00001474 }
Bill Janssen40a0f662008-08-12 16:56:25 +00001475
1476 if (err < 0)
1477 return PySSL_SetError(self, err, __FILE__, __LINE__);
1478 else {
1479 Py_INCREF(sock);
1480 return (PyObject *) sock;
1481 }
1482}
1483
1484PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1485"shutdown(s) -> socket\n\
1486\n\
1487Does the SSL shutdown handshake with the remote end, and returns\n\
1488the underlying socket object.");
1489
1490
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001491static PyMethodDef PySSLMethods[] = {
Bill Janssen6e027db2007-11-15 22:23:56 +00001492 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001493 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001494 PySSL_SSLwrite_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001495 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001496 PySSL_SSLread_doc},
Bill Janssen6e027db2007-11-15 22:23:56 +00001497 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1498 PySSL_SSLpending_doc},
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001499 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1500 PySSL_peercert_doc},
1501 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Bill Janssen40a0f662008-08-12 16:56:25 +00001502 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1503 PySSL_SSLshutdown_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001504 {NULL, NULL}
1505};
1506
Jeremy Hylton938ace62002-07-17 16:30:39 +00001507static PyTypeObject PySSL_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001508 PyVarObject_HEAD_INIT(NULL, 0)
Guido van Rossume6650f92007-12-06 19:05:55 +00001509 "ssl.SSLContext", /*tp_name*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001510 sizeof(PySSLObject), /*tp_basicsize*/
1511 0, /*tp_itemsize*/
1512 /* methods */
1513 (destructor)PySSL_dealloc, /*tp_dealloc*/
1514 0, /*tp_print*/
Amaury Forgeot d'Arce43d33a2008-07-02 20:50:16 +00001515 0, /*tp_getattr*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001516 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00001517 0, /*tp_reserved*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001518 0, /*tp_repr*/
1519 0, /*tp_as_number*/
1520 0, /*tp_as_sequence*/
1521 0, /*tp_as_mapping*/
1522 0, /*tp_hash*/
Amaury Forgeot d'Arce43d33a2008-07-02 20:50:16 +00001523 0, /*tp_call*/
1524 0, /*tp_str*/
1525 0, /*tp_getattro*/
1526 0, /*tp_setattro*/
1527 0, /*tp_as_buffer*/
1528 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1529 0, /*tp_doc*/
1530 0, /*tp_traverse*/
1531 0, /*tp_clear*/
1532 0, /*tp_richcompare*/
1533 0, /*tp_weaklistoffset*/
1534 0, /*tp_iter*/
1535 0, /*tp_iternext*/
1536 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001537};
1538
1539#ifdef HAVE_OPENSSL_RAND
1540
1541/* helper routines for seeding the SSL PRNG */
1542static PyObject *
1543PySSL_RAND_add(PyObject *self, PyObject *args)
1544{
1545 char *buf;
1546 int len;
1547 double entropy;
1548
1549 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
1550 return NULL;
1551 RAND_add(buf, len, entropy);
1552 Py_INCREF(Py_None);
1553 return Py_None;
1554}
1555
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001556PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001557"RAND_add(string, entropy)\n\
1558\n\
1559Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001560bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001561
1562static PyObject *
1563PySSL_RAND_status(PyObject *self)
1564{
Christian Heimes217cfd12007-12-02 14:31:20 +00001565 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001566}
1567
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001568PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001569"RAND_status() -> 0 or 1\n\
1570\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001571Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1572It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1573using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001574
1575static PyObject *
1576PySSL_RAND_egd(PyObject *self, PyObject *arg)
1577{
1578 int bytes;
1579
Bill Janssen6e027db2007-11-15 22:23:56 +00001580 if (!PyUnicode_Check(arg))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001581 return PyErr_Format(PyExc_TypeError,
1582 "RAND_egd() expected string, found %s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001583 Py_TYPE(arg)->tp_name);
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001584 bytes = RAND_egd(_PyUnicode_AsString(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001585 if (bytes == -1) {
1586 PyErr_SetString(PySSLErrorObject,
1587 "EGD connection failed or EGD did not return "
1588 "enough data to seed the PRNG");
1589 return NULL;
1590 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001591 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001592}
1593
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001594PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001595"RAND_egd(path) -> bytes\n\
1596\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001597Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1598Returns number of bytes read. Raises SSLError if connection to EGD\n\
1599fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001600
1601#endif
1602
Bill Janssen40a0f662008-08-12 16:56:25 +00001603
1604
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001605/* List of functions exported by this module. */
1606
1607static PyMethodDef PySSL_methods[] = {
Thomas Woutersed03b412007-08-28 21:37:11 +00001608 {"sslwrap", PySSL_sslwrap,
1609 METH_VARARGS, ssl_doc},
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001610 {"_test_decode_cert", PySSL_test_decode_certificate,
1611 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001612#ifdef HAVE_OPENSSL_RAND
Thomas Woutersed03b412007-08-28 21:37:11 +00001613 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001614 PySSL_RAND_add_doc},
1615 {"RAND_egd", PySSL_RAND_egd, METH_O,
1616 PySSL_RAND_egd_doc},
1617 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1618 PySSL_RAND_status_doc},
1619#endif
Thomas Woutersed03b412007-08-28 21:37:11 +00001620 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001621};
1622
1623
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001624#ifdef WITH_THREAD
1625
1626/* an implementation of OpenSSL threading operations in terms
1627 of the Python C thread library */
1628
1629static PyThread_type_lock *_ssl_locks = NULL;
1630
1631static unsigned long _ssl_thread_id_function (void) {
1632 return PyThread_get_thread_ident();
1633}
1634
Bill Janssen6e027db2007-11-15 22:23:56 +00001635static void _ssl_thread_locking_function
1636 (int mode, int n, const char *file, int line) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001637 /* this function is needed to perform locking on shared data
1638 structures. (Note that OpenSSL uses a number of global data
Bill Janssen6e027db2007-11-15 22:23:56 +00001639 structures that will be implicitly shared whenever multiple
1640 threads use OpenSSL.) Multi-threaded applications will
1641 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001642
Bill Janssen6e027db2007-11-15 22:23:56 +00001643 locking_function() must be able to handle up to
1644 CRYPTO_num_locks() different mutex locks. It sets the n-th
1645 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001646
1647 file and line are the file number of the function setting the
1648 lock. They can be useful for debugging.
1649 */
1650
1651 if ((_ssl_locks == NULL) ||
Christian Heimesba4af492008-03-28 00:55:15 +00001652 (n < 0) || ((unsigned)n >= _ssl_locks_count))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001653 return;
1654
1655 if (mode & CRYPTO_LOCK) {
1656 PyThread_acquire_lock(_ssl_locks[n], 1);
1657 } else {
1658 PyThread_release_lock(_ssl_locks[n]);
1659 }
1660}
1661
1662static int _setup_ssl_threads(void) {
1663
Christian Heimesba4af492008-03-28 00:55:15 +00001664 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001665
1666 if (_ssl_locks == NULL) {
1667 _ssl_locks_count = CRYPTO_num_locks();
1668 _ssl_locks = (PyThread_type_lock *)
1669 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1670 if (_ssl_locks == NULL)
1671 return 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001672 memset(_ssl_locks, 0,
1673 sizeof(PyThread_type_lock) * _ssl_locks_count);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001674 for (i = 0; i < _ssl_locks_count; i++) {
1675 _ssl_locks[i] = PyThread_allocate_lock();
1676 if (_ssl_locks[i] == NULL) {
Raymond Hettinger26dd7602009-01-26 16:53:29 +00001677 unsigned int j;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001678 for (j = 0; j < i; j++) {
1679 PyThread_free_lock(_ssl_locks[j]);
1680 }
1681 free(_ssl_locks);
1682 return 0;
1683 }
1684 }
1685 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1686 CRYPTO_set_id_callback(_ssl_thread_id_function);
1687 }
1688 return 1;
1689}
1690
1691#endif /* def HAVE_THREAD */
1692
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001693PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001694"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001695for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001696
Martin v. Löwis1a214512008-06-11 05:26:20 +00001697
1698static struct PyModuleDef _sslmodule = {
1699 PyModuleDef_HEAD_INIT,
1700 "_ssl",
1701 module_doc,
1702 -1,
1703 PySSL_methods,
1704 NULL,
1705 NULL,
1706 NULL,
1707 NULL
1708};
1709
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001710PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001711PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001712{
Antoine Pitrou04f6a322010-04-05 21:40:07 +00001713 PyObject *m, *d, *r;
1714 unsigned long libver;
1715 unsigned int major, minor, fix, patch, status;
Benjamin Petersonb173f782009-05-05 22:31:58 +00001716 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001717
Amaury Forgeot d'Arce43d33a2008-07-02 20:50:16 +00001718 if (PyType_Ready(&PySSL_Type) < 0)
1719 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001720
Martin v. Löwis1a214512008-06-11 05:26:20 +00001721 m = PyModule_Create(&_sslmodule);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001722 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001723 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001724 d = PyModule_GetDict(m);
1725
1726 /* Load _socket module and its C API */
Benjamin Petersonb173f782009-05-05 22:31:58 +00001727 socket_api = PySocketModule_ImportModuleAndAPI();
1728 if (!socket_api)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001729 return NULL;
Benjamin Petersonb173f782009-05-05 22:31:58 +00001730 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001731
1732 /* Init OpenSSL */
1733 SSL_load_error_strings();
Antoine Pitroufec12ff2010-04-21 19:46:23 +00001734 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001735#ifdef WITH_THREAD
1736 /* note that this will start threading if not already started */
1737 if (!_setup_ssl_threads()) {
Martin v. Löwis1a214512008-06-11 05:26:20 +00001738 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001739 }
1740#endif
Antoine Pitroufec12ff2010-04-21 19:46:23 +00001741 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001742
1743 /* Add symbols to module dict */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001744 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
Thomas Woutersed03b412007-08-28 21:37:11 +00001745 PySocketModule.error,
1746 NULL);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001747 if (PySSLErrorObject == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001748 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001749 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001750 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001751 if (PyDict_SetItemString(d, "SSLType",
1752 (PyObject *)&PySSL_Type) != 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001753 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001754 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001755 PY_SSL_ERROR_ZERO_RETURN);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001756 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001757 PY_SSL_ERROR_WANT_READ);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001758 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001759 PY_SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001760 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001761 PY_SSL_ERROR_WANT_X509_LOOKUP);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001762 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001763 PY_SSL_ERROR_SYSCALL);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001764 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001765 PY_SSL_ERROR_SSL);
1766 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1767 PY_SSL_ERROR_WANT_CONNECT);
1768 /* non ssl.h errorcodes */
1769 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1770 PY_SSL_ERROR_EOF);
1771 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1772 PY_SSL_ERROR_INVALID_ERROR_CODE);
Thomas Woutersed03b412007-08-28 21:37:11 +00001773 /* cert requirements */
1774 PyModule_AddIntConstant(m, "CERT_NONE",
1775 PY_SSL_CERT_NONE);
1776 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1777 PY_SSL_CERT_OPTIONAL);
1778 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1779 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001780
Thomas Woutersed03b412007-08-28 21:37:11 +00001781 /* protocol versions */
1782 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1783 PY_SSL_VERSION_SSL2);
1784 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1785 PY_SSL_VERSION_SSL3);
1786 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1787 PY_SSL_VERSION_SSL23);
1788 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1789 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00001790
1791 /* OpenSSL version */
1792 /* SSLeay() gives us the version of the library linked against,
1793 which could be different from the headers version.
1794 */
1795 libver = SSLeay();
1796 r = PyLong_FromUnsignedLong(libver);
1797 if (r == NULL)
1798 return NULL;
1799 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
1800 return NULL;
1801 status = libver & 0xF;
1802 libver >>= 4;
1803 patch = libver & 0xFF;
1804 libver >>= 8;
1805 fix = libver & 0xFF;
1806 libver >>= 8;
1807 minor = libver & 0xFF;
1808 libver >>= 8;
1809 major = libver & 0xFF;
1810 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
1811 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
1812 return NULL;
1813 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
1814 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
1815 return NULL;
1816
Martin v. Löwis1a214512008-06-11 05:26:20 +00001817 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001818}