move sections
[python/dscho.git] / Modules / _ssl.c
blobe44fa074fabcc1e36c116d9e9b17130536aa1bb9
1 /* SSL socket module
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
4 Re-worked a bit by Bill Janssen to add server-side support and
5 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
8 This module is imported by ssl.py. It should *not* be used
9 directly.
11 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
17 #include "Python.h"
19 #ifdef WITH_THREAD
20 #include "pythread.h"
21 #define PySSL_BEGIN_ALLOW_THREADS { \
22 PyThreadState *_save = NULL; \
23 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);} \
29 #else /* no WITH_THREAD */
31 #define PySSL_BEGIN_ALLOW_THREADS
32 #define PySSL_BLOCK_THREADS
33 #define PySSL_UNBLOCK_THREADS
34 #define PySSL_END_ALLOW_THREADS
36 #endif
38 enum py_ssl_error {
39 /* these mirror ssl.h */
40 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,
45 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
46 PY_SSL_ERROR_ZERO_RETURN,
47 PY_SSL_ERROR_WANT_CONNECT,
48 /* start of non ssl.h errorcodes */
49 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
50 PY_SSL_ERROR_INVALID_ERROR_CODE
53 enum py_ssl_server_or_client {
54 PY_SSL_CLIENT,
55 PY_SSL_SERVER
58 enum py_ssl_cert_requirements {
59 PY_SSL_CERT_NONE,
60 PY_SSL_CERT_OPTIONAL,
61 PY_SSL_CERT_REQUIRED
64 enum py_ssl_version {
65 PY_SSL_VERSION_SSL2,
66 PY_SSL_VERSION_SSL3,
67 PY_SSL_VERSION_SSL23,
68 PY_SSL_VERSION_TLS1
71 /* Include symbols from _socket module */
72 #include "socketmodule.h"
74 #if defined(HAVE_POLL_H)
75 #include <poll.h>
76 #elif defined(HAVE_SYS_POLL_H)
77 #include <sys/poll.h>
78 #endif
80 /* Include OpenSSL header files */
81 #include "openssl/rsa.h"
82 #include "openssl/crypto.h"
83 #include "openssl/x509.h"
84 #include "openssl/x509v3.h"
85 #include "openssl/pem.h"
86 #include "openssl/ssl.h"
87 #include "openssl/err.h"
88 #include "openssl/rand.h"
90 /* SSL error object */
91 static PyObject *PySSLErrorObject;
93 #ifdef WITH_THREAD
95 /* serves as a flag to see whether we've initialized the SSL thread support. */
96 /* 0 means no, greater than 0 means yes */
98 static unsigned int _ssl_locks_count = 0;
100 #endif /* def WITH_THREAD */
102 /* SSL socket object */
104 #define X509_NAME_MAXLEN 256
106 /* RAND_* APIs got added to OpenSSL in 0.9.5 */
107 #if OPENSSL_VERSION_NUMBER >= 0x0090500fL
108 # define HAVE_OPENSSL_RAND 1
109 #else
110 # undef HAVE_OPENSSL_RAND
111 #endif
113 typedef struct {
114 PyObject_HEAD
115 PySocketSockObject *Socket; /* Socket on which we're layered */
116 SSL_CTX* ctx;
117 SSL* ssl;
118 X509* peer_cert;
119 char server[X509_NAME_MAXLEN];
120 char issuer[X509_NAME_MAXLEN];
121 int shutdown_seen_zero;
123 } PySSLObject;
125 static PyTypeObject PySSL_Type;
126 static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args);
127 static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args);
128 static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
129 int writing);
130 static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args);
131 static PyObject *PySSL_cipher(PySSLObject *self);
133 #define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type)
135 typedef enum {
136 SOCKET_IS_NONBLOCKING,
137 SOCKET_IS_BLOCKING,
138 SOCKET_HAS_TIMED_OUT,
139 SOCKET_HAS_BEEN_CLOSED,
140 SOCKET_TOO_LARGE_FOR_SELECT,
141 SOCKET_OPERATION_OK
142 } timeout_state;
144 /* Wrap error strings with filename and line # */
145 #define STRINGIFY1(x) #x
146 #define STRINGIFY2(x) STRINGIFY1(x)
147 #define ERRSTR1(x,y,z) (x ":" y ": " z)
148 #define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
150 /* XXX It might be helpful to augment the error message generated
151 below with the name of the SSL function that generated the error.
152 I expect it's obvious most of the time.
155 static PyObject *
156 PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno)
158 PyObject *v;
159 char buf[2048];
160 char *errstr;
161 int err;
162 enum py_ssl_error p = PY_SSL_ERROR_NONE;
164 assert(ret <= 0);
166 if (obj->ssl != NULL) {
167 err = SSL_get_error(obj->ssl, ret);
169 switch (err) {
170 case SSL_ERROR_ZERO_RETURN:
171 errstr = "TLS/SSL connection has been closed";
172 p = PY_SSL_ERROR_ZERO_RETURN;
173 break;
174 case SSL_ERROR_WANT_READ:
175 errstr = "The operation did not complete (read)";
176 p = PY_SSL_ERROR_WANT_READ;
177 break;
178 case SSL_ERROR_WANT_WRITE:
179 p = PY_SSL_ERROR_WANT_WRITE;
180 errstr = "The operation did not complete (write)";
181 break;
182 case SSL_ERROR_WANT_X509_LOOKUP:
183 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
184 errstr = "The operation did not complete (X509 lookup)";
185 break;
186 case SSL_ERROR_WANT_CONNECT:
187 p = PY_SSL_ERROR_WANT_CONNECT;
188 errstr = "The operation did not complete (connect)";
189 break;
190 case SSL_ERROR_SYSCALL:
192 unsigned long e = ERR_get_error();
193 if (e == 0) {
194 if (ret == 0 || !obj->Socket) {
195 p = PY_SSL_ERROR_EOF;
196 errstr = "EOF occurred in violation of protocol";
197 } else if (ret == -1) {
198 /* underlying BIO reported an I/O error */
199 ERR_clear_error();
200 return obj->Socket->errorhandler();
201 } else { /* possible? */
202 p = PY_SSL_ERROR_SYSCALL;
203 errstr = "Some I/O error occurred";
205 } else {
206 p = PY_SSL_ERROR_SYSCALL;
207 /* XXX Protected by global interpreter lock */
208 errstr = ERR_error_string(e, NULL);
210 break;
212 case SSL_ERROR_SSL:
214 unsigned long e = ERR_get_error();
215 p = PY_SSL_ERROR_SSL;
216 if (e != 0)
217 /* XXX Protected by global interpreter lock */
218 errstr = ERR_error_string(e, NULL);
219 else { /* possible? */
220 errstr = "A failure in the SSL library occurred";
222 break;
224 default:
225 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
226 errstr = "Invalid error code";
228 } else {
229 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
231 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
232 ERR_clear_error();
233 v = Py_BuildValue("(is)", p, buf);
234 if (v != NULL) {
235 PyErr_SetObject(PySSLErrorObject, v);
236 Py_DECREF(v);
238 return NULL;
241 static PyObject *
242 _setSSLError (char *errstr, int errcode, char *filename, int lineno) {
244 char buf[2048];
245 PyObject *v;
247 if (errstr == NULL) {
248 errcode = ERR_peek_last_error();
249 errstr = ERR_error_string(errcode, NULL);
251 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
252 ERR_clear_error();
253 v = Py_BuildValue("(is)", errcode, buf);
254 if (v != NULL) {
255 PyErr_SetObject(PySSLErrorObject, v);
256 Py_DECREF(v);
258 return NULL;
261 static PySSLObject *
262 newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file,
263 enum py_ssl_server_or_client socket_type,
264 enum py_ssl_cert_requirements certreq,
265 enum py_ssl_version proto_version,
266 char *cacerts_file, char *ciphers)
268 PySSLObject *self;
269 char *errstr = NULL;
270 int ret;
271 int verification_mode;
273 self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */
274 if (self == NULL)
275 return NULL;
276 memset(self->server, '\0', sizeof(char) * X509_NAME_MAXLEN);
277 memset(self->issuer, '\0', sizeof(char) * X509_NAME_MAXLEN);
278 self->peer_cert = NULL;
279 self->ssl = NULL;
280 self->ctx = NULL;
281 self->Socket = NULL;
283 /* Make sure the SSL error state is initialized */
284 (void) ERR_get_state();
285 ERR_clear_error();
287 if ((key_file && !cert_file) || (!key_file && cert_file)) {
288 errstr = ERRSTR("Both the key & certificate files "
289 "must be specified");
290 goto fail;
293 if ((socket_type == PY_SSL_SERVER) &&
294 ((key_file == NULL) || (cert_file == NULL))) {
295 errstr = ERRSTR("Both the key & certificate files "
296 "must be specified for server-side operation");
297 goto fail;
300 PySSL_BEGIN_ALLOW_THREADS
301 if (proto_version == PY_SSL_VERSION_TLS1)
302 self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */
303 else if (proto_version == PY_SSL_VERSION_SSL3)
304 self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */
305 else if (proto_version == PY_SSL_VERSION_SSL2)
306 self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */
307 else if (proto_version == PY_SSL_VERSION_SSL23)
308 self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
309 PySSL_END_ALLOW_THREADS
311 if (self->ctx == NULL) {
312 errstr = ERRSTR("Invalid SSL protocol variant specified.");
313 goto fail;
316 if (ciphers != NULL) {
317 ret = SSL_CTX_set_cipher_list(self->ctx, ciphers);
318 if (ret == 0) {
319 errstr = ERRSTR("No cipher can be selected.");
320 goto fail;
324 if (certreq != PY_SSL_CERT_NONE) {
325 if (cacerts_file == NULL) {
326 errstr = ERRSTR("No root certificates specified for "
327 "verification of other-side certificates.");
328 goto fail;
329 } else {
330 PySSL_BEGIN_ALLOW_THREADS
331 ret = SSL_CTX_load_verify_locations(self->ctx,
332 cacerts_file,
333 NULL);
334 PySSL_END_ALLOW_THREADS
335 if (ret != 1) {
336 _setSSLError(NULL, 0, __FILE__, __LINE__);
337 goto fail;
341 if (key_file) {
342 PySSL_BEGIN_ALLOW_THREADS
343 ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
344 SSL_FILETYPE_PEM);
345 PySSL_END_ALLOW_THREADS
346 if (ret != 1) {
347 _setSSLError(NULL, ret, __FILE__, __LINE__);
348 goto fail;
351 PySSL_BEGIN_ALLOW_THREADS
352 ret = SSL_CTX_use_certificate_chain_file(self->ctx,
353 cert_file);
354 PySSL_END_ALLOW_THREADS
355 if (ret != 1) {
357 fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
358 ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
360 if (ERR_peek_last_error() != 0) {
361 _setSSLError(NULL, ret, __FILE__, __LINE__);
362 goto fail;
367 /* ssl compatibility */
368 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
370 verification_mode = SSL_VERIFY_NONE;
371 if (certreq == PY_SSL_CERT_OPTIONAL)
372 verification_mode = SSL_VERIFY_PEER;
373 else if (certreq == PY_SSL_CERT_REQUIRED)
374 verification_mode = (SSL_VERIFY_PEER |
375 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
376 SSL_CTX_set_verify(self->ctx, verification_mode,
377 NULL); /* set verify lvl */
379 PySSL_BEGIN_ALLOW_THREADS
380 self->ssl = SSL_new(self->ctx); /* New ssl struct */
381 PySSL_END_ALLOW_THREADS
382 SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */
383 #ifdef SSL_MODE_AUTO_RETRY
384 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
385 #endif
387 /* If the socket is in non-blocking mode or timeout mode, set the BIO
388 * to non-blocking mode (blocking is the default)
390 if (Sock->sock_timeout >= 0.0) {
391 /* Set both the read and write BIO's to non-blocking mode */
392 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
393 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
396 PySSL_BEGIN_ALLOW_THREADS
397 if (socket_type == PY_SSL_CLIENT)
398 SSL_set_connect_state(self->ssl);
399 else
400 SSL_set_accept_state(self->ssl);
401 PySSL_END_ALLOW_THREADS
403 self->Socket = Sock;
404 Py_INCREF(self->Socket);
405 return self;
406 fail:
407 if (errstr)
408 PyErr_SetString(PySSLErrorObject, errstr);
409 Py_DECREF(self);
410 return NULL;
413 static PyObject *
414 PySSL_sslwrap(PyObject *self, PyObject *args)
416 PySocketSockObject *Sock;
417 int server_side = 0;
418 int verification_mode = PY_SSL_CERT_NONE;
419 int protocol = PY_SSL_VERSION_SSL23;
420 char *key_file = NULL;
421 char *cert_file = NULL;
422 char *cacerts_file = NULL;
423 char *ciphers = NULL;
425 if (!PyArg_ParseTuple(args, "O!i|zziizz:sslwrap",
426 PySocketModule.Sock_Type,
427 &Sock,
428 &server_side,
429 &key_file, &cert_file,
430 &verification_mode, &protocol,
431 &cacerts_file, &ciphers))
432 return NULL;
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);
442 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
443 server_side, verification_mode,
444 protocol, cacerts_file,
445 ciphers);
448 PyDoc_STRVAR(ssl_doc,
449 "sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
450 " cacertsfile, ciphers]) -> sslobject");
452 /* SSL object methods */
454 static PyObject *PySSL_SSLdo_handshake(PySSLObject *self)
456 int ret;
457 int err;
458 int sockstate, nonblocking;
460 /* just in case the blocking state of the socket has been changed */
461 nonblocking = (self->Socket->sock_timeout >= 0.0);
462 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
463 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
465 /* Actually negotiate SSL connection */
466 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
467 do {
468 PySSL_BEGIN_ALLOW_THREADS
469 ret = SSL_do_handshake(self->ssl);
470 err = SSL_get_error(self->ssl, ret);
471 PySSL_END_ALLOW_THREADS
472 if(PyErr_CheckSignals()) {
473 return NULL;
475 if (err == SSL_ERROR_WANT_READ) {
476 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
477 } else if (err == SSL_ERROR_WANT_WRITE) {
478 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
479 } else {
480 sockstate = SOCKET_OPERATION_OK;
482 if (sockstate == SOCKET_HAS_TIMED_OUT) {
483 PyErr_SetString(PySSLErrorObject,
484 ERRSTR("The handshake operation timed out"));
485 return NULL;
486 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
487 PyErr_SetString(PySSLErrorObject,
488 ERRSTR("Underlying socket has been closed."));
489 return NULL;
490 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
491 PyErr_SetString(PySSLErrorObject,
492 ERRSTR("Underlying socket too large for select()."));
493 return NULL;
494 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
495 break;
497 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
498 if (ret < 1)
499 return PySSL_SetError(self, ret, __FILE__, __LINE__);
501 if (self->peer_cert)
502 X509_free (self->peer_cert);
503 PySSL_BEGIN_ALLOW_THREADS
504 if ((self->peer_cert = SSL_get_peer_certificate(self->ssl))) {
505 X509_NAME_oneline(X509_get_subject_name(self->peer_cert),
506 self->server, X509_NAME_MAXLEN);
507 X509_NAME_oneline(X509_get_issuer_name(self->peer_cert),
508 self->issuer, X509_NAME_MAXLEN);
510 PySSL_END_ALLOW_THREADS
512 Py_INCREF(Py_None);
513 return Py_None;
516 static PyObject *
517 PySSL_server(PySSLObject *self)
519 return PyString_FromString(self->server);
522 static PyObject *
523 PySSL_issuer(PySSLObject *self)
525 return PyString_FromString(self->issuer);
528 static PyObject *
529 _create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
531 char namebuf[X509_NAME_MAXLEN];
532 int buflen;
533 PyObject *name_obj;
534 PyObject *value_obj;
535 PyObject *attr;
536 unsigned char *valuebuf = NULL;
538 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
539 if (buflen < 0) {
540 _setSSLError(NULL, 0, __FILE__, __LINE__);
541 goto fail;
543 name_obj = PyString_FromStringAndSize(namebuf, buflen);
544 if (name_obj == NULL)
545 goto fail;
547 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
548 if (buflen < 0) {
549 _setSSLError(NULL, 0, __FILE__, __LINE__);
550 Py_DECREF(name_obj);
551 goto fail;
553 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
554 buflen, "strict");
555 OPENSSL_free(valuebuf);
556 if (value_obj == NULL) {
557 Py_DECREF(name_obj);
558 goto fail;
560 attr = PyTuple_New(2);
561 if (attr == NULL) {
562 Py_DECREF(name_obj);
563 Py_DECREF(value_obj);
564 goto fail;
566 PyTuple_SET_ITEM(attr, 0, name_obj);
567 PyTuple_SET_ITEM(attr, 1, value_obj);
568 return attr;
570 fail:
571 return NULL;
574 static PyObject *
575 _create_tuple_for_X509_NAME (X509_NAME *xname)
577 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
578 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
579 PyObject *rdnt;
580 PyObject *attr = NULL; /* tuple to hold an attribute */
581 int entry_count = X509_NAME_entry_count(xname);
582 X509_NAME_ENTRY *entry;
583 ASN1_OBJECT *name;
584 ASN1_STRING *value;
585 int index_counter;
586 int rdn_level = -1;
587 int retcode;
589 dn = PyList_New(0);
590 if (dn == NULL)
591 return NULL;
592 /* now create another tuple to hold the top-level RDN */
593 rdn = PyList_New(0);
594 if (rdn == NULL)
595 goto fail0;
597 for (index_counter = 0;
598 index_counter < entry_count;
599 index_counter++)
601 entry = X509_NAME_get_entry(xname, index_counter);
603 /* check to see if we've gotten to a new RDN */
604 if (rdn_level >= 0) {
605 if (rdn_level != entry->set) {
606 /* yes, new RDN */
607 /* add old RDN to DN */
608 rdnt = PyList_AsTuple(rdn);
609 Py_DECREF(rdn);
610 if (rdnt == NULL)
611 goto fail0;
612 retcode = PyList_Append(dn, rdnt);
613 Py_DECREF(rdnt);
614 if (retcode < 0)
615 goto fail0;
616 /* create new RDN */
617 rdn = PyList_New(0);
618 if (rdn == NULL)
619 goto fail0;
622 rdn_level = entry->set;
624 /* now add this attribute to the current RDN */
625 name = X509_NAME_ENTRY_get_object(entry);
626 value = X509_NAME_ENTRY_get_data(entry);
627 attr = _create_tuple_for_attribute(name, value);
629 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
630 entry->set,
631 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
632 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
634 if (attr == NULL)
635 goto fail1;
636 retcode = PyList_Append(rdn, attr);
637 Py_DECREF(attr);
638 if (retcode < 0)
639 goto fail1;
641 /* now, there's typically a dangling RDN */
642 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
643 rdnt = PyList_AsTuple(rdn);
644 Py_DECREF(rdn);
645 if (rdnt == NULL)
646 goto fail0;
647 retcode = PyList_Append(dn, rdnt);
648 Py_DECREF(rdnt);
649 if (retcode < 0)
650 goto fail0;
653 /* convert list to tuple */
654 rdnt = PyList_AsTuple(dn);
655 Py_DECREF(dn);
656 if (rdnt == NULL)
657 return NULL;
658 return rdnt;
660 fail1:
661 Py_XDECREF(rdn);
663 fail0:
664 Py_XDECREF(dn);
665 return NULL;
668 static PyObject *
669 _get_peer_alt_names (X509 *certificate) {
671 /* this code follows the procedure outlined in
672 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
673 function to extract the STACK_OF(GENERAL_NAME),
674 then iterates through the stack to add the
675 names. */
677 int i, j;
678 PyObject *peer_alt_names = Py_None;
679 PyObject *v, *t;
680 X509_EXTENSION *ext = NULL;
681 GENERAL_NAMES *names = NULL;
682 GENERAL_NAME *name;
683 X509V3_EXT_METHOD *method;
684 BIO *biobuf = NULL;
685 char buf[2048];
686 char *vptr;
687 int len;
688 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
689 #if OPENSSL_VERSION_NUMBER >= 0x009060dfL
690 const unsigned char *p;
691 #else
692 unsigned char *p;
693 #endif
695 if (certificate == NULL)
696 return peer_alt_names;
698 /* get a memory buffer */
699 biobuf = BIO_new(BIO_s_mem());
701 i = 0;
702 while ((i = X509_get_ext_by_NID(
703 certificate, NID_subject_alt_name, i)) >= 0) {
705 if (peer_alt_names == Py_None) {
706 peer_alt_names = PyList_New(0);
707 if (peer_alt_names == NULL)
708 goto fail;
711 /* now decode the altName */
712 ext = X509_get_ext(certificate, i);
713 if(!(method = X509V3_EXT_get(ext))) {
714 PyErr_SetString(PySSLErrorObject,
715 ERRSTR("No method for internalizing subjectAltName!"));
716 goto fail;
719 p = ext->value->data;
720 if (method->it)
721 names = (GENERAL_NAMES*) (ASN1_item_d2i(NULL,
723 ext->value->length,
724 ASN1_ITEM_ptr(method->it)));
725 else
726 names = (GENERAL_NAMES*) (method->d2i(NULL,
728 ext->value->length));
730 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
732 /* get a rendering of each name in the set of names */
734 name = sk_GENERAL_NAME_value(names, j);
735 if (name->type == GEN_DIRNAME) {
737 /* we special-case DirName as a tuple of tuples of attributes */
739 t = PyTuple_New(2);
740 if (t == NULL) {
741 goto fail;
744 v = PyString_FromString("DirName");
745 if (v == NULL) {
746 Py_DECREF(t);
747 goto fail;
749 PyTuple_SET_ITEM(t, 0, v);
751 v = _create_tuple_for_X509_NAME (name->d.dirn);
752 if (v == NULL) {
753 Py_DECREF(t);
754 goto fail;
756 PyTuple_SET_ITEM(t, 1, v);
758 } else {
760 /* for everything else, we use the OpenSSL print form */
762 (void) BIO_reset(biobuf);
763 GENERAL_NAME_print(biobuf, name);
764 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
765 if (len < 0) {
766 _setSSLError(NULL, 0, __FILE__, __LINE__);
767 goto fail;
769 vptr = strchr(buf, ':');
770 if (vptr == NULL)
771 goto fail;
772 t = PyTuple_New(2);
773 if (t == NULL)
774 goto fail;
775 v = PyString_FromStringAndSize(buf, (vptr - buf));
776 if (v == NULL) {
777 Py_DECREF(t);
778 goto fail;
780 PyTuple_SET_ITEM(t, 0, v);
781 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
782 if (v == NULL) {
783 Py_DECREF(t);
784 goto fail;
786 PyTuple_SET_ITEM(t, 1, v);
789 /* and add that rendering to the list */
791 if (PyList_Append(peer_alt_names, t) < 0) {
792 Py_DECREF(t);
793 goto fail;
795 Py_DECREF(t);
798 BIO_free(biobuf);
799 if (peer_alt_names != Py_None) {
800 v = PyList_AsTuple(peer_alt_names);
801 Py_DECREF(peer_alt_names);
802 return v;
803 } else {
804 return peer_alt_names;
808 fail:
809 if (biobuf != NULL)
810 BIO_free(biobuf);
812 if (peer_alt_names != Py_None) {
813 Py_XDECREF(peer_alt_names);
816 return NULL;
819 static PyObject *
820 _decode_certificate (X509 *certificate, int verbose) {
822 PyObject *retval = NULL;
823 BIO *biobuf = NULL;
824 PyObject *peer;
825 PyObject *peer_alt_names = NULL;
826 PyObject *issuer;
827 PyObject *version;
828 PyObject *sn_obj;
829 ASN1_INTEGER *serialNumber;
830 char buf[2048];
831 int len;
832 ASN1_TIME *notBefore, *notAfter;
833 PyObject *pnotBefore, *pnotAfter;
835 retval = PyDict_New();
836 if (retval == NULL)
837 return NULL;
839 peer = _create_tuple_for_X509_NAME(
840 X509_get_subject_name(certificate));
841 if (peer == NULL)
842 goto fail0;
843 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
844 Py_DECREF(peer);
845 goto fail0;
847 Py_DECREF(peer);
849 if (verbose) {
850 issuer = _create_tuple_for_X509_NAME(
851 X509_get_issuer_name(certificate));
852 if (issuer == NULL)
853 goto fail0;
854 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
855 Py_DECREF(issuer);
856 goto fail0;
858 Py_DECREF(issuer);
860 version = PyInt_FromLong(X509_get_version(certificate) + 1);
861 if (PyDict_SetItemString(retval, "version", version) < 0) {
862 Py_DECREF(version);
863 goto fail0;
865 Py_DECREF(version);
868 /* get a memory buffer */
869 biobuf = BIO_new(BIO_s_mem());
871 if (verbose) {
873 (void) BIO_reset(biobuf);
874 serialNumber = X509_get_serialNumber(certificate);
875 /* should not exceed 20 octets, 160 bits, so buf is big enough */
876 i2a_ASN1_INTEGER(biobuf, serialNumber);
877 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
878 if (len < 0) {
879 _setSSLError(NULL, 0, __FILE__, __LINE__);
880 goto fail1;
882 sn_obj = PyString_FromStringAndSize(buf, len);
883 if (sn_obj == NULL)
884 goto fail1;
885 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
886 Py_DECREF(sn_obj);
887 goto fail1;
889 Py_DECREF(sn_obj);
891 (void) BIO_reset(biobuf);
892 notBefore = X509_get_notBefore(certificate);
893 ASN1_TIME_print(biobuf, notBefore);
894 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
895 if (len < 0) {
896 _setSSLError(NULL, 0, __FILE__, __LINE__);
897 goto fail1;
899 pnotBefore = PyString_FromStringAndSize(buf, len);
900 if (pnotBefore == NULL)
901 goto fail1;
902 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
903 Py_DECREF(pnotBefore);
904 goto fail1;
906 Py_DECREF(pnotBefore);
909 (void) BIO_reset(biobuf);
910 notAfter = X509_get_notAfter(certificate);
911 ASN1_TIME_print(biobuf, notAfter);
912 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
913 if (len < 0) {
914 _setSSLError(NULL, 0, __FILE__, __LINE__);
915 goto fail1;
917 pnotAfter = PyString_FromStringAndSize(buf, len);
918 if (pnotAfter == NULL)
919 goto fail1;
920 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
921 Py_DECREF(pnotAfter);
922 goto fail1;
924 Py_DECREF(pnotAfter);
926 /* Now look for subjectAltName */
928 peer_alt_names = _get_peer_alt_names(certificate);
929 if (peer_alt_names == NULL)
930 goto fail1;
931 else if (peer_alt_names != Py_None) {
932 if (PyDict_SetItemString(retval, "subjectAltName",
933 peer_alt_names) < 0) {
934 Py_DECREF(peer_alt_names);
935 goto fail1;
937 Py_DECREF(peer_alt_names);
940 BIO_free(biobuf);
941 return retval;
943 fail1:
944 if (biobuf != NULL)
945 BIO_free(biobuf);
946 fail0:
947 Py_XDECREF(retval);
948 return NULL;
952 static PyObject *
953 PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
955 PyObject *retval = NULL;
956 char *filename = NULL;
957 X509 *x=NULL;
958 BIO *cert;
959 int verbose = 1;
961 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", &filename, &verbose))
962 return NULL;
964 if ((cert=BIO_new(BIO_s_file())) == NULL) {
965 PyErr_SetString(PySSLErrorObject, "Can't malloc memory to read file");
966 goto fail0;
969 if (BIO_read_filename(cert,filename) <= 0) {
970 PyErr_SetString(PySSLErrorObject, "Can't open file");
971 goto fail0;
974 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
975 if (x == NULL) {
976 PyErr_SetString(PySSLErrorObject, "Error decoding PEM-encoded file");
977 goto fail0;
980 retval = _decode_certificate(x, verbose);
982 fail0:
984 if (cert != NULL) BIO_free(cert);
985 return retval;
989 static PyObject *
990 PySSL_peercert(PySSLObject *self, PyObject *args)
992 PyObject *retval = NULL;
993 int len;
994 int verification;
995 PyObject *binary_mode = Py_None;
997 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
998 return NULL;
1000 if (!self->peer_cert)
1001 Py_RETURN_NONE;
1003 if (PyObject_IsTrue(binary_mode)) {
1004 /* return cert in DER-encoded format */
1006 unsigned char *bytes_buf = NULL;
1008 bytes_buf = NULL;
1009 len = i2d_X509(self->peer_cert, &bytes_buf);
1010 if (len < 0) {
1011 PySSL_SetError(self, len, __FILE__, __LINE__);
1012 return NULL;
1014 retval = PyString_FromStringAndSize((const char *) bytes_buf, len);
1015 OPENSSL_free(bytes_buf);
1016 return retval;
1018 } else {
1020 verification = SSL_CTX_get_verify_mode(self->ctx);
1021 if ((verification & SSL_VERIFY_PEER) == 0)
1022 return PyDict_New();
1023 else
1024 return _decode_certificate (self->peer_cert, 0);
1028 PyDoc_STRVAR(PySSL_peercert_doc,
1029 "peer_certificate([der=False]) -> certificate\n\
1031 Returns the certificate for the peer. If no certificate was provided,\n\
1032 returns None. If a certificate was provided, but not validated, returns\n\
1033 an empty dictionary. Otherwise returns a dict containing information\n\
1034 about the peer certificate.\n\
1036 If the optional argument is True, returns a DER-encoded copy of the\n\
1037 peer certificate, or None if no certificate was provided. This will\n\
1038 return the certificate even if it wasn't validated.");
1040 static PyObject *PySSL_cipher (PySSLObject *self) {
1042 PyObject *retval, *v;
1043 SSL_CIPHER *current;
1044 char *cipher_name;
1045 char *cipher_protocol;
1047 if (self->ssl == NULL)
1048 return Py_None;
1049 current = SSL_get_current_cipher(self->ssl);
1050 if (current == NULL)
1051 return Py_None;
1053 retval = PyTuple_New(3);
1054 if (retval == NULL)
1055 return NULL;
1057 cipher_name = (char *) SSL_CIPHER_get_name(current);
1058 if (cipher_name == NULL) {
1059 PyTuple_SET_ITEM(retval, 0, Py_None);
1060 } else {
1061 v = PyString_FromString(cipher_name);
1062 if (v == NULL)
1063 goto fail0;
1064 PyTuple_SET_ITEM(retval, 0, v);
1066 cipher_protocol = SSL_CIPHER_get_version(current);
1067 if (cipher_protocol == NULL) {
1068 PyTuple_SET_ITEM(retval, 1, Py_None);
1069 } else {
1070 v = PyString_FromString(cipher_protocol);
1071 if (v == NULL)
1072 goto fail0;
1073 PyTuple_SET_ITEM(retval, 1, v);
1075 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1076 if (v == NULL)
1077 goto fail0;
1078 PyTuple_SET_ITEM(retval, 2, v);
1079 return retval;
1081 fail0:
1082 Py_DECREF(retval);
1083 return NULL;
1086 static void PySSL_dealloc(PySSLObject *self)
1088 if (self->peer_cert) /* Possible not to have one? */
1089 X509_free (self->peer_cert);
1090 if (self->ssl)
1091 SSL_free(self->ssl);
1092 if (self->ctx)
1093 SSL_CTX_free(self->ctx);
1094 Py_XDECREF(self->Socket);
1095 PyObject_Del(self);
1098 /* If the socket has a timeout, do a select()/poll() on the socket.
1099 The argument writing indicates the direction.
1100 Returns one of the possibilities in the timeout_state enum (above).
1103 static int
1104 check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
1106 fd_set fds;
1107 struct timeval tv;
1108 int rc;
1110 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1111 if (s->sock_timeout < 0.0)
1112 return SOCKET_IS_BLOCKING;
1113 else if (s->sock_timeout == 0.0)
1114 return SOCKET_IS_NONBLOCKING;
1116 /* Guard against closed socket */
1117 if (s->sock_fd < 0)
1118 return SOCKET_HAS_BEEN_CLOSED;
1120 /* Prefer poll, if available, since you can poll() any fd
1121 * which can't be done with select(). */
1122 #ifdef HAVE_POLL
1124 struct pollfd pollfd;
1125 int timeout;
1127 pollfd.fd = s->sock_fd;
1128 pollfd.events = writing ? POLLOUT : POLLIN;
1130 /* s->sock_timeout is in seconds, timeout in ms */
1131 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1132 PySSL_BEGIN_ALLOW_THREADS
1133 rc = poll(&pollfd, 1, timeout);
1134 PySSL_END_ALLOW_THREADS
1136 goto normal_return;
1138 #endif
1140 /* Guard against socket too large for select*/
1141 #ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
1142 if (s->sock_fd >= FD_SETSIZE)
1143 return SOCKET_TOO_LARGE_FOR_SELECT;
1144 #endif
1146 /* Construct the arguments to select */
1147 tv.tv_sec = (int)s->sock_timeout;
1148 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1149 FD_ZERO(&fds);
1150 FD_SET(s->sock_fd, &fds);
1152 /* See if the socket is ready */
1153 PySSL_BEGIN_ALLOW_THREADS
1154 if (writing)
1155 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1156 else
1157 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1158 PySSL_END_ALLOW_THREADS
1160 #ifdef HAVE_POLL
1161 normal_return:
1162 #endif
1163 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1164 (when we are able to write or when there's something to read) */
1165 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
1168 static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1170 Py_buffer buf;
1171 int len;
1172 int sockstate;
1173 int err;
1174 int nonblocking;
1176 if (!PyArg_ParseTuple(args, "s*:write", &buf))
1177 return NULL;
1179 /* just in case the blocking state of the socket has been changed */
1180 nonblocking = (self->Socket->sock_timeout >= 0.0);
1181 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1182 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1184 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1185 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1186 PyErr_SetString(PySSLErrorObject,
1187 "The write operation timed out");
1188 goto error;
1189 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1190 PyErr_SetString(PySSLErrorObject,
1191 "Underlying socket has been closed.");
1192 goto error;
1193 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1194 PyErr_SetString(PySSLErrorObject,
1195 "Underlying socket too large for select().");
1196 goto error;
1198 do {
1199 PySSL_BEGIN_ALLOW_THREADS
1200 len = SSL_write(self->ssl, buf.buf, buf.len);
1201 err = SSL_get_error(self->ssl, len);
1202 PySSL_END_ALLOW_THREADS
1203 if (PyErr_CheckSignals()) {
1204 goto error;
1206 if (err == SSL_ERROR_WANT_READ) {
1207 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1208 } else if (err == SSL_ERROR_WANT_WRITE) {
1209 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1210 } else {
1211 sockstate = SOCKET_OPERATION_OK;
1213 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1214 PyErr_SetString(PySSLErrorObject,
1215 "The write operation timed out");
1216 goto error;
1217 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1218 PyErr_SetString(PySSLErrorObject,
1219 "Underlying socket has been closed.");
1220 goto error;
1221 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1222 break;
1224 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1226 PyBuffer_Release(&buf);
1227 if (len > 0)
1228 return PyInt_FromLong(len);
1229 else
1230 return PySSL_SetError(self, len, __FILE__, __LINE__);
1232 error:
1233 PyBuffer_Release(&buf);
1234 return NULL;
1237 PyDoc_STRVAR(PySSL_SSLwrite_doc,
1238 "write(s) -> len\n\
1240 Writes the string s into the SSL object. Returns the number\n\
1241 of bytes written.");
1243 static PyObject *PySSL_SSLpending(PySSLObject *self)
1245 int count = 0;
1247 PySSL_BEGIN_ALLOW_THREADS
1248 count = SSL_pending(self->ssl);
1249 PySSL_END_ALLOW_THREADS
1250 if (count < 0)
1251 return PySSL_SetError(self, count, __FILE__, __LINE__);
1252 else
1253 return PyInt_FromLong(count);
1256 PyDoc_STRVAR(PySSL_SSLpending_doc,
1257 "pending() -> count\n\
1259 Returns the number of already decrypted bytes available for read,\n\
1260 pending on the connection.\n");
1262 static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1264 PyObject *buf;
1265 int count = 0;
1266 int len = 1024;
1267 int sockstate;
1268 int err;
1269 int nonblocking;
1271 if (!PyArg_ParseTuple(args, "|i:read", &len))
1272 return NULL;
1274 if (!(buf = PyString_FromStringAndSize((char *) 0, len)))
1275 return NULL;
1277 /* just in case the blocking state of the socket has been changed */
1278 nonblocking = (self->Socket->sock_timeout >= 0.0);
1279 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1280 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1282 /* first check if there are bytes ready to be read */
1283 PySSL_BEGIN_ALLOW_THREADS
1284 count = SSL_pending(self->ssl);
1285 PySSL_END_ALLOW_THREADS
1287 if (!count) {
1288 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1289 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1290 PyErr_SetString(PySSLErrorObject,
1291 "The read operation timed out");
1292 Py_DECREF(buf);
1293 return NULL;
1294 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1295 PyErr_SetString(PySSLErrorObject,
1296 "Underlying socket too large for select().");
1297 Py_DECREF(buf);
1298 return NULL;
1299 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1300 if (SSL_get_shutdown(self->ssl) !=
1301 SSL_RECEIVED_SHUTDOWN)
1303 Py_DECREF(buf);
1304 PyErr_SetString(PySSLErrorObject,
1305 "Socket closed without SSL shutdown handshake");
1306 return NULL;
1307 } else {
1308 /* should contain a zero-length string */
1309 _PyString_Resize(&buf, 0);
1310 return buf;
1314 do {
1315 PySSL_BEGIN_ALLOW_THREADS
1316 count = SSL_read(self->ssl, PyString_AsString(buf), len);
1317 err = SSL_get_error(self->ssl, count);
1318 PySSL_END_ALLOW_THREADS
1319 if(PyErr_CheckSignals()) {
1320 Py_DECREF(buf);
1321 return NULL;
1323 if (err == SSL_ERROR_WANT_READ) {
1324 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1325 } else if (err == SSL_ERROR_WANT_WRITE) {
1326 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1327 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1328 (SSL_get_shutdown(self->ssl) ==
1329 SSL_RECEIVED_SHUTDOWN))
1331 _PyString_Resize(&buf, 0);
1332 return buf;
1333 } else {
1334 sockstate = SOCKET_OPERATION_OK;
1336 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1337 PyErr_SetString(PySSLErrorObject,
1338 "The read operation timed out");
1339 Py_DECREF(buf);
1340 return NULL;
1341 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1342 break;
1344 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1345 if (count <= 0) {
1346 Py_DECREF(buf);
1347 return PySSL_SetError(self, count, __FILE__, __LINE__);
1349 if (count != len)
1350 _PyString_Resize(&buf, count);
1351 return buf;
1354 PyDoc_STRVAR(PySSL_SSLread_doc,
1355 "read([len]) -> string\n\
1357 Read up to len bytes from the SSL socket.");
1359 static PyObject *PySSL_SSLshutdown(PySSLObject *self)
1361 int err, ssl_err, sockstate, nonblocking;
1362 int zeros = 0;
1364 /* Guard against closed socket */
1365 if (self->Socket->sock_fd < 0) {
1366 PyErr_SetString(PySSLErrorObject,
1367 "Underlying socket has been closed.");
1368 return NULL;
1371 /* Just in case the blocking state of the socket has been changed */
1372 nonblocking = (self->Socket->sock_timeout >= 0.0);
1373 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1374 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1376 while (1) {
1377 PySSL_BEGIN_ALLOW_THREADS
1378 /* Disable read-ahead so that unwrap can work correctly.
1379 * Otherwise OpenSSL might read in too much data,
1380 * eating clear text data that happens to be
1381 * transmitted after the SSL shutdown.
1382 * Should be safe to call repeatedly everytime this
1383 * function is used and the shutdown_seen_zero != 0
1384 * condition is met.
1386 if (self->shutdown_seen_zero)
1387 SSL_set_read_ahead(self->ssl, 0);
1388 err = SSL_shutdown(self->ssl);
1389 PySSL_END_ALLOW_THREADS
1390 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1391 if (err > 0)
1392 break;
1393 if (err == 0) {
1394 /* Don't loop endlessly; instead preserve legacy
1395 behaviour of trying SSL_shutdown() only twice.
1396 This looks necessary for OpenSSL < 0.9.8m */
1397 if (++zeros > 1)
1398 break;
1399 /* Shutdown was sent, now try receiving */
1400 self->shutdown_seen_zero = 1;
1401 continue;
1404 /* Possibly retry shutdown until timeout or failure */
1405 ssl_err = SSL_get_error(self->ssl, err);
1406 if (ssl_err == SSL_ERROR_WANT_READ)
1407 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1408 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1409 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1410 else
1411 break;
1412 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1413 if (ssl_err == SSL_ERROR_WANT_READ)
1414 PyErr_SetString(PySSLErrorObject,
1415 "The read operation timed out");
1416 else
1417 PyErr_SetString(PySSLErrorObject,
1418 "The write operation timed out");
1419 return NULL;
1421 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1422 PyErr_SetString(PySSLErrorObject,
1423 "Underlying socket too large for select().");
1424 return NULL;
1426 else if (sockstate != SOCKET_OPERATION_OK)
1427 /* Retain the SSL error code */
1428 break;
1431 if (err < 0)
1432 return PySSL_SetError(self, err, __FILE__, __LINE__);
1433 else {
1434 Py_INCREF(self->Socket);
1435 return (PyObject *) (self->Socket);
1439 PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1440 "shutdown(s) -> socket\n\
1442 Does the SSL shutdown handshake with the remote end, and returns\n\
1443 the underlying socket object.");
1445 static PyMethodDef PySSLMethods[] = {
1446 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1447 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1448 PySSL_SSLwrite_doc},
1449 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1450 PySSL_SSLread_doc},
1451 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1452 PySSL_SSLpending_doc},
1453 {"server", (PyCFunction)PySSL_server, METH_NOARGS},
1454 {"issuer", (PyCFunction)PySSL_issuer, METH_NOARGS},
1455 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1456 PySSL_peercert_doc},
1457 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1458 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1459 PySSL_SSLshutdown_doc},
1460 {NULL, NULL}
1463 static PyObject *PySSL_getattr(PySSLObject *self, char *name)
1465 return Py_FindMethod(PySSLMethods, (PyObject *)self, name);
1468 static PyTypeObject PySSL_Type = {
1469 PyVarObject_HEAD_INIT(NULL, 0)
1470 "ssl.SSLContext", /*tp_name*/
1471 sizeof(PySSLObject), /*tp_basicsize*/
1472 0, /*tp_itemsize*/
1473 /* methods */
1474 (destructor)PySSL_dealloc, /*tp_dealloc*/
1475 0, /*tp_print*/
1476 (getattrfunc)PySSL_getattr, /*tp_getattr*/
1477 0, /*tp_setattr*/
1478 0, /*tp_compare*/
1479 0, /*tp_repr*/
1480 0, /*tp_as_number*/
1481 0, /*tp_as_sequence*/
1482 0, /*tp_as_mapping*/
1483 0, /*tp_hash*/
1486 #ifdef HAVE_OPENSSL_RAND
1488 /* helper routines for seeding the SSL PRNG */
1489 static PyObject *
1490 PySSL_RAND_add(PyObject *self, PyObject *args)
1492 char *buf;
1493 int len;
1494 double entropy;
1496 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
1497 return NULL;
1498 RAND_add(buf, len, entropy);
1499 Py_INCREF(Py_None);
1500 return Py_None;
1503 PyDoc_STRVAR(PySSL_RAND_add_doc,
1504 "RAND_add(string, entropy)\n\
1506 Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
1507 bound on the entropy contained in string. See RFC 1750.");
1509 static PyObject *
1510 PySSL_RAND_status(PyObject *self)
1512 return PyInt_FromLong(RAND_status());
1515 PyDoc_STRVAR(PySSL_RAND_status_doc,
1516 "RAND_status() -> 0 or 1\n\
1518 Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1519 It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1520 using the ssl() function.");
1522 static PyObject *
1523 PySSL_RAND_egd(PyObject *self, PyObject *arg)
1525 int bytes;
1527 if (!PyString_Check(arg))
1528 return PyErr_Format(PyExc_TypeError,
1529 "RAND_egd() expected string, found %s",
1530 Py_TYPE(arg)->tp_name);
1531 bytes = RAND_egd(PyString_AS_STRING(arg));
1532 if (bytes == -1) {
1533 PyErr_SetString(PySSLErrorObject,
1534 "EGD connection failed or EGD did not return "
1535 "enough data to seed the PRNG");
1536 return NULL;
1538 return PyInt_FromLong(bytes);
1541 PyDoc_STRVAR(PySSL_RAND_egd_doc,
1542 "RAND_egd(path) -> bytes\n\
1544 Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1545 Returns number of bytes read. Raises SSLError if connection to EGD\n\
1546 fails or if it does provide enough data to seed PRNG.");
1548 #endif
1550 /* List of functions exported by this module. */
1552 static PyMethodDef PySSL_methods[] = {
1553 {"sslwrap", PySSL_sslwrap,
1554 METH_VARARGS, ssl_doc},
1555 {"_test_decode_cert", PySSL_test_decode_certificate,
1556 METH_VARARGS},
1557 #ifdef HAVE_OPENSSL_RAND
1558 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1559 PySSL_RAND_add_doc},
1560 {"RAND_egd", PySSL_RAND_egd, METH_O,
1561 PySSL_RAND_egd_doc},
1562 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1563 PySSL_RAND_status_doc},
1564 #endif
1565 {NULL, NULL} /* Sentinel */
1569 #ifdef WITH_THREAD
1571 /* an implementation of OpenSSL threading operations in terms
1572 of the Python C thread library */
1574 static PyThread_type_lock *_ssl_locks = NULL;
1576 static unsigned long _ssl_thread_id_function (void) {
1577 return PyThread_get_thread_ident();
1580 static void _ssl_thread_locking_function (int mode, int n, const char *file, int line) {
1581 /* this function is needed to perform locking on shared data
1582 structures. (Note that OpenSSL uses a number of global data
1583 structures that will be implicitly shared whenever multiple threads
1584 use OpenSSL.) Multi-threaded applications will crash at random if
1585 it is not set.
1587 locking_function() must be able to handle up to CRYPTO_num_locks()
1588 different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and
1589 releases it otherwise.
1591 file and line are the file number of the function setting the
1592 lock. They can be useful for debugging.
1595 if ((_ssl_locks == NULL) ||
1596 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1597 return;
1599 if (mode & CRYPTO_LOCK) {
1600 PyThread_acquire_lock(_ssl_locks[n], 1);
1601 } else {
1602 PyThread_release_lock(_ssl_locks[n]);
1606 static int _setup_ssl_threads(void) {
1608 unsigned int i;
1610 if (_ssl_locks == NULL) {
1611 _ssl_locks_count = CRYPTO_num_locks();
1612 _ssl_locks = (PyThread_type_lock *)
1613 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1614 if (_ssl_locks == NULL)
1615 return 0;
1616 memset(_ssl_locks, 0, sizeof(PyThread_type_lock) * _ssl_locks_count);
1617 for (i = 0; i < _ssl_locks_count; i++) {
1618 _ssl_locks[i] = PyThread_allocate_lock();
1619 if (_ssl_locks[i] == NULL) {
1620 unsigned int j;
1621 for (j = 0; j < i; j++) {
1622 PyThread_free_lock(_ssl_locks[j]);
1624 free(_ssl_locks);
1625 return 0;
1628 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1629 CRYPTO_set_id_callback(_ssl_thread_id_function);
1631 return 1;
1634 #endif /* def HAVE_THREAD */
1636 PyDoc_STRVAR(module_doc,
1637 "Implementation module for SSL socket operations. See the socket module\n\
1638 for documentation.");
1640 PyMODINIT_FUNC
1641 init_ssl(void)
1643 PyObject *m, *d, *r;
1644 unsigned long libver;
1645 unsigned int major, minor, fix, patch, status;
1647 Py_TYPE(&PySSL_Type) = &PyType_Type;
1649 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
1650 if (m == NULL)
1651 return;
1652 d = PyModule_GetDict(m);
1654 /* Load _socket module and its C API */
1655 if (PySocketModule_ImportModuleAndAPI())
1656 return;
1658 /* Init OpenSSL */
1659 SSL_load_error_strings();
1660 SSL_library_init();
1661 #ifdef WITH_THREAD
1662 /* note that this will start threading if not already started */
1663 if (!_setup_ssl_threads()) {
1664 return;
1666 #endif
1667 OpenSSL_add_all_algorithms();
1669 /* Add symbols to module dict */
1670 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
1671 PySocketModule.error,
1672 NULL);
1673 if (PySSLErrorObject == NULL)
1674 return;
1675 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
1676 return;
1677 if (PyDict_SetItemString(d, "SSLType",
1678 (PyObject *)&PySSL_Type) != 0)
1679 return;
1680 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
1681 PY_SSL_ERROR_ZERO_RETURN);
1682 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
1683 PY_SSL_ERROR_WANT_READ);
1684 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
1685 PY_SSL_ERROR_WANT_WRITE);
1686 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
1687 PY_SSL_ERROR_WANT_X509_LOOKUP);
1688 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
1689 PY_SSL_ERROR_SYSCALL);
1690 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
1691 PY_SSL_ERROR_SSL);
1692 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1693 PY_SSL_ERROR_WANT_CONNECT);
1694 /* non ssl.h errorcodes */
1695 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1696 PY_SSL_ERROR_EOF);
1697 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1698 PY_SSL_ERROR_INVALID_ERROR_CODE);
1699 /* cert requirements */
1700 PyModule_AddIntConstant(m, "CERT_NONE",
1701 PY_SSL_CERT_NONE);
1702 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1703 PY_SSL_CERT_OPTIONAL);
1704 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1705 PY_SSL_CERT_REQUIRED);
1707 /* protocol versions */
1708 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1709 PY_SSL_VERSION_SSL2);
1710 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1711 PY_SSL_VERSION_SSL3);
1712 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1713 PY_SSL_VERSION_SSL23);
1714 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1715 PY_SSL_VERSION_TLS1);
1717 /* OpenSSL version */
1718 /* SSLeay() gives us the version of the library linked against,
1719 which could be different from the headers version.
1721 libver = SSLeay();
1722 r = PyLong_FromUnsignedLong(libver);
1723 if (r == NULL)
1724 return;
1725 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
1726 return;
1727 status = libver & 0xF;
1728 libver >>= 4;
1729 patch = libver & 0xFF;
1730 libver >>= 8;
1731 fix = libver & 0xFF;
1732 libver >>= 8;
1733 minor = libver & 0xFF;
1734 libver >>= 8;
1735 major = libver & 0xFF;
1736 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
1737 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
1738 return;
1739 r = PyString_FromString(SSLeay_version(SSLEAY_VERSION));
1740 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
1741 return;