Added updates with respect to recent changes to TimedRotatingFileHandler.
[python.git] / Modules / _ssl.c
blob3f167b32caf7fc32c247d8bf1648be8060489f59
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.
7 This module is imported by ssl.py. It should *not* be used
8 directly.
10 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
12 XXX what about SSL_MODE_AUTO_RETRY
15 #include "Python.h"
17 #ifdef WITH_THREAD
18 #include "pythread.h"
19 #define PySSL_BEGIN_ALLOW_THREADS { \
20 PyThreadState *_save = NULL; \
21 if (_ssl_locks_count>0) {_save = PyEval_SaveThread();}
22 #define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)};
23 #define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()};
24 #define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \
27 #else /* no WITH_THREAD */
29 #define PySSL_BEGIN_ALLOW_THREADS
30 #define PySSL_BLOCK_THREADS
31 #define PySSL_UNBLOCK_THREADS
32 #define PySSL_END_ALLOW_THREADS
34 #endif
36 enum py_ssl_error {
37 /* these mirror ssl.h */
38 PY_SSL_ERROR_NONE,
39 PY_SSL_ERROR_SSL,
40 PY_SSL_ERROR_WANT_READ,
41 PY_SSL_ERROR_WANT_WRITE,
42 PY_SSL_ERROR_WANT_X509_LOOKUP,
43 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
44 PY_SSL_ERROR_ZERO_RETURN,
45 PY_SSL_ERROR_WANT_CONNECT,
46 /* start of non ssl.h errorcodes */
47 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
48 PY_SSL_ERROR_INVALID_ERROR_CODE
51 enum py_ssl_server_or_client {
52 PY_SSL_CLIENT,
53 PY_SSL_SERVER
56 enum py_ssl_cert_requirements {
57 PY_SSL_CERT_NONE,
58 PY_SSL_CERT_OPTIONAL,
59 PY_SSL_CERT_REQUIRED
62 enum py_ssl_version {
63 PY_SSL_VERSION_SSL2,
64 PY_SSL_VERSION_SSL3,
65 PY_SSL_VERSION_SSL23,
66 PY_SSL_VERSION_TLS1,
69 /* Include symbols from _socket module */
70 #include "socketmodule.h"
72 #if defined(HAVE_POLL_H)
73 #include <poll.h>
74 #elif defined(HAVE_SYS_POLL_H)
75 #include <sys/poll.h>
76 #endif
78 /* Include OpenSSL header files */
79 #include "openssl/rsa.h"
80 #include "openssl/crypto.h"
81 #include "openssl/x509.h"
82 #include "openssl/x509v3.h"
83 #include "openssl/pem.h"
84 #include "openssl/ssl.h"
85 #include "openssl/err.h"
86 #include "openssl/rand.h"
88 /* SSL error object */
89 static PyObject *PySSLErrorObject;
91 #ifdef WITH_THREAD
93 /* serves as a flag to see whether we've initialized the SSL thread support. */
94 /* 0 means no, greater than 0 means yes */
96 static unsigned int _ssl_locks_count = 0;
98 #endif /* def WITH_THREAD */
100 /* SSL socket object */
102 #define X509_NAME_MAXLEN 256
104 /* RAND_* APIs got added to OpenSSL in 0.9.5 */
105 #if OPENSSL_VERSION_NUMBER >= 0x0090500fL
106 # define HAVE_OPENSSL_RAND 1
107 #else
108 # undef HAVE_OPENSSL_RAND
109 #endif
111 typedef struct {
112 PyObject_HEAD
113 PySocketSockObject *Socket; /* Socket on which we're layered */
114 SSL_CTX* ctx;
115 SSL* ssl;
116 X509* peer_cert;
117 char server[X509_NAME_MAXLEN];
118 char issuer[X509_NAME_MAXLEN];
120 } PySSLObject;
122 static PyTypeObject PySSL_Type;
123 static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args);
124 static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args);
125 static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
126 int writing);
127 static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args);
128 static PyObject *PySSL_cipher(PySSLObject *self);
130 #define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type)
132 typedef enum {
133 SOCKET_IS_NONBLOCKING,
134 SOCKET_IS_BLOCKING,
135 SOCKET_HAS_TIMED_OUT,
136 SOCKET_HAS_BEEN_CLOSED,
137 SOCKET_TOO_LARGE_FOR_SELECT,
138 SOCKET_OPERATION_OK
139 } timeout_state;
141 /* Wrap error strings with filename and line # */
142 #define STRINGIFY1(x) #x
143 #define STRINGIFY2(x) STRINGIFY1(x)
144 #define ERRSTR1(x,y,z) (x ":" y ": " z)
145 #define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
147 /* XXX It might be helpful to augment the error message generated
148 below with the name of the SSL function that generated the error.
149 I expect it's obvious most of the time.
152 static PyObject *
153 PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno)
155 PyObject *v;
156 char buf[2048];
157 char *errstr;
158 int err;
159 enum py_ssl_error p = PY_SSL_ERROR_NONE;
161 assert(ret <= 0);
163 if (obj->ssl != NULL) {
164 err = SSL_get_error(obj->ssl, ret);
166 switch (err) {
167 case SSL_ERROR_ZERO_RETURN:
168 errstr = "TLS/SSL connection has been closed";
169 p = PY_SSL_ERROR_ZERO_RETURN;
170 break;
171 case SSL_ERROR_WANT_READ:
172 errstr = "The operation did not complete (read)";
173 p = PY_SSL_ERROR_WANT_READ;
174 break;
175 case SSL_ERROR_WANT_WRITE:
176 p = PY_SSL_ERROR_WANT_WRITE;
177 errstr = "The operation did not complete (write)";
178 break;
179 case SSL_ERROR_WANT_X509_LOOKUP:
180 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
181 errstr =
182 "The operation did not complete (X509 lookup)";
183 break;
184 case SSL_ERROR_WANT_CONNECT:
185 p = PY_SSL_ERROR_WANT_CONNECT;
186 errstr = "The operation did not complete (connect)";
187 break;
188 case SSL_ERROR_SYSCALL:
190 unsigned long e = ERR_get_error();
191 if (e == 0) {
192 if (ret == 0 || !obj->Socket) {
193 p = PY_SSL_ERROR_EOF;
194 errstr =
195 "EOF occurred in violation of protocol";
196 } else if (ret == -1) {
197 /* underlying BIO reported an I/O error */
198 return obj->Socket->errorhandler();
199 } else { /* possible? */
200 p = PY_SSL_ERROR_SYSCALL;
201 errstr = "Some I/O error occurred";
203 } else {
204 p = PY_SSL_ERROR_SYSCALL;
205 /* XXX Protected by global interpreter lock */
206 errstr = ERR_error_string(e, NULL);
208 break;
210 case SSL_ERROR_SSL:
212 unsigned long e = ERR_get_error();
213 p = PY_SSL_ERROR_SSL;
214 if (e != 0)
215 /* XXX Protected by global interpreter lock */
216 errstr = ERR_error_string(e, NULL);
217 else { /* possible? */
218 errstr =
219 "A failure in the SSL library occurred";
221 break;
223 default:
224 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
225 errstr = "Invalid error code";
227 } else {
228 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
230 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
231 v = Py_BuildValue("(is)", p, buf);
232 if (v != NULL) {
233 PyErr_SetObject(PySSLErrorObject, v);
234 Py_DECREF(v);
236 return NULL;
239 static PyObject *
240 _setSSLError (char *errstr, int errcode, char *filename, int lineno) {
242 char buf[2048];
243 PyObject *v;
245 if (errstr == NULL) {
246 errcode = ERR_peek_last_error();
247 errstr = ERR_error_string(errcode, NULL);
249 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
250 v = Py_BuildValue("(is)", errcode, buf);
251 if (v != NULL) {
252 PyErr_SetObject(PySSLErrorObject, v);
253 Py_DECREF(v);
255 return NULL;
258 static PySSLObject *
259 newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file,
260 enum py_ssl_server_or_client socket_type,
261 enum py_ssl_cert_requirements certreq,
262 enum py_ssl_version proto_version,
263 char *cacerts_file)
265 PySSLObject *self;
266 char *errstr = NULL;
267 int ret;
268 int err;
269 int sockstate;
270 int verification_mode;
272 self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */
273 if (self == NULL)
274 return NULL;
275 memset(self->server, '\0', sizeof(char) * X509_NAME_MAXLEN);
276 memset(self->issuer, '\0', sizeof(char) * X509_NAME_MAXLEN);
277 self->peer_cert = NULL;
278 self->ssl = NULL;
279 self->ctx = NULL;
280 self->Socket = NULL;
282 /* Make sure the SSL error state is initialized */
283 (void) ERR_get_state();
284 ERR_clear_error();
286 if ((key_file && !cert_file) || (!key_file && cert_file)) {
287 errstr = ERRSTR("Both the key & certificate files "
288 "must be specified");
289 goto fail;
292 if ((socket_type == PY_SSL_SERVER) &&
293 ((key_file == NULL) || (cert_file == NULL))) {
294 errstr = ERRSTR("Both the key & certificate files "
295 "must be specified for server-side operation");
296 goto fail;
299 PySSL_BEGIN_ALLOW_THREADS
300 if (proto_version == PY_SSL_VERSION_TLS1)
301 self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */
302 else if (proto_version == PY_SSL_VERSION_SSL3)
303 self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */
304 else if (proto_version == PY_SSL_VERSION_SSL2)
305 self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */
306 else if (proto_version == PY_SSL_VERSION_SSL23)
307 self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
308 PySSL_END_ALLOW_THREADS
310 if (self->ctx == NULL) {
311 errstr = ERRSTR("Invalid SSL protocol variant specified.");
312 goto fail;
315 if (certreq != PY_SSL_CERT_NONE) {
316 if (cacerts_file == NULL) {
317 errstr = ERRSTR("No root certificates specified for "
318 "verification of other-side certificates.");
319 goto fail;
320 } else {
321 PySSL_BEGIN_ALLOW_THREADS
322 ret = SSL_CTX_load_verify_locations(self->ctx,
323 cacerts_file,
324 NULL);
325 PySSL_END_ALLOW_THREADS
326 if (ret != 1) {
327 _setSSLError(NULL, 0, __FILE__, __LINE__);
328 goto fail;
332 if (key_file) {
333 PySSL_BEGIN_ALLOW_THREADS
334 ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
335 SSL_FILETYPE_PEM);
336 PySSL_END_ALLOW_THREADS
337 if (ret != 1) {
338 _setSSLError(NULL, ret, __FILE__, __LINE__);
339 goto fail;
342 PySSL_BEGIN_ALLOW_THREADS
343 ret = SSL_CTX_use_certificate_chain_file(self->ctx,
344 cert_file);
345 PySSL_END_ALLOW_THREADS
346 if (ret != 1) {
348 fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
349 ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
351 if (ERR_peek_last_error() != 0) {
352 _setSSLError(NULL, ret, __FILE__, __LINE__);
353 goto fail;
358 /* ssl compatibility */
359 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
361 verification_mode = SSL_VERIFY_NONE;
362 if (certreq == PY_SSL_CERT_OPTIONAL)
363 verification_mode = SSL_VERIFY_PEER;
364 else if (certreq == PY_SSL_CERT_REQUIRED)
365 verification_mode = (SSL_VERIFY_PEER |
366 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
367 SSL_CTX_set_verify(self->ctx, verification_mode,
368 NULL); /* set verify lvl */
370 PySSL_BEGIN_ALLOW_THREADS
371 self->ssl = SSL_new(self->ctx); /* New ssl struct */
372 PySSL_END_ALLOW_THREADS
373 SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */
375 /* If the socket is in non-blocking mode or timeout mode, set the BIO
376 * to non-blocking mode (blocking is the default)
378 if (Sock->sock_timeout >= 0.0) {
379 /* Set both the read and write BIO's to non-blocking mode */
380 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
381 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
384 PySSL_BEGIN_ALLOW_THREADS
385 if (socket_type == PY_SSL_CLIENT)
386 SSL_set_connect_state(self->ssl);
387 else
388 SSL_set_accept_state(self->ssl);
389 PySSL_END_ALLOW_THREADS
391 /* Actually negotiate SSL connection */
392 /* XXX If SSL_connect() returns 0, it's also a failure. */
393 sockstate = 0;
394 do {
395 PySSL_BEGIN_ALLOW_THREADS
396 if (socket_type == PY_SSL_CLIENT)
397 ret = SSL_connect(self->ssl);
398 else
399 ret = SSL_accept(self->ssl);
400 err = SSL_get_error(self->ssl, ret);
401 PySSL_END_ALLOW_THREADS
402 if(PyErr_CheckSignals()) {
403 goto fail;
405 if (err == SSL_ERROR_WANT_READ) {
406 sockstate = check_socket_and_wait_for_timeout(Sock, 0);
407 } else if (err == SSL_ERROR_WANT_WRITE) {
408 sockstate = check_socket_and_wait_for_timeout(Sock, 1);
409 } else {
410 sockstate = SOCKET_OPERATION_OK;
412 if (sockstate == SOCKET_HAS_TIMED_OUT) {
413 PyErr_SetString(PySSLErrorObject,
414 ERRSTR("The connect operation timed out"));
415 goto fail;
416 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
417 PyErr_SetString(PySSLErrorObject,
418 ERRSTR("Underlying socket has been closed."));
419 goto fail;
420 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
421 PyErr_SetString(PySSLErrorObject,
422 ERRSTR("Underlying socket too large for select()."));
423 goto fail;
424 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
425 break;
427 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
428 if (ret < 1) {
429 PySSL_SetError(self, ret, __FILE__, __LINE__);
430 goto fail;
432 self->ssl->debug = 1;
434 PySSL_BEGIN_ALLOW_THREADS
435 if ((self->peer_cert = SSL_get_peer_certificate(self->ssl))) {
436 X509_NAME_oneline(X509_get_subject_name(self->peer_cert),
437 self->server, X509_NAME_MAXLEN);
438 X509_NAME_oneline(X509_get_issuer_name(self->peer_cert),
439 self->issuer, X509_NAME_MAXLEN);
441 PySSL_END_ALLOW_THREADS
442 self->Socket = Sock;
443 Py_INCREF(self->Socket);
444 return self;
445 fail:
446 if (errstr)
447 PyErr_SetString(PySSLErrorObject, errstr);
448 Py_DECREF(self);
449 return NULL;
452 static PyObject *
453 PySSL_sslwrap(PyObject *self, PyObject *args)
455 PySocketSockObject *Sock;
456 int server_side = 0;
457 int verification_mode = PY_SSL_CERT_NONE;
458 int protocol = PY_SSL_VERSION_SSL23;
459 char *key_file = NULL;
460 char *cert_file = NULL;
461 char *cacerts_file = NULL;
463 if (!PyArg_ParseTuple(args, "O!i|zziiz:sslwrap",
464 PySocketModule.Sock_Type,
465 &Sock,
466 &server_side,
467 &key_file, &cert_file,
468 &verification_mode, &protocol,
469 &cacerts_file))
470 return NULL;
473 fprintf(stderr,
474 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
475 "protocol %d, certs %p\n",
476 server_side, key_file, cert_file, verification_mode,
477 protocol, cacerts_file);
480 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
481 server_side, verification_mode,
482 protocol, cacerts_file);
485 PyDoc_STRVAR(ssl_doc,
486 "sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
487 " cacertsfile]) -> sslobject");
489 /* SSL object methods */
491 static PyObject *
492 PySSL_server(PySSLObject *self)
494 return PyString_FromString(self->server);
497 static PyObject *
498 PySSL_issuer(PySSLObject *self)
500 return PyString_FromString(self->issuer);
503 static PyObject *
504 _create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
506 char namebuf[X509_NAME_MAXLEN];
507 int buflen;
508 PyObject *name_obj;
509 PyObject *value_obj;
510 PyObject *attr;
511 unsigned char *valuebuf = NULL;
513 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
514 if (buflen < 0) {
515 _setSSLError(NULL, 0, __FILE__, __LINE__);
516 goto fail;
518 name_obj = PyString_FromStringAndSize(namebuf, buflen);
519 if (name_obj == NULL)
520 goto fail;
522 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
523 if (buflen < 0) {
524 _setSSLError(NULL, 0, __FILE__, __LINE__);
525 Py_DECREF(name_obj);
526 goto fail;
528 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
529 buflen, "strict");
530 OPENSSL_free(valuebuf);
531 if (value_obj == NULL) {
532 Py_DECREF(name_obj);
533 goto fail;
535 attr = PyTuple_New(2);
536 if (attr == NULL) {
537 Py_DECREF(name_obj);
538 Py_DECREF(value_obj);
539 goto fail;
541 PyTuple_SET_ITEM(attr, 0, name_obj);
542 PyTuple_SET_ITEM(attr, 1, value_obj);
543 return attr;
545 fail:
546 return NULL;
549 static PyObject *
550 _create_tuple_for_X509_NAME (X509_NAME *xname)
552 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
553 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
554 PyObject *rdnt;
555 PyObject *attr = NULL; /* tuple to hold an attribute */
556 int entry_count = X509_NAME_entry_count(xname);
557 X509_NAME_ENTRY *entry;
558 ASN1_OBJECT *name;
559 ASN1_STRING *value;
560 int index_counter;
561 int rdn_level = -1;
562 int retcode;
564 dn = PyList_New(0);
565 if (dn == NULL)
566 return NULL;
567 /* now create another tuple to hold the top-level RDN */
568 rdn = PyList_New(0);
569 if (rdn == NULL)
570 goto fail0;
572 for (index_counter = 0;
573 index_counter < entry_count;
574 index_counter++)
576 entry = X509_NAME_get_entry(xname, index_counter);
578 /* check to see if we've gotten to a new RDN */
579 if (rdn_level >= 0) {
580 if (rdn_level != entry->set) {
581 /* yes, new RDN */
582 /* add old RDN to DN */
583 rdnt = PyList_AsTuple(rdn);
584 Py_DECREF(rdn);
585 if (rdnt == NULL)
586 goto fail0;
587 retcode = PyList_Append(dn, rdnt);
588 Py_DECREF(rdnt);
589 if (retcode < 0)
590 goto fail0;
591 /* create new RDN */
592 rdn = PyList_New(0);
593 if (rdn == NULL)
594 goto fail0;
597 rdn_level = entry->set;
599 /* now add this attribute to the current RDN */
600 name = X509_NAME_ENTRY_get_object(entry);
601 value = X509_NAME_ENTRY_get_data(entry);
602 attr = _create_tuple_for_attribute(name, value);
604 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
605 entry->set,
606 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
607 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
609 if (attr == NULL)
610 goto fail1;
611 retcode = PyList_Append(rdn, attr);
612 Py_DECREF(attr);
613 if (retcode < 0)
614 goto fail1;
616 /* now, there's typically a dangling RDN */
617 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
618 rdnt = PyList_AsTuple(rdn);
619 Py_DECREF(rdn);
620 if (rdnt == NULL)
621 goto fail0;
622 retcode = PyList_Append(dn, rdnt);
623 Py_DECREF(rdnt);
624 if (retcode < 0)
625 goto fail0;
628 /* convert list to tuple */
629 rdnt = PyList_AsTuple(dn);
630 Py_DECREF(dn);
631 if (rdnt == NULL)
632 return NULL;
633 return rdnt;
635 fail1:
636 Py_XDECREF(rdn);
638 fail0:
639 Py_XDECREF(dn);
640 return NULL;
643 static PyObject *
644 _get_peer_alt_names (X509 *certificate) {
646 /* this code follows the procedure outlined in
647 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
648 function to extract the STACK_OF(GENERAL_NAME),
649 then iterates through the stack to add the
650 names. */
652 int i, j;
653 PyObject *peer_alt_names = Py_None;
654 PyObject *v, *t;
655 X509_EXTENSION *ext = NULL;
656 GENERAL_NAMES *names = NULL;
657 GENERAL_NAME *name;
658 X509V3_EXT_METHOD *method;
659 BIO *biobuf = NULL;
660 char buf[2048];
661 char *vptr;
662 int len;
663 const unsigned char *p;
665 if (certificate == NULL)
666 return peer_alt_names;
668 /* get a memory buffer */
669 biobuf = BIO_new(BIO_s_mem());
671 i = 0;
672 while ((i = X509_get_ext_by_NID(
673 certificate, NID_subject_alt_name, i)) >= 0) {
675 if (peer_alt_names == Py_None) {
676 peer_alt_names = PyList_New(0);
677 if (peer_alt_names == NULL)
678 goto fail;
681 /* now decode the altName */
682 ext = X509_get_ext(certificate, i);
683 if(!(method = X509V3_EXT_get(ext))) {
684 PyErr_SetString(PySSLErrorObject,
685 ERRSTR("No method for internalizing subjectAltName!"));
686 goto fail;
689 p = ext->value->data;
690 if (method->it)
691 names = (GENERAL_NAMES*) (ASN1_item_d2i(NULL,
693 ext->value->length,
694 ASN1_ITEM_ptr(method->it)));
695 else
696 names = (GENERAL_NAMES*) (method->d2i(NULL,
698 ext->value->length));
700 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
702 /* get a rendering of each name in the set of names */
704 name = sk_GENERAL_NAME_value(names, j);
705 if (name->type == GEN_DIRNAME) {
707 /* we special-case DirName as a tuple of tuples of attributes */
709 t = PyTuple_New(2);
710 if (t == NULL) {
711 goto fail;
714 v = PyString_FromString("DirName");
715 if (v == NULL) {
716 Py_DECREF(t);
717 goto fail;
719 PyTuple_SET_ITEM(t, 0, v);
721 v = _create_tuple_for_X509_NAME (name->d.dirn);
722 if (v == NULL) {
723 Py_DECREF(t);
724 goto fail;
726 PyTuple_SET_ITEM(t, 1, v);
728 } else {
730 /* for everything else, we use the OpenSSL print form */
732 (void) BIO_reset(biobuf);
733 GENERAL_NAME_print(biobuf, name);
734 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
735 if (len < 0) {
736 _setSSLError(NULL, 0, __FILE__, __LINE__);
737 goto fail;
739 vptr = strchr(buf, ':');
740 if (vptr == NULL)
741 goto fail;
742 t = PyTuple_New(2);
743 if (t == NULL)
744 goto fail;
745 v = PyString_FromStringAndSize(buf, (vptr - buf));
746 if (v == NULL) {
747 Py_DECREF(t);
748 goto fail;
750 PyTuple_SET_ITEM(t, 0, v);
751 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
752 if (v == NULL) {
753 Py_DECREF(t);
754 goto fail;
756 PyTuple_SET_ITEM(t, 1, v);
759 /* and add that rendering to the list */
761 if (PyList_Append(peer_alt_names, t) < 0) {
762 Py_DECREF(t);
763 goto fail;
765 Py_DECREF(t);
768 BIO_free(biobuf);
769 if (peer_alt_names != Py_None) {
770 v = PyList_AsTuple(peer_alt_names);
771 Py_DECREF(peer_alt_names);
772 return v;
773 } else {
774 return peer_alt_names;
778 fail:
779 if (biobuf != NULL)
780 BIO_free(biobuf);
782 if (peer_alt_names != Py_None) {
783 Py_XDECREF(peer_alt_names);
786 return NULL;
789 static PyObject *
790 _decode_certificate (X509 *certificate, int verbose) {
792 PyObject *retval = NULL;
793 BIO *biobuf = NULL;
794 PyObject *peer;
795 PyObject *peer_alt_names = NULL;
796 PyObject *issuer;
797 PyObject *version;
798 PyObject *sn_obj;
799 ASN1_INTEGER *serialNumber;
800 char buf[2048];
801 int len;
802 ASN1_TIME *notBefore, *notAfter;
803 PyObject *pnotBefore, *pnotAfter;
805 retval = PyDict_New();
806 if (retval == NULL)
807 return NULL;
809 peer = _create_tuple_for_X509_NAME(
810 X509_get_subject_name(certificate));
811 if (peer == NULL)
812 goto fail0;
813 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
814 Py_DECREF(peer);
815 goto fail0;
817 Py_DECREF(peer);
819 if (verbose) {
820 issuer = _create_tuple_for_X509_NAME(
821 X509_get_issuer_name(certificate));
822 if (issuer == NULL)
823 goto fail0;
824 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
825 Py_DECREF(issuer);
826 goto fail0;
828 Py_DECREF(issuer);
830 version = PyInt_FromLong(X509_get_version(certificate) + 1);
831 if (PyDict_SetItemString(retval, "version", version) < 0) {
832 Py_DECREF(version);
833 goto fail0;
835 Py_DECREF(version);
838 /* get a memory buffer */
839 biobuf = BIO_new(BIO_s_mem());
841 if (verbose) {
843 (void) BIO_reset(biobuf);
844 serialNumber = X509_get_serialNumber(certificate);
845 /* should not exceed 20 octets, 160 bits, so buf is big enough */
846 i2a_ASN1_INTEGER(biobuf, serialNumber);
847 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
848 if (len < 0) {
849 _setSSLError(NULL, 0, __FILE__, __LINE__);
850 goto fail1;
852 sn_obj = PyString_FromStringAndSize(buf, len);
853 if (sn_obj == NULL)
854 goto fail1;
855 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
856 Py_DECREF(sn_obj);
857 goto fail1;
859 Py_DECREF(sn_obj);
861 (void) BIO_reset(biobuf);
862 notBefore = X509_get_notBefore(certificate);
863 ASN1_TIME_print(biobuf, notBefore);
864 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
865 if (len < 0) {
866 _setSSLError(NULL, 0, __FILE__, __LINE__);
867 goto fail1;
869 pnotBefore = PyString_FromStringAndSize(buf, len);
870 if (pnotBefore == NULL)
871 goto fail1;
872 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
873 Py_DECREF(pnotBefore);
874 goto fail1;
876 Py_DECREF(pnotBefore);
879 (void) BIO_reset(biobuf);
880 notAfter = X509_get_notAfter(certificate);
881 ASN1_TIME_print(biobuf, notAfter);
882 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
883 if (len < 0) {
884 _setSSLError(NULL, 0, __FILE__, __LINE__);
885 goto fail1;
887 pnotAfter = PyString_FromStringAndSize(buf, len);
888 if (pnotAfter == NULL)
889 goto fail1;
890 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
891 Py_DECREF(pnotAfter);
892 goto fail1;
894 Py_DECREF(pnotAfter);
896 /* Now look for subjectAltName */
898 peer_alt_names = _get_peer_alt_names(certificate);
899 if (peer_alt_names == NULL)
900 goto fail1;
901 else if (peer_alt_names != Py_None) {
902 if (PyDict_SetItemString(retval, "subjectAltName",
903 peer_alt_names) < 0) {
904 Py_DECREF(peer_alt_names);
905 goto fail1;
907 Py_DECREF(peer_alt_names);
910 BIO_free(biobuf);
911 return retval;
913 fail1:
914 if (biobuf != NULL)
915 BIO_free(biobuf);
916 fail0:
917 Py_XDECREF(retval);
918 return NULL;
922 static PyObject *
923 PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
925 PyObject *retval = NULL;
926 char *filename = NULL;
927 X509 *x=NULL;
928 BIO *cert;
929 int verbose = 1;
931 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", &filename, &verbose))
932 return NULL;
934 if ((cert=BIO_new(BIO_s_file())) == NULL) {
935 PyErr_SetString(PySSLErrorObject, "Can't malloc memory to read file");
936 goto fail0;
939 if (BIO_read_filename(cert,filename) <= 0) {
940 PyErr_SetString(PySSLErrorObject, "Can't open file");
941 goto fail0;
944 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
945 if (x == NULL) {
946 PyErr_SetString(PySSLErrorObject, "Error decoding PEM-encoded file");
947 goto fail0;
950 retval = _decode_certificate(x, verbose);
952 fail0:
954 if (cert != NULL) BIO_free(cert);
955 return retval;
959 static PyObject *
960 PySSL_peercert(PySSLObject *self, PyObject *args)
962 PyObject *retval = NULL;
963 int len;
964 int verification;
965 PyObject *binary_mode = Py_None;
967 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
968 return NULL;
970 if (!self->peer_cert)
971 Py_RETURN_NONE;
973 if (PyObject_IsTrue(binary_mode)) {
974 /* return cert in DER-encoded format */
976 unsigned char *bytes_buf = NULL;
978 bytes_buf = NULL;
979 len = i2d_X509(self->peer_cert, &bytes_buf);
980 if (len < 0) {
981 PySSL_SetError(self, len, __FILE__, __LINE__);
982 return NULL;
984 retval = PyString_FromStringAndSize((const char *) bytes_buf, len);
985 OPENSSL_free(bytes_buf);
986 return retval;
988 } else {
990 verification = SSL_CTX_get_verify_mode(self->ctx);
991 if ((verification & SSL_VERIFY_PEER) == 0)
992 return PyDict_New();
993 else
994 return _decode_certificate (self->peer_cert, 0);
998 PyDoc_STRVAR(PySSL_peercert_doc,
999 "peer_certificate([der=False]) -> certificate\n\
1001 Returns the certificate for the peer. If no certificate was provided,\n\
1002 returns None. If a certificate was provided, but not validated, returns\n\
1003 an empty dictionary. Otherwise returns a dict containing information\n\
1004 about the peer certificate.\n\
1006 If the optional argument is True, returns a DER-encoded copy of the\n\
1007 peer certificate, or None if no certificate was provided. This will\n\
1008 return the certificate even if it wasn't validated.");
1010 static PyObject *PySSL_cipher (PySSLObject *self) {
1012 PyObject *retval, *v;
1013 SSL_CIPHER *current;
1014 char *cipher_name;
1015 char *cipher_protocol;
1017 if (self->ssl == NULL)
1018 return Py_None;
1019 current = SSL_get_current_cipher(self->ssl);
1020 if (current == NULL)
1021 return Py_None;
1023 retval = PyTuple_New(3);
1024 if (retval == NULL)
1025 return NULL;
1027 cipher_name = (char *) SSL_CIPHER_get_name(current);
1028 if (cipher_name == NULL) {
1029 PyTuple_SET_ITEM(retval, 0, Py_None);
1030 } else {
1031 v = PyString_FromString(cipher_name);
1032 if (v == NULL)
1033 goto fail0;
1034 PyTuple_SET_ITEM(retval, 0, v);
1036 cipher_protocol = SSL_CIPHER_get_version(current);
1037 if (cipher_protocol == NULL) {
1038 PyTuple_SET_ITEM(retval, 1, Py_None);
1039 } else {
1040 v = PyString_FromString(cipher_protocol);
1041 if (v == NULL)
1042 goto fail0;
1043 PyTuple_SET_ITEM(retval, 1, v);
1045 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1046 if (v == NULL)
1047 goto fail0;
1048 PyTuple_SET_ITEM(retval, 2, v);
1049 return retval;
1051 fail0:
1052 Py_DECREF(retval);
1053 return NULL;
1056 static void PySSL_dealloc(PySSLObject *self)
1058 if (self->peer_cert) /* Possible not to have one? */
1059 X509_free (self->peer_cert);
1060 if (self->ssl)
1061 SSL_free(self->ssl);
1062 if (self->ctx)
1063 SSL_CTX_free(self->ctx);
1064 Py_XDECREF(self->Socket);
1065 PyObject_Del(self);
1068 /* If the socket has a timeout, do a select()/poll() on the socket.
1069 The argument writing indicates the direction.
1070 Returns one of the possibilities in the timeout_state enum (above).
1073 static int
1074 check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
1076 fd_set fds;
1077 struct timeval tv;
1078 int rc;
1080 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1081 if (s->sock_timeout < 0.0)
1082 return SOCKET_IS_BLOCKING;
1083 else if (s->sock_timeout == 0.0)
1084 return SOCKET_IS_NONBLOCKING;
1086 /* Guard against closed socket */
1087 if (s->sock_fd < 0)
1088 return SOCKET_HAS_BEEN_CLOSED;
1090 /* Prefer poll, if available, since you can poll() any fd
1091 * which can't be done with select(). */
1092 #ifdef HAVE_POLL
1094 struct pollfd pollfd;
1095 int timeout;
1097 pollfd.fd = s->sock_fd;
1098 pollfd.events = writing ? POLLOUT : POLLIN;
1100 /* s->sock_timeout is in seconds, timeout in ms */
1101 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1102 PySSL_BEGIN_ALLOW_THREADS
1103 rc = poll(&pollfd, 1, timeout);
1104 PySSL_END_ALLOW_THREADS
1106 goto normal_return;
1108 #endif
1110 /* Guard against socket too large for select*/
1111 #ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
1112 if (s->sock_fd >= FD_SETSIZE)
1113 return SOCKET_TOO_LARGE_FOR_SELECT;
1114 #endif
1116 /* Construct the arguments to select */
1117 tv.tv_sec = (int)s->sock_timeout;
1118 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1119 FD_ZERO(&fds);
1120 FD_SET(s->sock_fd, &fds);
1122 /* See if the socket is ready */
1123 PySSL_BEGIN_ALLOW_THREADS
1124 if (writing)
1125 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1126 else
1127 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1128 PySSL_END_ALLOW_THREADS
1130 normal_return:
1131 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1132 (when we are able to write or when there's something to read) */
1133 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
1136 static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1138 char *data;
1139 int len;
1140 int count;
1141 int sockstate;
1142 int err;
1144 if (!PyArg_ParseTuple(args, "s#:write", &data, &count))
1145 return NULL;
1147 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1148 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1149 PyErr_SetString(PySSLErrorObject,
1150 "The write operation timed out");
1151 return NULL;
1152 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1153 PyErr_SetString(PySSLErrorObject,
1154 "Underlying socket has been closed.");
1155 return NULL;
1156 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1157 PyErr_SetString(PySSLErrorObject,
1158 "Underlying socket too large for select().");
1159 return NULL;
1161 do {
1162 err = 0;
1163 PySSL_BEGIN_ALLOW_THREADS
1164 len = SSL_write(self->ssl, data, count);
1165 err = SSL_get_error(self->ssl, len);
1166 PySSL_END_ALLOW_THREADS
1167 if(PyErr_CheckSignals()) {
1168 return NULL;
1170 if (err == SSL_ERROR_WANT_READ) {
1171 sockstate =
1172 check_socket_and_wait_for_timeout(self->Socket, 0);
1173 } else if (err == SSL_ERROR_WANT_WRITE) {
1174 sockstate =
1175 check_socket_and_wait_for_timeout(self->Socket, 1);
1176 } else {
1177 sockstate = SOCKET_OPERATION_OK;
1179 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1180 PyErr_SetString(PySSLErrorObject,
1181 "The write operation timed out");
1182 return NULL;
1183 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1184 PyErr_SetString(PySSLErrorObject,
1185 "Underlying socket has been closed.");
1186 return NULL;
1187 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1188 break;
1190 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1191 if (len > 0)
1192 return PyInt_FromLong(len);
1193 else
1194 return PySSL_SetError(self, len, __FILE__, __LINE__);
1197 PyDoc_STRVAR(PySSL_SSLwrite_doc,
1198 "write(s) -> len\n\
1200 Writes the string s into the SSL object. Returns the number\n\
1201 of bytes written.");
1203 static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1205 PyObject *buf;
1206 int count = 0;
1207 int len = 1024;
1208 int sockstate;
1209 int err;
1211 if (!PyArg_ParseTuple(args, "|i:read", &len))
1212 return NULL;
1214 if (!(buf = PyString_FromStringAndSize((char *) 0, len)))
1215 return NULL;
1217 /* first check if there are bytes ready to be read */
1218 PySSL_BEGIN_ALLOW_THREADS
1219 count = SSL_pending(self->ssl);
1220 PySSL_END_ALLOW_THREADS
1222 if (!count) {
1223 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1224 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1225 PyErr_SetString(PySSLErrorObject,
1226 "The read operation timed out");
1227 Py_DECREF(buf);
1228 return NULL;
1229 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1230 PyErr_SetString(PySSLErrorObject,
1231 "Underlying socket too large for select().");
1232 Py_DECREF(buf);
1233 return NULL;
1234 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1235 /* should contain a zero-length string */
1236 _PyString_Resize(&buf, 0);
1237 return buf;
1240 do {
1241 err = 0;
1242 PySSL_BEGIN_ALLOW_THREADS
1243 count = SSL_read(self->ssl, PyString_AsString(buf), len);
1244 err = SSL_get_error(self->ssl, count);
1245 PySSL_END_ALLOW_THREADS
1246 if(PyErr_CheckSignals()) {
1247 Py_DECREF(buf);
1248 return NULL;
1250 if (err == SSL_ERROR_WANT_READ) {
1251 sockstate =
1252 check_socket_and_wait_for_timeout(self->Socket, 0);
1253 } else if (err == SSL_ERROR_WANT_WRITE) {
1254 sockstate =
1255 check_socket_and_wait_for_timeout(self->Socket, 1);
1256 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1257 (SSL_get_shutdown(self->ssl) ==
1258 SSL_RECEIVED_SHUTDOWN))
1260 _PyString_Resize(&buf, 0);
1261 return buf;
1262 } else {
1263 sockstate = SOCKET_OPERATION_OK;
1265 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1266 PyErr_SetString(PySSLErrorObject,
1267 "The read operation timed out");
1268 Py_DECREF(buf);
1269 return NULL;
1270 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1271 break;
1273 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1274 if (count <= 0) {
1275 Py_DECREF(buf);
1276 return PySSL_SetError(self, count, __FILE__, __LINE__);
1278 if (count != len)
1279 _PyString_Resize(&buf, count);
1280 return buf;
1283 PyDoc_STRVAR(PySSL_SSLread_doc,
1284 "read([len]) -> string\n\
1286 Read up to len bytes from the SSL socket.");
1288 static PyMethodDef PySSLMethods[] = {
1289 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1290 PySSL_SSLwrite_doc},
1291 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1292 PySSL_SSLread_doc},
1293 {"server", (PyCFunction)PySSL_server, METH_NOARGS},
1294 {"issuer", (PyCFunction)PySSL_issuer, METH_NOARGS},
1295 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1296 PySSL_peercert_doc},
1297 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1298 {NULL, NULL}
1301 static PyObject *PySSL_getattr(PySSLObject *self, char *name)
1303 return Py_FindMethod(PySSLMethods, (PyObject *)self, name);
1306 static PyTypeObject PySSL_Type = {
1307 PyVarObject_HEAD_INIT(NULL, 0)
1308 "ssl.SSLContext", /*tp_name*/
1309 sizeof(PySSLObject), /*tp_basicsize*/
1310 0, /*tp_itemsize*/
1311 /* methods */
1312 (destructor)PySSL_dealloc, /*tp_dealloc*/
1313 0, /*tp_print*/
1314 (getattrfunc)PySSL_getattr, /*tp_getattr*/
1315 0, /*tp_setattr*/
1316 0, /*tp_compare*/
1317 0, /*tp_repr*/
1318 0, /*tp_as_number*/
1319 0, /*tp_as_sequence*/
1320 0, /*tp_as_mapping*/
1321 0, /*tp_hash*/
1324 #ifdef HAVE_OPENSSL_RAND
1326 /* helper routines for seeding the SSL PRNG */
1327 static PyObject *
1328 PySSL_RAND_add(PyObject *self, PyObject *args)
1330 char *buf;
1331 int len;
1332 double entropy;
1334 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
1335 return NULL;
1336 RAND_add(buf, len, entropy);
1337 Py_INCREF(Py_None);
1338 return Py_None;
1341 PyDoc_STRVAR(PySSL_RAND_add_doc,
1342 "RAND_add(string, entropy)\n\
1344 Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
1345 bound on the entropy contained in string. See RFC 1750.");
1347 static PyObject *
1348 PySSL_RAND_status(PyObject *self)
1350 return PyInt_FromLong(RAND_status());
1353 PyDoc_STRVAR(PySSL_RAND_status_doc,
1354 "RAND_status() -> 0 or 1\n\
1356 Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1357 It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1358 using the ssl() function.");
1360 static PyObject *
1361 PySSL_RAND_egd(PyObject *self, PyObject *arg)
1363 int bytes;
1365 if (!PyString_Check(arg))
1366 return PyErr_Format(PyExc_TypeError,
1367 "RAND_egd() expected string, found %s",
1368 Py_TYPE(arg)->tp_name);
1369 bytes = RAND_egd(PyString_AS_STRING(arg));
1370 if (bytes == -1) {
1371 PyErr_SetString(PySSLErrorObject,
1372 "EGD connection failed or EGD did not return "
1373 "enough data to seed the PRNG");
1374 return NULL;
1376 return PyInt_FromLong(bytes);
1379 PyDoc_STRVAR(PySSL_RAND_egd_doc,
1380 "RAND_egd(path) -> bytes\n\
1382 Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1383 Returns number of bytes read. Raises SSLError if connection to EGD\n\
1384 fails or if it does provide enough data to seed PRNG.");
1386 #endif
1388 /* List of functions exported by this module. */
1390 static PyMethodDef PySSL_methods[] = {
1391 {"sslwrap", PySSL_sslwrap,
1392 METH_VARARGS, ssl_doc},
1393 {"_test_decode_cert", PySSL_test_decode_certificate,
1394 METH_VARARGS},
1395 #ifdef HAVE_OPENSSL_RAND
1396 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1397 PySSL_RAND_add_doc},
1398 {"RAND_egd", PySSL_RAND_egd, METH_O,
1399 PySSL_RAND_egd_doc},
1400 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1401 PySSL_RAND_status_doc},
1402 #endif
1403 {NULL, NULL} /* Sentinel */
1407 #ifdef WITH_THREAD
1409 /* an implementation of OpenSSL threading operations in terms
1410 of the Python C thread library */
1412 static PyThread_type_lock *_ssl_locks = NULL;
1414 static unsigned long _ssl_thread_id_function (void) {
1415 return PyThread_get_thread_ident();
1418 static void _ssl_thread_locking_function (int mode, int n, const char *file, int line) {
1419 /* this function is needed to perform locking on shared data
1420 structures. (Note that OpenSSL uses a number of global data
1421 structures that will be implicitly shared whenever multiple threads
1422 use OpenSSL.) Multi-threaded applications will crash at random if
1423 it is not set.
1425 locking_function() must be able to handle up to CRYPTO_num_locks()
1426 different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and
1427 releases it otherwise.
1429 file and line are the file number of the function setting the
1430 lock. They can be useful for debugging.
1433 if ((_ssl_locks == NULL) ||
1434 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1435 return;
1437 if (mode & CRYPTO_LOCK) {
1438 PyThread_acquire_lock(_ssl_locks[n], 1);
1439 } else {
1440 PyThread_release_lock(_ssl_locks[n]);
1444 static int _setup_ssl_threads(void) {
1446 unsigned int i;
1448 if (_ssl_locks == NULL) {
1449 _ssl_locks_count = CRYPTO_num_locks();
1450 _ssl_locks = (PyThread_type_lock *)
1451 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1452 if (_ssl_locks == NULL)
1453 return 0;
1454 memset(_ssl_locks, 0, sizeof(PyThread_type_lock) * _ssl_locks_count);
1455 for (i = 0; i < _ssl_locks_count; i++) {
1456 _ssl_locks[i] = PyThread_allocate_lock();
1457 if (_ssl_locks[i] == NULL) {
1458 int j;
1459 for (j = 0; j < i; j++) {
1460 PyThread_free_lock(_ssl_locks[j]);
1462 free(_ssl_locks);
1463 return 0;
1466 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1467 CRYPTO_set_id_callback(_ssl_thread_id_function);
1469 return 1;
1472 #endif /* def HAVE_THREAD */
1474 PyDoc_STRVAR(module_doc,
1475 "Implementation module for SSL socket operations. See the socket module\n\
1476 for documentation.");
1478 PyMODINIT_FUNC
1479 init_ssl(void)
1481 PyObject *m, *d;
1483 Py_TYPE(&PySSL_Type) = &PyType_Type;
1485 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
1486 if (m == NULL)
1487 return;
1488 d = PyModule_GetDict(m);
1490 /* Load _socket module and its C API */
1491 if (PySocketModule_ImportModuleAndAPI())
1492 return;
1494 /* Init OpenSSL */
1495 SSL_load_error_strings();
1496 #ifdef WITH_THREAD
1497 /* note that this will start threading if not already started */
1498 if (!_setup_ssl_threads()) {
1499 return;
1501 #endif
1502 SSLeay_add_ssl_algorithms();
1504 /* Add symbols to module dict */
1505 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
1506 PySocketModule.error,
1507 NULL);
1508 if (PySSLErrorObject == NULL)
1509 return;
1510 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
1511 return;
1512 if (PyDict_SetItemString(d, "SSLType",
1513 (PyObject *)&PySSL_Type) != 0)
1514 return;
1515 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
1516 PY_SSL_ERROR_ZERO_RETURN);
1517 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
1518 PY_SSL_ERROR_WANT_READ);
1519 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
1520 PY_SSL_ERROR_WANT_WRITE);
1521 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
1522 PY_SSL_ERROR_WANT_X509_LOOKUP);
1523 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
1524 PY_SSL_ERROR_SYSCALL);
1525 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
1526 PY_SSL_ERROR_SSL);
1527 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1528 PY_SSL_ERROR_WANT_CONNECT);
1529 /* non ssl.h errorcodes */
1530 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1531 PY_SSL_ERROR_EOF);
1532 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1533 PY_SSL_ERROR_INVALID_ERROR_CODE);
1534 /* cert requirements */
1535 PyModule_AddIntConstant(m, "CERT_NONE",
1536 PY_SSL_CERT_NONE);
1537 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1538 PY_SSL_CERT_OPTIONAL);
1539 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1540 PY_SSL_CERT_REQUIRED);
1542 /* protocol versions */
1543 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1544 PY_SSL_VERSION_SSL2);
1545 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1546 PY_SSL_VERSION_SSL3);
1547 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1548 PY_SSL_VERSION_SSL23);
1549 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1550 PY_SSL_VERSION_TLS1);