Adding basic imputil documentation.
[python.git] / Modules / _ssl.c
bloba1c2380c834a4bdb99eebfc37570f874cb7a966b
1 /* SSL socket module
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
5 This module is imported by socket.py. It should *not* be used
6 directly.
8 */
10 #include "Python.h"
12 enum py_ssl_error {
13 /* these mirror ssl.h */
14 PY_SSL_ERROR_NONE,
15 PY_SSL_ERROR_SSL,
16 PY_SSL_ERROR_WANT_READ,
17 PY_SSL_ERROR_WANT_WRITE,
18 PY_SSL_ERROR_WANT_X509_LOOKUP,
19 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
20 PY_SSL_ERROR_ZERO_RETURN,
21 PY_SSL_ERROR_WANT_CONNECT,
22 /* start of non ssl.h errorcodes */
23 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
24 PY_SSL_ERROR_INVALID_ERROR_CODE
27 enum py_ssl_server_or_client {
28 PY_SSL_CLIENT,
29 PY_SSL_SERVER
32 enum py_ssl_cert_requirements {
33 PY_SSL_CERT_NONE,
34 PY_SSL_CERT_OPTIONAL,
35 PY_SSL_CERT_REQUIRED
38 enum py_ssl_version {
39 PY_SSL_VERSION_SSL2,
40 PY_SSL_VERSION_SSL3,
41 PY_SSL_VERSION_SSL23,
42 PY_SSL_VERSION_TLS1,
45 /* Include symbols from _socket module */
46 #include "socketmodule.h"
48 #if defined(HAVE_POLL_H)
49 #include <poll.h>
50 #elif defined(HAVE_SYS_POLL_H)
51 #include <sys/poll.h>
52 #endif
54 /* Include OpenSSL header files */
55 #include "openssl/rsa.h"
56 #include "openssl/crypto.h"
57 #include "openssl/x509.h"
58 #include "openssl/pem.h"
59 #include "openssl/ssl.h"
60 #include "openssl/err.h"
61 #include "openssl/rand.h"
63 /* SSL error object */
64 static PyObject *PySSLErrorObject;
66 /* SSL socket object */
68 #define X509_NAME_MAXLEN 256
70 /* RAND_* APIs got added to OpenSSL in 0.9.5 */
71 #if OPENSSL_VERSION_NUMBER >= 0x0090500fL
72 # define HAVE_OPENSSL_RAND 1
73 #else
74 # undef HAVE_OPENSSL_RAND
75 #endif
77 typedef struct {
78 PyObject_HEAD
79 PySocketSockObject *Socket; /* Socket on which we're layered */
80 SSL_CTX* ctx;
81 SSL* ssl;
82 X509* peer_cert;
83 char server[X509_NAME_MAXLEN];
84 char issuer[X509_NAME_MAXLEN];
86 } PySSLObject;
88 static PyTypeObject PySSL_Type;
89 static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args);
90 static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args);
91 static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
92 int writing);
93 static PyObject *PySSL_peercert(PySSLObject *self);
96 #define PySSLObject_Check(v) (Py_Type(v) == &PySSL_Type)
98 typedef enum {
99 SOCKET_IS_NONBLOCKING,
100 SOCKET_IS_BLOCKING,
101 SOCKET_HAS_TIMED_OUT,
102 SOCKET_HAS_BEEN_CLOSED,
103 SOCKET_TOO_LARGE_FOR_SELECT,
104 SOCKET_OPERATION_OK
105 } timeout_state;
107 /* Wrap error strings with filename and line # */
108 #define STRINGIFY1(x) #x
109 #define STRINGIFY2(x) STRINGIFY1(x)
110 #define ERRSTR1(x,y,z) (x ":" y ": " z)
111 #define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
113 /* XXX It might be helpful to augment the error message generated
114 below with the name of the SSL function that generated the error.
115 I expect it's obvious most of the time.
118 static PyObject *
119 PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno)
121 PyObject *v;
122 char buf[2048];
123 char *errstr;
124 int err;
125 enum py_ssl_error p = PY_SSL_ERROR_NONE;
127 assert(ret <= 0);
129 if ((obj != NULL) && (obj->ssl != NULL)) {
130 err = SSL_get_error(obj->ssl, ret);
132 switch (err) {
133 case SSL_ERROR_ZERO_RETURN:
134 errstr = "TLS/SSL connection has been closed";
135 p = PY_SSL_ERROR_ZERO_RETURN;
136 break;
137 case SSL_ERROR_WANT_READ:
138 errstr = "The operation did not complete (read)";
139 p = PY_SSL_ERROR_WANT_READ;
140 break;
141 case SSL_ERROR_WANT_WRITE:
142 p = PY_SSL_ERROR_WANT_WRITE;
143 errstr = "The operation did not complete (write)";
144 break;
145 case SSL_ERROR_WANT_X509_LOOKUP:
146 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
147 errstr =
148 "The operation did not complete (X509 lookup)";
149 break;
150 case SSL_ERROR_WANT_CONNECT:
151 p = PY_SSL_ERROR_WANT_CONNECT;
152 errstr = "The operation did not complete (connect)";
153 break;
154 case SSL_ERROR_SYSCALL:
156 unsigned long e = ERR_get_error();
157 if (e == 0) {
158 if (ret == 0 || !obj->Socket) {
159 p = PY_SSL_ERROR_EOF;
160 errstr =
161 "EOF occurred in violation of protocol";
162 } else if (ret == -1) {
163 /* underlying BIO reported an I/O error */
164 return obj->Socket->errorhandler();
165 } else { /* possible? */
166 p = PY_SSL_ERROR_SYSCALL;
167 errstr = "Some I/O error occurred";
169 } else {
170 p = PY_SSL_ERROR_SYSCALL;
171 /* XXX Protected by global interpreter lock */
172 errstr = ERR_error_string(e, NULL);
174 break;
176 case SSL_ERROR_SSL:
178 unsigned long e = ERR_get_error();
179 p = PY_SSL_ERROR_SSL;
180 if (e != 0)
181 /* XXX Protected by global interpreter lock */
182 errstr = ERR_error_string(e, NULL);
183 else { /* possible? */
184 errstr =
185 "A failure in the SSL library occurred";
187 break;
189 default:
190 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
191 errstr = "Invalid error code";
193 } else {
194 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
196 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
197 v = Py_BuildValue("(is)", p, buf);
198 if (v != NULL) {
199 PyErr_SetObject(PySSLErrorObject, v);
200 Py_DECREF(v);
202 return NULL;
205 static PySSLObject *
206 newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file,
207 enum py_ssl_server_or_client socket_type,
208 enum py_ssl_cert_requirements certreq,
209 enum py_ssl_version proto_version,
210 char *cacerts_file)
212 PySSLObject *self;
213 char *errstr = NULL;
214 int ret;
215 int err;
216 int sockstate;
217 int verification_mode;
219 self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */
220 if (self == NULL)
221 return NULL;
222 memset(self->server, '\0', sizeof(char) * X509_NAME_MAXLEN);
223 memset(self->issuer, '\0', sizeof(char) * X509_NAME_MAXLEN);
224 self->peer_cert = NULL;
225 self->ssl = NULL;
226 self->ctx = NULL;
227 self->Socket = NULL;
229 if ((key_file && !cert_file) || (!key_file && cert_file)) {
230 errstr = ERRSTR("Both the key & certificate files "
231 "must be specified");
232 goto fail;
235 if ((socket_type == PY_SSL_SERVER) &&
236 ((key_file == NULL) || (cert_file == NULL))) {
237 errstr = ERRSTR("Both the key & certificate files "
238 "must be specified for server-side operation");
239 goto fail;
242 Py_BEGIN_ALLOW_THREADS
243 if (proto_version == PY_SSL_VERSION_TLS1)
244 self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */
245 else if (proto_version == PY_SSL_VERSION_SSL3)
246 self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */
247 else if (proto_version == PY_SSL_VERSION_SSL2)
248 self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */
249 else
250 self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
251 Py_END_ALLOW_THREADS
253 if (self->ctx == NULL) {
254 errstr = ERRSTR("Invalid SSL protocol variant specified.");
255 goto fail;
258 if (certreq != PY_SSL_CERT_NONE) {
259 if (cacerts_file == NULL) {
260 errstr = ERRSTR("No root certificates specified for "
261 "verification of other-side certificates.");
262 goto fail;
263 } else {
264 Py_BEGIN_ALLOW_THREADS
265 ret = SSL_CTX_load_verify_locations(self->ctx,
266 cacerts_file,
267 NULL);
268 Py_END_ALLOW_THREADS
269 if (ret != 1) {
270 PySSL_SetError(NULL, 0, __FILE__, __LINE__);
271 goto fail;
275 if (key_file) {
276 Py_BEGIN_ALLOW_THREADS
277 ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
278 SSL_FILETYPE_PEM);
279 Py_END_ALLOW_THREADS
280 if (ret != 1) {
281 PySSL_SetError(NULL, 0, __FILE__, __LINE__);
282 goto fail;
285 Py_BEGIN_ALLOW_THREADS
286 ret = SSL_CTX_use_certificate_chain_file(self->ctx,
287 cert_file);
288 Py_END_ALLOW_THREADS
289 if (ret != 1) {
290 PySSL_SetError(NULL, 0, __FILE__, __LINE__);
291 goto fail;
293 /* ssl compatibility */
294 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
297 verification_mode = SSL_VERIFY_NONE;
298 if (certreq == PY_SSL_CERT_OPTIONAL)
299 verification_mode = SSL_VERIFY_PEER;
300 else if (certreq == PY_SSL_CERT_REQUIRED)
301 verification_mode = (SSL_VERIFY_PEER |
302 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
303 SSL_CTX_set_verify(self->ctx, verification_mode,
304 NULL); /* set verify lvl */
306 Py_BEGIN_ALLOW_THREADS
307 self->ssl = SSL_new(self->ctx); /* New ssl struct */
308 Py_END_ALLOW_THREADS
309 SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */
311 /* If the socket is in non-blocking mode or timeout mode, set the BIO
312 * to non-blocking mode (blocking is the default)
314 if (Sock->sock_timeout >= 0.0) {
315 /* Set both the read and write BIO's to non-blocking mode */
316 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
317 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
320 Py_BEGIN_ALLOW_THREADS
321 if (socket_type == PY_SSL_CLIENT)
322 SSL_set_connect_state(self->ssl);
323 else
324 SSL_set_accept_state(self->ssl);
325 Py_END_ALLOW_THREADS
327 /* Actually negotiate SSL connection */
328 /* XXX If SSL_connect() returns 0, it's also a failure. */
329 sockstate = 0;
330 do {
331 Py_BEGIN_ALLOW_THREADS
332 if (socket_type == PY_SSL_CLIENT)
333 ret = SSL_connect(self->ssl);
334 else
335 ret = SSL_accept(self->ssl);
336 err = SSL_get_error(self->ssl, ret);
337 Py_END_ALLOW_THREADS
338 if(PyErr_CheckSignals()) {
339 goto fail;
341 if (err == SSL_ERROR_WANT_READ) {
342 sockstate = check_socket_and_wait_for_timeout(Sock, 0);
343 } else if (err == SSL_ERROR_WANT_WRITE) {
344 sockstate = check_socket_and_wait_for_timeout(Sock, 1);
345 } else {
346 sockstate = SOCKET_OPERATION_OK;
348 if (sockstate == SOCKET_HAS_TIMED_OUT) {
349 PyErr_SetString(PySSLErrorObject,
350 ERRSTR("The connect operation timed out"));
351 goto fail;
352 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
353 PyErr_SetString(PySSLErrorObject,
354 ERRSTR("Underlying socket has been closed."));
355 goto fail;
356 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
357 PyErr_SetString(PySSLErrorObject,
358 ERRSTR("Underlying socket too large for select()."));
359 goto fail;
360 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
361 break;
363 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
364 if (ret < 1) {
365 PySSL_SetError(self, ret, __FILE__, __LINE__);
366 goto fail;
368 self->ssl->debug = 1;
370 Py_BEGIN_ALLOW_THREADS
371 if ((self->peer_cert = SSL_get_peer_certificate(self->ssl))) {
372 X509_NAME_oneline(X509_get_subject_name(self->peer_cert),
373 self->server, X509_NAME_MAXLEN);
374 X509_NAME_oneline(X509_get_issuer_name(self->peer_cert),
375 self->issuer, X509_NAME_MAXLEN);
377 Py_END_ALLOW_THREADS
378 self->Socket = Sock;
379 Py_INCREF(self->Socket);
380 return self;
381 fail:
382 if (errstr)
383 PyErr_SetString(PySSLErrorObject, errstr);
384 Py_DECREF(self);
385 return NULL;
388 static PyObject *
389 PySSL_sslwrap(PyObject *self, PyObject *args)
391 PySocketSockObject *Sock;
392 int server_side = 0;
393 int verification_mode = PY_SSL_CERT_NONE;
394 int protocol = PY_SSL_VERSION_SSL23;
395 char *key_file = NULL;
396 char *cert_file = NULL;
397 char *cacerts_file = NULL;
399 if (!PyArg_ParseTuple(args, "O!i|zziiz:sslwrap",
400 PySocketModule.Sock_Type,
401 &Sock,
402 &server_side,
403 &key_file, &cert_file,
404 &verification_mode, &protocol,
405 &cacerts_file))
406 return NULL;
409 fprintf(stderr,
410 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
411 "protocol %d, certs %p\n",
412 server_side, key_file, cert_file, verification_mode,
413 protocol, cacerts_file);
416 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
417 server_side, verification_mode,
418 protocol, cacerts_file);
421 PyDoc_STRVAR(ssl_doc,
422 "sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
423 " cacertsfile]) -> sslobject");
425 /* SSL object methods */
427 static PyObject *
428 PySSL_server(PySSLObject *self)
430 return PyString_FromString(self->server);
433 static PyObject *
434 PySSL_issuer(PySSLObject *self)
436 return PyString_FromString(self->issuer);
439 static PyObject *
440 _create_dict_for_X509_NAME (X509_NAME *xname)
442 PyObject *pd = PyDict_New();
443 int index_counter;
445 if (pd == NULL)
446 return NULL;
448 for (index_counter = 0;
449 index_counter < X509_NAME_entry_count(xname);
450 index_counter++)
452 char namebuf[X509_NAME_MAXLEN];
453 int buflen;
454 PyObject *name_obj;
455 ASN1_STRING *value;
456 PyObject *value_obj;
457 unsigned char *valuebuf = NULL;
459 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname,
460 index_counter);
462 ASN1_OBJECT *name = X509_NAME_ENTRY_get_object(entry);
463 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
464 if (buflen < 0)
465 goto fail0;
466 name_obj = PyString_FromStringAndSize(namebuf, buflen);
467 if (name_obj == NULL)
468 goto fail0;
470 value = X509_NAME_ENTRY_get_data(entry);
471 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
472 if (buflen < 0) {
473 Py_DECREF(name_obj);
474 goto fail0;
476 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
477 buflen, "strict");
478 OPENSSL_free(valuebuf);
479 if (value_obj == NULL) {
480 Py_DECREF(name_obj);
481 goto fail0;
483 if (PyDict_SetItem(pd, name_obj, value_obj) < 0) {
484 Py_DECREF(name_obj);
485 Py_DECREF(value_obj);
486 goto fail0;
488 Py_DECREF(name_obj);
489 Py_DECREF(value_obj);
491 return pd;
493 fail0:
494 Py_XDECREF(pd);
495 return NULL;
498 static PyObject *
499 PySSL_peercert(PySSLObject *self)
501 PyObject *retval = NULL;
502 BIO *biobuf = NULL;
503 PyObject *peer;
504 PyObject *issuer;
505 PyObject *version;
506 char buf[2048];
507 int len;
508 ASN1_TIME *notBefore, *notAfter;
509 PyObject *pnotBefore, *pnotAfter;
510 int verification;
512 if (!self->peer_cert)
513 Py_RETURN_NONE;
515 retval = PyDict_New();
516 if (retval == NULL)
517 return NULL;
519 verification = SSL_CTX_get_verify_mode(self->ctx);
520 if ((verification & SSL_VERIFY_PEER) == 0)
521 return retval;
523 peer = _create_dict_for_X509_NAME(
524 X509_get_subject_name(self->peer_cert));
525 if (peer == NULL)
526 goto fail0;
527 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
528 Py_DECREF(peer);
529 goto fail0;
531 Py_DECREF(peer);
533 issuer = _create_dict_for_X509_NAME(
534 X509_get_issuer_name(self->peer_cert));
535 if (issuer == NULL)
536 goto fail0;
537 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
538 Py_DECREF(issuer);
539 goto fail0;
541 Py_DECREF(issuer);
543 version = PyInt_FromLong(X509_get_version(self->peer_cert));
544 if (PyDict_SetItemString(retval, "version", version) < 0) {
545 Py_DECREF(version);
546 goto fail0;
548 Py_DECREF(version);
550 /* get a memory buffer */
551 biobuf = BIO_new(BIO_s_mem());
553 notBefore = X509_get_notBefore(self->peer_cert);
554 ASN1_TIME_print(biobuf, notBefore);
555 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
556 pnotBefore = PyString_FromStringAndSize(buf, len);
557 if (pnotBefore == NULL)
558 goto fail1;
559 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
560 Py_DECREF(pnotBefore);
561 goto fail1;
563 Py_DECREF(pnotBefore);
565 (void) BIO_reset(biobuf);
566 notAfter = X509_get_notAfter(self->peer_cert);
567 ASN1_TIME_print(biobuf, notAfter);
568 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
569 BIO_free(biobuf);
570 pnotAfter = PyString_FromStringAndSize(buf, len);
571 if (pnotAfter == NULL)
572 goto fail0;
573 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
574 Py_DECREF(pnotAfter);
575 goto fail0;
577 Py_DECREF(pnotAfter);
578 return retval;
580 fail1:
581 if (biobuf != NULL)
582 BIO_free(biobuf);
583 fail0:
584 Py_XDECREF(retval);
585 return NULL;
588 static void PySSL_dealloc(PySSLObject *self)
590 if (self->peer_cert) /* Possible not to have one? */
591 X509_free (self->peer_cert);
592 if (self->ssl)
593 SSL_free(self->ssl);
594 if (self->ctx)
595 SSL_CTX_free(self->ctx);
596 Py_XDECREF(self->Socket);
597 PyObject_Del(self);
600 /* If the socket has a timeout, do a select()/poll() on the socket.
601 The argument writing indicates the direction.
602 Returns one of the possibilities in the timeout_state enum (above).
605 static int
606 check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
608 fd_set fds;
609 struct timeval tv;
610 int rc;
612 /* Nothing to do unless we're in timeout mode (not non-blocking) */
613 if (s->sock_timeout < 0.0)
614 return SOCKET_IS_BLOCKING;
615 else if (s->sock_timeout == 0.0)
616 return SOCKET_IS_NONBLOCKING;
618 /* Guard against closed socket */
619 if (s->sock_fd < 0)
620 return SOCKET_HAS_BEEN_CLOSED;
622 /* Prefer poll, if available, since you can poll() any fd
623 * which can't be done with select(). */
624 #ifdef HAVE_POLL
626 struct pollfd pollfd;
627 int timeout;
629 pollfd.fd = s->sock_fd;
630 pollfd.events = writing ? POLLOUT : POLLIN;
632 /* s->sock_timeout is in seconds, timeout in ms */
633 timeout = (int)(s->sock_timeout * 1000 + 0.5);
634 Py_BEGIN_ALLOW_THREADS
635 rc = poll(&pollfd, 1, timeout);
636 Py_END_ALLOW_THREADS
638 goto normal_return;
640 #endif
642 /* Guard against socket too large for select*/
643 #ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
644 if (s->sock_fd >= FD_SETSIZE)
645 return SOCKET_TOO_LARGE_FOR_SELECT;
646 #endif
648 /* Construct the arguments to select */
649 tv.tv_sec = (int)s->sock_timeout;
650 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
651 FD_ZERO(&fds);
652 FD_SET(s->sock_fd, &fds);
654 /* See if the socket is ready */
655 Py_BEGIN_ALLOW_THREADS
656 if (writing)
657 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
658 else
659 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
660 Py_END_ALLOW_THREADS
662 normal_return:
663 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
664 (when we are able to write or when there's something to read) */
665 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
668 static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
670 char *data;
671 int len;
672 int count;
673 int sockstate;
674 int err;
676 if (!PyArg_ParseTuple(args, "s#:write", &data, &count))
677 return NULL;
679 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
680 if (sockstate == SOCKET_HAS_TIMED_OUT) {
681 PyErr_SetString(PySSLErrorObject,
682 "The write operation timed out");
683 return NULL;
684 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
685 PyErr_SetString(PySSLErrorObject,
686 "Underlying socket has been closed.");
687 return NULL;
688 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
689 PyErr_SetString(PySSLErrorObject,
690 "Underlying socket too large for select().");
691 return NULL;
693 do {
694 err = 0;
695 Py_BEGIN_ALLOW_THREADS
696 len = SSL_write(self->ssl, data, count);
697 err = SSL_get_error(self->ssl, len);
698 Py_END_ALLOW_THREADS
699 if(PyErr_CheckSignals()) {
700 return NULL;
702 if (err == SSL_ERROR_WANT_READ) {
703 sockstate =
704 check_socket_and_wait_for_timeout(self->Socket, 0);
705 } else if (err == SSL_ERROR_WANT_WRITE) {
706 sockstate =
707 check_socket_and_wait_for_timeout(self->Socket, 1);
708 } else {
709 sockstate = SOCKET_OPERATION_OK;
711 if (sockstate == SOCKET_HAS_TIMED_OUT) {
712 PyErr_SetString(PySSLErrorObject,
713 "The write operation timed out");
714 return NULL;
715 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
716 PyErr_SetString(PySSLErrorObject,
717 "Underlying socket has been closed.");
718 return NULL;
719 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
720 break;
722 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
723 if (len > 0)
724 return PyInt_FromLong(len);
725 else
726 return PySSL_SetError(self, len, __FILE__, __LINE__);
729 PyDoc_STRVAR(PySSL_SSLwrite_doc,
730 "write(s) -> len\n\
732 Writes the string s into the SSL object. Returns the number\n\
733 of bytes written.");
735 static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
737 PyObject *buf;
738 int count = 0;
739 int len = 1024;
740 int sockstate;
741 int err;
743 if (!PyArg_ParseTuple(args, "|i:read", &len))
744 return NULL;
746 if (!(buf = PyString_FromStringAndSize((char *) 0, len)))
747 return NULL;
749 /* first check if there are bytes ready to be read */
750 Py_BEGIN_ALLOW_THREADS
751 count = SSL_pending(self->ssl);
752 Py_END_ALLOW_THREADS
754 if (!count) {
755 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
756 if (sockstate == SOCKET_HAS_TIMED_OUT) {
757 PyErr_SetString(PySSLErrorObject,
758 "The read operation timed out");
759 Py_DECREF(buf);
760 return NULL;
761 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
762 PyErr_SetString(PySSLErrorObject,
763 "Underlying socket too large for select().");
764 Py_DECREF(buf);
765 return NULL;
766 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
767 if (SSL_get_shutdown(self->ssl) !=
768 SSL_RECEIVED_SHUTDOWN)
770 Py_DECREF(buf);
771 PyErr_SetString(PySSLErrorObject,
772 "Socket closed without SSL shutdown handshake");
773 return NULL;
774 } else {
775 /* should contain a zero-length string */
776 _PyString_Resize(&buf, 0);
777 return buf;
781 do {
782 err = 0;
783 Py_BEGIN_ALLOW_THREADS
784 count = SSL_read(self->ssl, PyString_AsString(buf), len);
785 err = SSL_get_error(self->ssl, count);
786 Py_END_ALLOW_THREADS
787 if(PyErr_CheckSignals()) {
788 Py_DECREF(buf);
789 return NULL;
791 if (err == SSL_ERROR_WANT_READ) {
792 sockstate =
793 check_socket_and_wait_for_timeout(self->Socket, 0);
794 } else if (err == SSL_ERROR_WANT_WRITE) {
795 sockstate =
796 check_socket_and_wait_for_timeout(self->Socket, 1);
797 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
798 (SSL_get_shutdown(self->ssl) ==
799 SSL_RECEIVED_SHUTDOWN))
801 _PyString_Resize(&buf, 0);
802 return buf;
803 } else {
804 sockstate = SOCKET_OPERATION_OK;
806 if (sockstate == SOCKET_HAS_TIMED_OUT) {
807 PyErr_SetString(PySSLErrorObject,
808 "The read operation timed out");
809 Py_DECREF(buf);
810 return NULL;
811 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
812 break;
814 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
815 if (count <= 0) {
816 Py_DECREF(buf);
817 return PySSL_SetError(self, count, __FILE__, __LINE__);
819 if (count != len)
820 _PyString_Resize(&buf, count);
821 return buf;
824 PyDoc_STRVAR(PySSL_SSLread_doc,
825 "read([len]) -> string\n\
827 Read up to len bytes from the SSL socket.");
829 static PyObject *PySSL_SSLshutdown(PySSLObject *self, PyObject *args)
831 int err;
833 /* Guard against closed socket */
834 if (self->Socket->sock_fd < 0) {
835 PyErr_SetString(PySSLErrorObject,
836 "Underlying socket has been closed.");
837 return NULL;
840 Py_BEGIN_ALLOW_THREADS
841 err = SSL_shutdown(self->ssl);
842 if (err == 0) {
843 /* we need to call it again to finish the shutdown */
844 err = SSL_shutdown(self->ssl);
846 Py_END_ALLOW_THREADS
848 if (err < 0)
849 return PySSL_SetError(self, err, __FILE__, __LINE__);
850 else {
851 Py_INCREF(self->Socket);
852 return (PyObject *) (self->Socket);
856 PyDoc_STRVAR(PySSL_SSLshutdown_doc,
857 "shutdown(s) -> socket\n\
859 Does the SSL shutdown handshake with the remote end, and returns\n\
860 the underlying socket object.");
862 static PyMethodDef PySSLMethods[] = {
863 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
864 PySSL_SSLwrite_doc},
865 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
866 PySSL_SSLread_doc},
867 {"server", (PyCFunction)PySSL_server, METH_NOARGS},
868 {"issuer", (PyCFunction)PySSL_issuer, METH_NOARGS},
869 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_NOARGS},
870 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
871 PySSL_SSLshutdown_doc},
872 {NULL, NULL}
875 static PyObject *PySSL_getattr(PySSLObject *self, char *name)
877 return Py_FindMethod(PySSLMethods, (PyObject *)self, name);
880 static PyTypeObject PySSL_Type = {
881 PyVarObject_HEAD_INIT(NULL, 0)
882 "ssl.SSLContext", /*tp_name*/
883 sizeof(PySSLObject), /*tp_basicsize*/
884 0, /*tp_itemsize*/
885 /* methods */
886 (destructor)PySSL_dealloc, /*tp_dealloc*/
887 0, /*tp_print*/
888 (getattrfunc)PySSL_getattr, /*tp_getattr*/
889 0, /*tp_setattr*/
890 0, /*tp_compare*/
891 0, /*tp_repr*/
892 0, /*tp_as_number*/
893 0, /*tp_as_sequence*/
894 0, /*tp_as_mapping*/
895 0, /*tp_hash*/
898 #ifdef HAVE_OPENSSL_RAND
900 /* helper routines for seeding the SSL PRNG */
901 static PyObject *
902 PySSL_RAND_add(PyObject *self, PyObject *args)
904 char *buf;
905 int len;
906 double entropy;
908 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
909 return NULL;
910 RAND_add(buf, len, entropy);
911 Py_INCREF(Py_None);
912 return Py_None;
915 PyDoc_STRVAR(PySSL_RAND_add_doc,
916 "RAND_add(string, entropy)\n\
918 Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
919 bound on the entropy contained in string.");
921 static PyObject *
922 PySSL_RAND_status(PyObject *self)
924 return PyInt_FromLong(RAND_status());
927 PyDoc_STRVAR(PySSL_RAND_status_doc,
928 "RAND_status() -> 0 or 1\n\
930 Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
931 It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
932 using the ssl() function.");
934 static PyObject *
935 PySSL_RAND_egd(PyObject *self, PyObject *arg)
937 int bytes;
939 if (!PyString_Check(arg))
940 return PyErr_Format(PyExc_TypeError,
941 "RAND_egd() expected string, found %s",
942 Py_Type(arg)->tp_name);
943 bytes = RAND_egd(PyString_AS_STRING(arg));
944 if (bytes == -1) {
945 PyErr_SetString(PySSLErrorObject,
946 "EGD connection failed or EGD did not return "
947 "enough data to seed the PRNG");
948 return NULL;
950 return PyInt_FromLong(bytes);
953 PyDoc_STRVAR(PySSL_RAND_egd_doc,
954 "RAND_egd(path) -> bytes\n\
956 Queries the entropy gather daemon (EGD) on socket path. Returns number\n\
957 of bytes read. Raises ssl.sslerror if connection to EGD fails or\n\
958 if it does provide enough data to seed PRNG.");
960 #endif
962 /* List of functions exported by this module. */
964 static PyMethodDef PySSL_methods[] = {
965 {"sslwrap", PySSL_sslwrap,
966 METH_VARARGS, ssl_doc},
967 #ifdef HAVE_OPENSSL_RAND
968 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
969 PySSL_RAND_add_doc},
970 {"RAND_egd", PySSL_RAND_egd, METH_O,
971 PySSL_RAND_egd_doc},
972 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
973 PySSL_RAND_status_doc},
974 #endif
975 {NULL, NULL} /* Sentinel */
979 PyDoc_STRVAR(module_doc,
980 "Implementation module for SSL socket operations. See the socket module\n\
981 for documentation.");
983 PyMODINIT_FUNC
984 init_ssl(void)
986 PyObject *m, *d;
988 Py_Type(&PySSL_Type) = &PyType_Type;
990 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
991 if (m == NULL)
992 return;
993 d = PyModule_GetDict(m);
995 /* Load _socket module and its C API */
996 if (PySocketModule_ImportModuleAndAPI())
997 return;
999 /* Init OpenSSL */
1000 SSL_load_error_strings();
1001 SSLeay_add_ssl_algorithms();
1003 /* Add symbols to module dict */
1004 PySSLErrorObject = PyErr_NewException("ssl.sslerror",
1005 PySocketModule.error,
1006 NULL);
1007 if (PySSLErrorObject == NULL)
1008 return;
1009 if (PyDict_SetItemString(d, "sslerror", PySSLErrorObject) != 0)
1010 return;
1011 if (PyDict_SetItemString(d, "SSLType",
1012 (PyObject *)&PySSL_Type) != 0)
1013 return;
1014 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
1015 PY_SSL_ERROR_ZERO_RETURN);
1016 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
1017 PY_SSL_ERROR_WANT_READ);
1018 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
1019 PY_SSL_ERROR_WANT_WRITE);
1020 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
1021 PY_SSL_ERROR_WANT_X509_LOOKUP);
1022 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
1023 PY_SSL_ERROR_SYSCALL);
1024 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
1025 PY_SSL_ERROR_SSL);
1026 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1027 PY_SSL_ERROR_WANT_CONNECT);
1028 /* non ssl.h errorcodes */
1029 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1030 PY_SSL_ERROR_EOF);
1031 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1032 PY_SSL_ERROR_INVALID_ERROR_CODE);
1033 /* cert requirements */
1034 PyModule_AddIntConstant(m, "CERT_NONE",
1035 PY_SSL_CERT_NONE);
1036 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1037 PY_SSL_CERT_OPTIONAL);
1038 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1039 PY_SSL_CERT_REQUIRED);
1041 /* protocol versions */
1042 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1043 PY_SSL_VERSION_SSL2);
1044 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1045 PY_SSL_VERSION_SSL3);
1046 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1047 PY_SSL_VERSION_SSL23);
1048 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1049 PY_SSL_VERSION_TLS1);