Remove outdated include; this include was breaking OS X builds using
[python.git] / Modules / _ssl.c
blob643693eecb33abdd9f6de7e9d36067935a1d52ce
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 what about SSL_MODE_AUTO_RETRY?
16 #include "Python.h"
18 #ifdef WITH_THREAD
19 #include "pythread.h"
20 #define PySSL_BEGIN_ALLOW_THREADS { \
21 PyThreadState *_save = NULL; \
22 if (_ssl_locks_count>0) {_save = PyEval_SaveThread();}
23 #define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)};
24 #define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()};
25 #define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \
28 #else /* no WITH_THREAD */
30 #define PySSL_BEGIN_ALLOW_THREADS
31 #define PySSL_BLOCK_THREADS
32 #define PySSL_UNBLOCK_THREADS
33 #define PySSL_END_ALLOW_THREADS
35 #endif
37 enum py_ssl_error {
38 /* these mirror ssl.h */
39 PY_SSL_ERROR_NONE,
40 PY_SSL_ERROR_SSL,
41 PY_SSL_ERROR_WANT_READ,
42 PY_SSL_ERROR_WANT_WRITE,
43 PY_SSL_ERROR_WANT_X509_LOOKUP,
44 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
45 PY_SSL_ERROR_ZERO_RETURN,
46 PY_SSL_ERROR_WANT_CONNECT,
47 /* start of non ssl.h errorcodes */
48 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
49 PY_SSL_ERROR_INVALID_ERROR_CODE
52 enum py_ssl_server_or_client {
53 PY_SSL_CLIENT,
54 PY_SSL_SERVER
57 enum py_ssl_cert_requirements {
58 PY_SSL_CERT_NONE,
59 PY_SSL_CERT_OPTIONAL,
60 PY_SSL_CERT_REQUIRED
63 enum py_ssl_version {
64 PY_SSL_VERSION_SSL2,
65 PY_SSL_VERSION_SSL3,
66 PY_SSL_VERSION_SSL23,
67 PY_SSL_VERSION_TLS1,
70 /* Include symbols from _socket module */
71 #include "socketmodule.h"
73 #if defined(HAVE_POLL_H)
74 #include <poll.h>
75 #elif defined(HAVE_SYS_POLL_H)
76 #include <sys/poll.h>
77 #endif
79 /* Include OpenSSL header files */
80 #include "openssl/rsa.h"
81 #include "openssl/crypto.h"
82 #include "openssl/x509.h"
83 #include "openssl/x509v3.h"
84 #include "openssl/pem.h"
85 #include "openssl/ssl.h"
86 #include "openssl/err.h"
87 #include "openssl/rand.h"
89 /* SSL error object */
90 static PyObject *PySSLErrorObject;
92 #ifdef WITH_THREAD
94 /* serves as a flag to see whether we've initialized the SSL thread support. */
95 /* 0 means no, greater than 0 means yes */
97 static unsigned int _ssl_locks_count = 0;
99 #endif /* def WITH_THREAD */
101 /* SSL socket object */
103 #define X509_NAME_MAXLEN 256
105 /* RAND_* APIs got added to OpenSSL in 0.9.5 */
106 #if OPENSSL_VERSION_NUMBER >= 0x0090500fL
107 # define HAVE_OPENSSL_RAND 1
108 #else
109 # undef HAVE_OPENSSL_RAND
110 #endif
112 typedef struct {
113 PyObject_HEAD
114 PySocketSockObject *Socket; /* Socket on which we're layered */
115 SSL_CTX* ctx;
116 SSL* ssl;
117 X509* peer_cert;
118 char server[X509_NAME_MAXLEN];
119 char issuer[X509_NAME_MAXLEN];
121 } PySSLObject;
123 static PyTypeObject PySSL_Type;
124 static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args);
125 static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args);
126 static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
127 int writing);
128 static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args);
129 static PyObject *PySSL_cipher(PySSLObject *self);
131 #define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type)
133 typedef enum {
134 SOCKET_IS_NONBLOCKING,
135 SOCKET_IS_BLOCKING,
136 SOCKET_HAS_TIMED_OUT,
137 SOCKET_HAS_BEEN_CLOSED,
138 SOCKET_TOO_LARGE_FOR_SELECT,
139 SOCKET_OPERATION_OK
140 } timeout_state;
142 /* Wrap error strings with filename and line # */
143 #define STRINGIFY1(x) #x
144 #define STRINGIFY2(x) STRINGIFY1(x)
145 #define ERRSTR1(x,y,z) (x ":" y ": " z)
146 #define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
148 /* XXX It might be helpful to augment the error message generated
149 below with the name of the SSL function that generated the error.
150 I expect it's obvious most of the time.
153 static PyObject *
154 PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno)
156 PyObject *v;
157 char buf[2048];
158 char *errstr;
159 int err;
160 enum py_ssl_error p = PY_SSL_ERROR_NONE;
162 assert(ret <= 0);
164 if (obj->ssl != NULL) {
165 err = SSL_get_error(obj->ssl, ret);
167 switch (err) {
168 case SSL_ERROR_ZERO_RETURN:
169 errstr = "TLS/SSL connection has been closed";
170 p = PY_SSL_ERROR_ZERO_RETURN;
171 break;
172 case SSL_ERROR_WANT_READ:
173 errstr = "The operation did not complete (read)";
174 p = PY_SSL_ERROR_WANT_READ;
175 break;
176 case SSL_ERROR_WANT_WRITE:
177 p = PY_SSL_ERROR_WANT_WRITE;
178 errstr = "The operation did not complete (write)";
179 break;
180 case SSL_ERROR_WANT_X509_LOOKUP:
181 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
182 errstr =
183 "The operation did not complete (X509 lookup)";
184 break;
185 case SSL_ERROR_WANT_CONNECT:
186 p = PY_SSL_ERROR_WANT_CONNECT;
187 errstr = "The operation did not complete (connect)";
188 break;
189 case SSL_ERROR_SYSCALL:
191 unsigned long e = ERR_get_error();
192 if (e == 0) {
193 if (ret == 0 || !obj->Socket) {
194 p = PY_SSL_ERROR_EOF;
195 errstr =
196 "EOF occurred in violation of protocol";
197 } else if (ret == -1) {
198 /* underlying BIO reported an I/O error */
199 return obj->Socket->errorhandler();
200 } else { /* possible? */
201 p = PY_SSL_ERROR_SYSCALL;
202 errstr = "Some I/O error occurred";
204 } else {
205 p = PY_SSL_ERROR_SYSCALL;
206 /* XXX Protected by global interpreter lock */
207 errstr = ERR_error_string(e, NULL);
209 break;
211 case SSL_ERROR_SSL:
213 unsigned long e = ERR_get_error();
214 p = PY_SSL_ERROR_SSL;
215 if (e != 0)
216 /* XXX Protected by global interpreter lock */
217 errstr = ERR_error_string(e, NULL);
218 else { /* possible? */
219 errstr =
220 "A failure in the SSL library occurred";
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 v = Py_BuildValue("(is)", p, buf);
233 if (v != NULL) {
234 PyErr_SetObject(PySSLErrorObject, v);
235 Py_DECREF(v);
237 return NULL;
240 static PyObject *
241 _setSSLError (char *errstr, int errcode, char *filename, int lineno) {
243 char buf[2048];
244 PyObject *v;
246 if (errstr == NULL) {
247 errcode = ERR_peek_last_error();
248 errstr = ERR_error_string(errcode, NULL);
250 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
251 v = Py_BuildValue("(is)", errcode, buf);
252 if (v != NULL) {
253 PyErr_SetObject(PySSLErrorObject, v);
254 Py_DECREF(v);
256 return NULL;
259 static PySSLObject *
260 newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file,
261 enum py_ssl_server_or_client socket_type,
262 enum py_ssl_cert_requirements certreq,
263 enum py_ssl_version proto_version,
264 char *cacerts_file)
266 PySSLObject *self;
267 char *errstr = NULL;
268 int ret;
269 int verification_mode;
271 self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */
272 if (self == NULL)
273 return NULL;
274 memset(self->server, '\0', sizeof(char) * X509_NAME_MAXLEN);
275 memset(self->issuer, '\0', sizeof(char) * X509_NAME_MAXLEN);
276 self->peer_cert = NULL;
277 self->ssl = NULL;
278 self->ctx = NULL;
279 self->Socket = NULL;
281 /* Make sure the SSL error state is initialized */
282 (void) ERR_get_state();
283 ERR_clear_error();
285 if ((key_file && !cert_file) || (!key_file && cert_file)) {
286 errstr = ERRSTR("Both the key & certificate files "
287 "must be specified");
288 goto fail;
291 if ((socket_type == PY_SSL_SERVER) &&
292 ((key_file == NULL) || (cert_file == NULL))) {
293 errstr = ERRSTR("Both the key & certificate files "
294 "must be specified for server-side operation");
295 goto fail;
298 PySSL_BEGIN_ALLOW_THREADS
299 if (proto_version == PY_SSL_VERSION_TLS1)
300 self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */
301 else if (proto_version == PY_SSL_VERSION_SSL3)
302 self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */
303 else if (proto_version == PY_SSL_VERSION_SSL2)
304 self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */
305 else if (proto_version == PY_SSL_VERSION_SSL23)
306 self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
307 PySSL_END_ALLOW_THREADS
309 if (self->ctx == NULL) {
310 errstr = ERRSTR("Invalid SSL protocol variant specified.");
311 goto fail;
314 if (certreq != PY_SSL_CERT_NONE) {
315 if (cacerts_file == NULL) {
316 errstr = ERRSTR("No root certificates specified for "
317 "verification of other-side certificates.");
318 goto fail;
319 } else {
320 PySSL_BEGIN_ALLOW_THREADS
321 ret = SSL_CTX_load_verify_locations(self->ctx,
322 cacerts_file,
323 NULL);
324 PySSL_END_ALLOW_THREADS
325 if (ret != 1) {
326 _setSSLError(NULL, 0, __FILE__, __LINE__);
327 goto fail;
331 if (key_file) {
332 PySSL_BEGIN_ALLOW_THREADS
333 ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
334 SSL_FILETYPE_PEM);
335 PySSL_END_ALLOW_THREADS
336 if (ret != 1) {
337 _setSSLError(NULL, ret, __FILE__, __LINE__);
338 goto fail;
341 PySSL_BEGIN_ALLOW_THREADS
342 ret = SSL_CTX_use_certificate_chain_file(self->ctx,
343 cert_file);
344 PySSL_END_ALLOW_THREADS
345 if (ret != 1) {
347 fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
348 ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
350 if (ERR_peek_last_error() != 0) {
351 _setSSLError(NULL, ret, __FILE__, __LINE__);
352 goto fail;
357 /* ssl compatibility */
358 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
360 verification_mode = SSL_VERIFY_NONE;
361 if (certreq == PY_SSL_CERT_OPTIONAL)
362 verification_mode = SSL_VERIFY_PEER;
363 else if (certreq == PY_SSL_CERT_REQUIRED)
364 verification_mode = (SSL_VERIFY_PEER |
365 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
366 SSL_CTX_set_verify(self->ctx, verification_mode,
367 NULL); /* set verify lvl */
369 PySSL_BEGIN_ALLOW_THREADS
370 self->ssl = SSL_new(self->ctx); /* New ssl struct */
371 PySSL_END_ALLOW_THREADS
372 SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */
374 /* If the socket is in non-blocking mode or timeout mode, set the BIO
375 * to non-blocking mode (blocking is the default)
377 if (Sock->sock_timeout >= 0.0) {
378 /* Set both the read and write BIO's to non-blocking mode */
379 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
380 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
383 PySSL_BEGIN_ALLOW_THREADS
384 if (socket_type == PY_SSL_CLIENT)
385 SSL_set_connect_state(self->ssl);
386 else
387 SSL_set_accept_state(self->ssl);
388 PySSL_END_ALLOW_THREADS
390 self->Socket = Sock;
391 Py_INCREF(self->Socket);
392 return self;
393 fail:
394 if (errstr)
395 PyErr_SetString(PySSLErrorObject, errstr);
396 Py_DECREF(self);
397 return NULL;
400 static PyObject *
401 PySSL_sslwrap(PyObject *self, PyObject *args)
403 PySocketSockObject *Sock;
404 int server_side = 0;
405 int verification_mode = PY_SSL_CERT_NONE;
406 int protocol = PY_SSL_VERSION_SSL23;
407 char *key_file = NULL;
408 char *cert_file = NULL;
409 char *cacerts_file = NULL;
411 if (!PyArg_ParseTuple(args, "O!i|zziiz:sslwrap",
412 PySocketModule.Sock_Type,
413 &Sock,
414 &server_side,
415 &key_file, &cert_file,
416 &verification_mode, &protocol,
417 &cacerts_file))
418 return NULL;
421 fprintf(stderr,
422 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
423 "protocol %d, certs %p\n",
424 server_side, key_file, cert_file, verification_mode,
425 protocol, cacerts_file);
428 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
429 server_side, verification_mode,
430 protocol, cacerts_file);
433 PyDoc_STRVAR(ssl_doc,
434 "sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
435 " cacertsfile]) -> sslobject");
437 /* SSL object methods */
439 static PyObject *PySSL_SSLdo_handshake(PySSLObject *self)
441 int ret;
442 int err;
443 int sockstate;
445 /* Actually negotiate SSL connection */
446 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
447 sockstate = 0;
448 do {
449 PySSL_BEGIN_ALLOW_THREADS
450 ret = SSL_do_handshake(self->ssl);
451 err = SSL_get_error(self->ssl, ret);
452 PySSL_END_ALLOW_THREADS
453 if(PyErr_CheckSignals()) {
454 return NULL;
456 if (err == SSL_ERROR_WANT_READ) {
457 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
458 } else if (err == SSL_ERROR_WANT_WRITE) {
459 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
460 } else {
461 sockstate = SOCKET_OPERATION_OK;
463 if (sockstate == SOCKET_HAS_TIMED_OUT) {
464 PyErr_SetString(PySSLErrorObject,
465 ERRSTR("The handshake operation timed out"));
466 return NULL;
467 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
468 PyErr_SetString(PySSLErrorObject,
469 ERRSTR("Underlying socket has been closed."));
470 return NULL;
471 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
472 PyErr_SetString(PySSLErrorObject,
473 ERRSTR("Underlying socket too large for select()."));
474 return NULL;
475 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
476 break;
478 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
479 if (ret < 1)
480 return PySSL_SetError(self, ret, __FILE__, __LINE__);
481 self->ssl->debug = 1;
483 if (self->peer_cert)
484 X509_free (self->peer_cert);
485 PySSL_BEGIN_ALLOW_THREADS
486 if ((self->peer_cert = SSL_get_peer_certificate(self->ssl))) {
487 X509_NAME_oneline(X509_get_subject_name(self->peer_cert),
488 self->server, X509_NAME_MAXLEN);
489 X509_NAME_oneline(X509_get_issuer_name(self->peer_cert),
490 self->issuer, X509_NAME_MAXLEN);
492 PySSL_END_ALLOW_THREADS
494 Py_INCREF(Py_None);
495 return Py_None;
498 static PyObject *
499 PySSL_server(PySSLObject *self)
501 return PyString_FromString(self->server);
504 static PyObject *
505 PySSL_issuer(PySSLObject *self)
507 return PyString_FromString(self->issuer);
510 static PyObject *
511 _create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
513 char namebuf[X509_NAME_MAXLEN];
514 int buflen;
515 PyObject *name_obj;
516 PyObject *value_obj;
517 PyObject *attr;
518 unsigned char *valuebuf = NULL;
520 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
521 if (buflen < 0) {
522 _setSSLError(NULL, 0, __FILE__, __LINE__);
523 goto fail;
525 name_obj = PyString_FromStringAndSize(namebuf, buflen);
526 if (name_obj == NULL)
527 goto fail;
529 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
530 if (buflen < 0) {
531 _setSSLError(NULL, 0, __FILE__, __LINE__);
532 Py_DECREF(name_obj);
533 goto fail;
535 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
536 buflen, "strict");
537 OPENSSL_free(valuebuf);
538 if (value_obj == NULL) {
539 Py_DECREF(name_obj);
540 goto fail;
542 attr = PyTuple_New(2);
543 if (attr == NULL) {
544 Py_DECREF(name_obj);
545 Py_DECREF(value_obj);
546 goto fail;
548 PyTuple_SET_ITEM(attr, 0, name_obj);
549 PyTuple_SET_ITEM(attr, 1, value_obj);
550 return attr;
552 fail:
553 return NULL;
556 static PyObject *
557 _create_tuple_for_X509_NAME (X509_NAME *xname)
559 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
560 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
561 PyObject *rdnt;
562 PyObject *attr = NULL; /* tuple to hold an attribute */
563 int entry_count = X509_NAME_entry_count(xname);
564 X509_NAME_ENTRY *entry;
565 ASN1_OBJECT *name;
566 ASN1_STRING *value;
567 int index_counter;
568 int rdn_level = -1;
569 int retcode;
571 dn = PyList_New(0);
572 if (dn == NULL)
573 return NULL;
574 /* now create another tuple to hold the top-level RDN */
575 rdn = PyList_New(0);
576 if (rdn == NULL)
577 goto fail0;
579 for (index_counter = 0;
580 index_counter < entry_count;
581 index_counter++)
583 entry = X509_NAME_get_entry(xname, index_counter);
585 /* check to see if we've gotten to a new RDN */
586 if (rdn_level >= 0) {
587 if (rdn_level != entry->set) {
588 /* yes, new RDN */
589 /* add old RDN to DN */
590 rdnt = PyList_AsTuple(rdn);
591 Py_DECREF(rdn);
592 if (rdnt == NULL)
593 goto fail0;
594 retcode = PyList_Append(dn, rdnt);
595 Py_DECREF(rdnt);
596 if (retcode < 0)
597 goto fail0;
598 /* create new RDN */
599 rdn = PyList_New(0);
600 if (rdn == NULL)
601 goto fail0;
604 rdn_level = entry->set;
606 /* now add this attribute to the current RDN */
607 name = X509_NAME_ENTRY_get_object(entry);
608 value = X509_NAME_ENTRY_get_data(entry);
609 attr = _create_tuple_for_attribute(name, value);
611 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
612 entry->set,
613 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
614 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
616 if (attr == NULL)
617 goto fail1;
618 retcode = PyList_Append(rdn, attr);
619 Py_DECREF(attr);
620 if (retcode < 0)
621 goto fail1;
623 /* now, there's typically a dangling RDN */
624 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
625 rdnt = PyList_AsTuple(rdn);
626 Py_DECREF(rdn);
627 if (rdnt == NULL)
628 goto fail0;
629 retcode = PyList_Append(dn, rdnt);
630 Py_DECREF(rdnt);
631 if (retcode < 0)
632 goto fail0;
635 /* convert list to tuple */
636 rdnt = PyList_AsTuple(dn);
637 Py_DECREF(dn);
638 if (rdnt == NULL)
639 return NULL;
640 return rdnt;
642 fail1:
643 Py_XDECREF(rdn);
645 fail0:
646 Py_XDECREF(dn);
647 return NULL;
650 static PyObject *
651 _get_peer_alt_names (X509 *certificate) {
653 /* this code follows the procedure outlined in
654 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
655 function to extract the STACK_OF(GENERAL_NAME),
656 then iterates through the stack to add the
657 names. */
659 int i, j;
660 PyObject *peer_alt_names = Py_None;
661 PyObject *v, *t;
662 X509_EXTENSION *ext = NULL;
663 GENERAL_NAMES *names = NULL;
664 GENERAL_NAME *name;
665 X509V3_EXT_METHOD *method;
666 BIO *biobuf = NULL;
667 char buf[2048];
668 char *vptr;
669 int len;
670 unsigned char *p;
672 if (certificate == NULL)
673 return peer_alt_names;
675 /* get a memory buffer */
676 biobuf = BIO_new(BIO_s_mem());
678 i = 0;
679 while ((i = X509_get_ext_by_NID(
680 certificate, NID_subject_alt_name, i)) >= 0) {
682 if (peer_alt_names == Py_None) {
683 peer_alt_names = PyList_New(0);
684 if (peer_alt_names == NULL)
685 goto fail;
688 /* now decode the altName */
689 ext = X509_get_ext(certificate, i);
690 if(!(method = X509V3_EXT_get(ext))) {
691 PyErr_SetString(PySSLErrorObject,
692 ERRSTR("No method for internalizing subjectAltName!"));
693 goto fail;
696 p = ext->value->data;
697 if (method->it)
698 names = (GENERAL_NAMES*) (ASN1_item_d2i(NULL,
700 ext->value->length,
701 ASN1_ITEM_ptr(method->it)));
702 else
703 names = (GENERAL_NAMES*) (method->d2i(NULL,
705 ext->value->length));
707 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
709 /* get a rendering of each name in the set of names */
711 name = sk_GENERAL_NAME_value(names, j);
712 if (name->type == GEN_DIRNAME) {
714 /* we special-case DirName as a tuple of tuples of attributes */
716 t = PyTuple_New(2);
717 if (t == NULL) {
718 goto fail;
721 v = PyString_FromString("DirName");
722 if (v == NULL) {
723 Py_DECREF(t);
724 goto fail;
726 PyTuple_SET_ITEM(t, 0, v);
728 v = _create_tuple_for_X509_NAME (name->d.dirn);
729 if (v == NULL) {
730 Py_DECREF(t);
731 goto fail;
733 PyTuple_SET_ITEM(t, 1, v);
735 } else {
737 /* for everything else, we use the OpenSSL print form */
739 (void) BIO_reset(biobuf);
740 GENERAL_NAME_print(biobuf, name);
741 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
742 if (len < 0) {
743 _setSSLError(NULL, 0, __FILE__, __LINE__);
744 goto fail;
746 vptr = strchr(buf, ':');
747 if (vptr == NULL)
748 goto fail;
749 t = PyTuple_New(2);
750 if (t == NULL)
751 goto fail;
752 v = PyString_FromStringAndSize(buf, (vptr - buf));
753 if (v == NULL) {
754 Py_DECREF(t);
755 goto fail;
757 PyTuple_SET_ITEM(t, 0, v);
758 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
759 if (v == NULL) {
760 Py_DECREF(t);
761 goto fail;
763 PyTuple_SET_ITEM(t, 1, v);
766 /* and add that rendering to the list */
768 if (PyList_Append(peer_alt_names, t) < 0) {
769 Py_DECREF(t);
770 goto fail;
772 Py_DECREF(t);
775 BIO_free(biobuf);
776 if (peer_alt_names != Py_None) {
777 v = PyList_AsTuple(peer_alt_names);
778 Py_DECREF(peer_alt_names);
779 return v;
780 } else {
781 return peer_alt_names;
785 fail:
786 if (biobuf != NULL)
787 BIO_free(biobuf);
789 if (peer_alt_names != Py_None) {
790 Py_XDECREF(peer_alt_names);
793 return NULL;
796 static PyObject *
797 _decode_certificate (X509 *certificate, int verbose) {
799 PyObject *retval = NULL;
800 BIO *biobuf = NULL;
801 PyObject *peer;
802 PyObject *peer_alt_names = NULL;
803 PyObject *issuer;
804 PyObject *version;
805 PyObject *sn_obj;
806 ASN1_INTEGER *serialNumber;
807 char buf[2048];
808 int len;
809 ASN1_TIME *notBefore, *notAfter;
810 PyObject *pnotBefore, *pnotAfter;
812 retval = PyDict_New();
813 if (retval == NULL)
814 return NULL;
816 peer = _create_tuple_for_X509_NAME(
817 X509_get_subject_name(certificate));
818 if (peer == NULL)
819 goto fail0;
820 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
821 Py_DECREF(peer);
822 goto fail0;
824 Py_DECREF(peer);
826 if (verbose) {
827 issuer = _create_tuple_for_X509_NAME(
828 X509_get_issuer_name(certificate));
829 if (issuer == NULL)
830 goto fail0;
831 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
832 Py_DECREF(issuer);
833 goto fail0;
835 Py_DECREF(issuer);
837 version = PyInt_FromLong(X509_get_version(certificate) + 1);
838 if (PyDict_SetItemString(retval, "version", version) < 0) {
839 Py_DECREF(version);
840 goto fail0;
842 Py_DECREF(version);
845 /* get a memory buffer */
846 biobuf = BIO_new(BIO_s_mem());
848 if (verbose) {
850 (void) BIO_reset(biobuf);
851 serialNumber = X509_get_serialNumber(certificate);
852 /* should not exceed 20 octets, 160 bits, so buf is big enough */
853 i2a_ASN1_INTEGER(biobuf, serialNumber);
854 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
855 if (len < 0) {
856 _setSSLError(NULL, 0, __FILE__, __LINE__);
857 goto fail1;
859 sn_obj = PyString_FromStringAndSize(buf, len);
860 if (sn_obj == NULL)
861 goto fail1;
862 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
863 Py_DECREF(sn_obj);
864 goto fail1;
866 Py_DECREF(sn_obj);
868 (void) BIO_reset(biobuf);
869 notBefore = X509_get_notBefore(certificate);
870 ASN1_TIME_print(biobuf, notBefore);
871 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
872 if (len < 0) {
873 _setSSLError(NULL, 0, __FILE__, __LINE__);
874 goto fail1;
876 pnotBefore = PyString_FromStringAndSize(buf, len);
877 if (pnotBefore == NULL)
878 goto fail1;
879 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
880 Py_DECREF(pnotBefore);
881 goto fail1;
883 Py_DECREF(pnotBefore);
886 (void) BIO_reset(biobuf);
887 notAfter = X509_get_notAfter(certificate);
888 ASN1_TIME_print(biobuf, notAfter);
889 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
890 if (len < 0) {
891 _setSSLError(NULL, 0, __FILE__, __LINE__);
892 goto fail1;
894 pnotAfter = PyString_FromStringAndSize(buf, len);
895 if (pnotAfter == NULL)
896 goto fail1;
897 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
898 Py_DECREF(pnotAfter);
899 goto fail1;
901 Py_DECREF(pnotAfter);
903 /* Now look for subjectAltName */
905 peer_alt_names = _get_peer_alt_names(certificate);
906 if (peer_alt_names == NULL)
907 goto fail1;
908 else if (peer_alt_names != Py_None) {
909 if (PyDict_SetItemString(retval, "subjectAltName",
910 peer_alt_names) < 0) {
911 Py_DECREF(peer_alt_names);
912 goto fail1;
914 Py_DECREF(peer_alt_names);
917 BIO_free(biobuf);
918 return retval;
920 fail1:
921 if (biobuf != NULL)
922 BIO_free(biobuf);
923 fail0:
924 Py_XDECREF(retval);
925 return NULL;
929 static PyObject *
930 PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
932 PyObject *retval = NULL;
933 char *filename = NULL;
934 X509 *x=NULL;
935 BIO *cert;
936 int verbose = 1;
938 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", &filename, &verbose))
939 return NULL;
941 if ((cert=BIO_new(BIO_s_file())) == NULL) {
942 PyErr_SetString(PySSLErrorObject, "Can't malloc memory to read file");
943 goto fail0;
946 if (BIO_read_filename(cert,filename) <= 0) {
947 PyErr_SetString(PySSLErrorObject, "Can't open file");
948 goto fail0;
951 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
952 if (x == NULL) {
953 PyErr_SetString(PySSLErrorObject, "Error decoding PEM-encoded file");
954 goto fail0;
957 retval = _decode_certificate(x, verbose);
959 fail0:
961 if (cert != NULL) BIO_free(cert);
962 return retval;
966 static PyObject *
967 PySSL_peercert(PySSLObject *self, PyObject *args)
969 PyObject *retval = NULL;
970 int len;
971 int verification;
972 PyObject *binary_mode = Py_None;
974 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
975 return NULL;
977 if (!self->peer_cert)
978 Py_RETURN_NONE;
980 if (PyObject_IsTrue(binary_mode)) {
981 /* return cert in DER-encoded format */
983 unsigned char *bytes_buf = NULL;
985 bytes_buf = NULL;
986 len = i2d_X509(self->peer_cert, &bytes_buf);
987 if (len < 0) {
988 PySSL_SetError(self, len, __FILE__, __LINE__);
989 return NULL;
991 retval = PyString_FromStringAndSize((const char *) bytes_buf, len);
992 OPENSSL_free(bytes_buf);
993 return retval;
995 } else {
997 verification = SSL_CTX_get_verify_mode(self->ctx);
998 if ((verification & SSL_VERIFY_PEER) == 0)
999 return PyDict_New();
1000 else
1001 return _decode_certificate (self->peer_cert, 0);
1005 PyDoc_STRVAR(PySSL_peercert_doc,
1006 "peer_certificate([der=False]) -> certificate\n\
1008 Returns the certificate for the peer. If no certificate was provided,\n\
1009 returns None. If a certificate was provided, but not validated, returns\n\
1010 an empty dictionary. Otherwise returns a dict containing information\n\
1011 about the peer certificate.\n\
1013 If the optional argument is True, returns a DER-encoded copy of the\n\
1014 peer certificate, or None if no certificate was provided. This will\n\
1015 return the certificate even if it wasn't validated.");
1017 static PyObject *PySSL_cipher (PySSLObject *self) {
1019 PyObject *retval, *v;
1020 SSL_CIPHER *current;
1021 char *cipher_name;
1022 char *cipher_protocol;
1024 if (self->ssl == NULL)
1025 return Py_None;
1026 current = SSL_get_current_cipher(self->ssl);
1027 if (current == NULL)
1028 return Py_None;
1030 retval = PyTuple_New(3);
1031 if (retval == NULL)
1032 return NULL;
1034 cipher_name = (char *) SSL_CIPHER_get_name(current);
1035 if (cipher_name == NULL) {
1036 PyTuple_SET_ITEM(retval, 0, Py_None);
1037 } else {
1038 v = PyString_FromString(cipher_name);
1039 if (v == NULL)
1040 goto fail0;
1041 PyTuple_SET_ITEM(retval, 0, v);
1043 cipher_protocol = SSL_CIPHER_get_version(current);
1044 if (cipher_protocol == NULL) {
1045 PyTuple_SET_ITEM(retval, 1, Py_None);
1046 } else {
1047 v = PyString_FromString(cipher_protocol);
1048 if (v == NULL)
1049 goto fail0;
1050 PyTuple_SET_ITEM(retval, 1, v);
1052 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1053 if (v == NULL)
1054 goto fail0;
1055 PyTuple_SET_ITEM(retval, 2, v);
1056 return retval;
1058 fail0:
1059 Py_DECREF(retval);
1060 return NULL;
1063 static void PySSL_dealloc(PySSLObject *self)
1065 if (self->peer_cert) /* Possible not to have one? */
1066 X509_free (self->peer_cert);
1067 if (self->ssl)
1068 SSL_free(self->ssl);
1069 if (self->ctx)
1070 SSL_CTX_free(self->ctx);
1071 Py_XDECREF(self->Socket);
1072 PyObject_Del(self);
1075 /* If the socket has a timeout, do a select()/poll() on the socket.
1076 The argument writing indicates the direction.
1077 Returns one of the possibilities in the timeout_state enum (above).
1080 static int
1081 check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
1083 fd_set fds;
1084 struct timeval tv;
1085 int rc;
1087 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1088 if (s->sock_timeout < 0.0)
1089 return SOCKET_IS_BLOCKING;
1090 else if (s->sock_timeout == 0.0)
1091 return SOCKET_IS_NONBLOCKING;
1093 /* Guard against closed socket */
1094 if (s->sock_fd < 0)
1095 return SOCKET_HAS_BEEN_CLOSED;
1097 /* Prefer poll, if available, since you can poll() any fd
1098 * which can't be done with select(). */
1099 #ifdef HAVE_POLL
1101 struct pollfd pollfd;
1102 int timeout;
1104 pollfd.fd = s->sock_fd;
1105 pollfd.events = writing ? POLLOUT : POLLIN;
1107 /* s->sock_timeout is in seconds, timeout in ms */
1108 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1109 PySSL_BEGIN_ALLOW_THREADS
1110 rc = poll(&pollfd, 1, timeout);
1111 PySSL_END_ALLOW_THREADS
1113 goto normal_return;
1115 #endif
1117 /* Guard against socket too large for select*/
1118 #ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
1119 if (s->sock_fd >= FD_SETSIZE)
1120 return SOCKET_TOO_LARGE_FOR_SELECT;
1121 #endif
1123 /* Construct the arguments to select */
1124 tv.tv_sec = (int)s->sock_timeout;
1125 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1126 FD_ZERO(&fds);
1127 FD_SET(s->sock_fd, &fds);
1129 /* See if the socket is ready */
1130 PySSL_BEGIN_ALLOW_THREADS
1131 if (writing)
1132 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1133 else
1134 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1135 PySSL_END_ALLOW_THREADS
1137 #ifdef HAVE_POLL
1138 normal_return:
1139 #endif
1140 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1141 (when we are able to write or when there's something to read) */
1142 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
1145 static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1147 char *data;
1148 int len;
1149 int count;
1150 int sockstate;
1151 int err;
1152 int nonblocking;
1154 if (!PyArg_ParseTuple(args, "s#:write", &data, &count))
1155 return NULL;
1157 /* just in case the blocking state of the socket has been changed */
1158 nonblocking = (self->Socket->sock_timeout >= 0.0);
1159 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1160 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1162 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1163 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1164 PyErr_SetString(PySSLErrorObject,
1165 "The write operation timed out");
1166 return NULL;
1167 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1168 PyErr_SetString(PySSLErrorObject,
1169 "Underlying socket has been closed.");
1170 return NULL;
1171 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1172 PyErr_SetString(PySSLErrorObject,
1173 "Underlying socket too large for select().");
1174 return NULL;
1176 do {
1177 err = 0;
1178 PySSL_BEGIN_ALLOW_THREADS
1179 len = SSL_write(self->ssl, data, count);
1180 err = SSL_get_error(self->ssl, len);
1181 PySSL_END_ALLOW_THREADS
1182 if(PyErr_CheckSignals()) {
1183 return NULL;
1185 if (err == SSL_ERROR_WANT_READ) {
1186 sockstate =
1187 check_socket_and_wait_for_timeout(self->Socket, 0);
1188 } else if (err == SSL_ERROR_WANT_WRITE) {
1189 sockstate =
1190 check_socket_and_wait_for_timeout(self->Socket, 1);
1191 } else {
1192 sockstate = SOCKET_OPERATION_OK;
1194 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1195 PyErr_SetString(PySSLErrorObject,
1196 "The write operation timed out");
1197 return NULL;
1198 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1199 PyErr_SetString(PySSLErrorObject,
1200 "Underlying socket has been closed.");
1201 return NULL;
1202 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1203 break;
1205 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1206 if (len > 0)
1207 return PyInt_FromLong(len);
1208 else
1209 return PySSL_SetError(self, len, __FILE__, __LINE__);
1212 PyDoc_STRVAR(PySSL_SSLwrite_doc,
1213 "write(s) -> len\n\
1215 Writes the string s into the SSL object. Returns the number\n\
1216 of bytes written.");
1218 static PyObject *PySSL_SSLpending(PySSLObject *self)
1220 int count = 0;
1222 PySSL_BEGIN_ALLOW_THREADS
1223 count = SSL_pending(self->ssl);
1224 PySSL_END_ALLOW_THREADS
1225 if (count < 0)
1226 return PySSL_SetError(self, count, __FILE__, __LINE__);
1227 else
1228 return PyInt_FromLong(count);
1231 PyDoc_STRVAR(PySSL_SSLpending_doc,
1232 "pending() -> count\n\
1234 Returns the number of already decrypted bytes available for read,\n\
1235 pending on the connection.\n");
1237 static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1239 PyObject *buf;
1240 int count = 0;
1241 int len = 1024;
1242 int sockstate;
1243 int err;
1244 int nonblocking;
1246 if (!PyArg_ParseTuple(args, "|i:read", &len))
1247 return NULL;
1249 if (!(buf = PyString_FromStringAndSize((char *) 0, len)))
1250 return NULL;
1252 /* just in case the blocking state of the socket has been changed */
1253 nonblocking = (self->Socket->sock_timeout >= 0.0);
1254 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1255 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1257 /* first check if there are bytes ready to be read */
1258 PySSL_BEGIN_ALLOW_THREADS
1259 count = SSL_pending(self->ssl);
1260 PySSL_END_ALLOW_THREADS
1262 if (!count) {
1263 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1264 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1265 PyErr_SetString(PySSLErrorObject,
1266 "The read operation timed out");
1267 Py_DECREF(buf);
1268 return NULL;
1269 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1270 PyErr_SetString(PySSLErrorObject,
1271 "Underlying socket too large for select().");
1272 Py_DECREF(buf);
1273 return NULL;
1274 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1275 if (SSL_get_shutdown(self->ssl) !=
1276 SSL_RECEIVED_SHUTDOWN)
1278 Py_DECREF(buf);
1279 PyErr_SetString(PySSLErrorObject,
1280 "Socket closed without SSL shutdown handshake");
1281 return NULL;
1282 } else {
1283 /* should contain a zero-length string */
1284 _PyString_Resize(&buf, 0);
1285 return buf;
1289 do {
1290 err = 0;
1291 PySSL_BEGIN_ALLOW_THREADS
1292 count = SSL_read(self->ssl, PyString_AsString(buf), len);
1293 err = SSL_get_error(self->ssl, count);
1294 PySSL_END_ALLOW_THREADS
1295 if(PyErr_CheckSignals()) {
1296 Py_DECREF(buf);
1297 return NULL;
1299 if (err == SSL_ERROR_WANT_READ) {
1300 sockstate =
1301 check_socket_and_wait_for_timeout(self->Socket, 0);
1302 } else if (err == SSL_ERROR_WANT_WRITE) {
1303 sockstate =
1304 check_socket_and_wait_for_timeout(self->Socket, 1);
1305 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1306 (SSL_get_shutdown(self->ssl) ==
1307 SSL_RECEIVED_SHUTDOWN))
1309 _PyString_Resize(&buf, 0);
1310 return buf;
1311 } else {
1312 sockstate = SOCKET_OPERATION_OK;
1314 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1315 PyErr_SetString(PySSLErrorObject,
1316 "The read operation timed out");
1317 Py_DECREF(buf);
1318 return NULL;
1319 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1320 break;
1322 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1323 if (count <= 0) {
1324 Py_DECREF(buf);
1325 return PySSL_SetError(self, count, __FILE__, __LINE__);
1327 if (count != len)
1328 _PyString_Resize(&buf, count);
1329 return buf;
1332 PyDoc_STRVAR(PySSL_SSLread_doc,
1333 "read([len]) -> string\n\
1335 Read up to len bytes from the SSL socket.");
1337 static PyObject *PySSL_SSLshutdown(PySSLObject *self)
1339 int err;
1341 /* Guard against closed socket */
1342 if (self->Socket->sock_fd < 0) {
1343 PyErr_SetString(PySSLErrorObject,
1344 "Underlying socket has been closed.");
1345 return NULL;
1348 PySSL_BEGIN_ALLOW_THREADS
1349 err = SSL_shutdown(self->ssl);
1350 if (err == 0) {
1351 /* we need to call it again to finish the shutdown */
1352 err = SSL_shutdown(self->ssl);
1354 PySSL_END_ALLOW_THREADS
1356 if (err < 0)
1357 return PySSL_SetError(self, err, __FILE__, __LINE__);
1358 else {
1359 Py_INCREF(self->Socket);
1360 return (PyObject *) (self->Socket);
1364 PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1365 "shutdown(s) -> socket\n\
1367 Does the SSL shutdown handshake with the remote end, and returns\n\
1368 the underlying socket object.");
1370 static PyMethodDef PySSLMethods[] = {
1371 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1372 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1373 PySSL_SSLwrite_doc},
1374 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1375 PySSL_SSLread_doc},
1376 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1377 PySSL_SSLpending_doc},
1378 {"server", (PyCFunction)PySSL_server, METH_NOARGS},
1379 {"issuer", (PyCFunction)PySSL_issuer, METH_NOARGS},
1380 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1381 PySSL_peercert_doc},
1382 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1383 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1384 PySSL_SSLshutdown_doc},
1385 {NULL, NULL}
1388 static PyObject *PySSL_getattr(PySSLObject *self, char *name)
1390 return Py_FindMethod(PySSLMethods, (PyObject *)self, name);
1393 static PyTypeObject PySSL_Type = {
1394 PyVarObject_HEAD_INIT(NULL, 0)
1395 "ssl.SSLContext", /*tp_name*/
1396 sizeof(PySSLObject), /*tp_basicsize*/
1397 0, /*tp_itemsize*/
1398 /* methods */
1399 (destructor)PySSL_dealloc, /*tp_dealloc*/
1400 0, /*tp_print*/
1401 (getattrfunc)PySSL_getattr, /*tp_getattr*/
1402 0, /*tp_setattr*/
1403 0, /*tp_compare*/
1404 0, /*tp_repr*/
1405 0, /*tp_as_number*/
1406 0, /*tp_as_sequence*/
1407 0, /*tp_as_mapping*/
1408 0, /*tp_hash*/
1411 #ifdef HAVE_OPENSSL_RAND
1413 /* helper routines for seeding the SSL PRNG */
1414 static PyObject *
1415 PySSL_RAND_add(PyObject *self, PyObject *args)
1417 char *buf;
1418 int len;
1419 double entropy;
1421 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
1422 return NULL;
1423 RAND_add(buf, len, entropy);
1424 Py_INCREF(Py_None);
1425 return Py_None;
1428 PyDoc_STRVAR(PySSL_RAND_add_doc,
1429 "RAND_add(string, entropy)\n\
1431 Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
1432 bound on the entropy contained in string. See RFC 1750.");
1434 static PyObject *
1435 PySSL_RAND_status(PyObject *self)
1437 return PyInt_FromLong(RAND_status());
1440 PyDoc_STRVAR(PySSL_RAND_status_doc,
1441 "RAND_status() -> 0 or 1\n\
1443 Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1444 It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1445 using the ssl() function.");
1447 static PyObject *
1448 PySSL_RAND_egd(PyObject *self, PyObject *arg)
1450 int bytes;
1452 if (!PyString_Check(arg))
1453 return PyErr_Format(PyExc_TypeError,
1454 "RAND_egd() expected string, found %s",
1455 Py_TYPE(arg)->tp_name);
1456 bytes = RAND_egd(PyString_AS_STRING(arg));
1457 if (bytes == -1) {
1458 PyErr_SetString(PySSLErrorObject,
1459 "EGD connection failed or EGD did not return "
1460 "enough data to seed the PRNG");
1461 return NULL;
1463 return PyInt_FromLong(bytes);
1466 PyDoc_STRVAR(PySSL_RAND_egd_doc,
1467 "RAND_egd(path) -> bytes\n\
1469 Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1470 Returns number of bytes read. Raises SSLError if connection to EGD\n\
1471 fails or if it does provide enough data to seed PRNG.");
1473 #endif
1475 /* List of functions exported by this module. */
1477 static PyMethodDef PySSL_methods[] = {
1478 {"sslwrap", PySSL_sslwrap,
1479 METH_VARARGS, ssl_doc},
1480 {"_test_decode_cert", PySSL_test_decode_certificate,
1481 METH_VARARGS},
1482 #ifdef HAVE_OPENSSL_RAND
1483 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1484 PySSL_RAND_add_doc},
1485 {"RAND_egd", PySSL_RAND_egd, METH_O,
1486 PySSL_RAND_egd_doc},
1487 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1488 PySSL_RAND_status_doc},
1489 #endif
1490 {NULL, NULL} /* Sentinel */
1494 #ifdef WITH_THREAD
1496 /* an implementation of OpenSSL threading operations in terms
1497 of the Python C thread library */
1499 static PyThread_type_lock *_ssl_locks = NULL;
1501 static unsigned long _ssl_thread_id_function (void) {
1502 return PyThread_get_thread_ident();
1505 static void _ssl_thread_locking_function (int mode, int n, const char *file, int line) {
1506 /* this function is needed to perform locking on shared data
1507 structures. (Note that OpenSSL uses a number of global data
1508 structures that will be implicitly shared whenever multiple threads
1509 use OpenSSL.) Multi-threaded applications will crash at random if
1510 it is not set.
1512 locking_function() must be able to handle up to CRYPTO_num_locks()
1513 different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and
1514 releases it otherwise.
1516 file and line are the file number of the function setting the
1517 lock. They can be useful for debugging.
1520 if ((_ssl_locks == NULL) ||
1521 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1522 return;
1524 if (mode & CRYPTO_LOCK) {
1525 PyThread_acquire_lock(_ssl_locks[n], 1);
1526 } else {
1527 PyThread_release_lock(_ssl_locks[n]);
1531 static int _setup_ssl_threads(void) {
1533 unsigned int i;
1535 if (_ssl_locks == NULL) {
1536 _ssl_locks_count = CRYPTO_num_locks();
1537 _ssl_locks = (PyThread_type_lock *)
1538 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1539 if (_ssl_locks == NULL)
1540 return 0;
1541 memset(_ssl_locks, 0, sizeof(PyThread_type_lock) * _ssl_locks_count);
1542 for (i = 0; i < _ssl_locks_count; i++) {
1543 _ssl_locks[i] = PyThread_allocate_lock();
1544 if (_ssl_locks[i] == NULL) {
1545 unsigned int j;
1546 for (j = 0; j < i; j++) {
1547 PyThread_free_lock(_ssl_locks[j]);
1549 free(_ssl_locks);
1550 return 0;
1553 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1554 CRYPTO_set_id_callback(_ssl_thread_id_function);
1556 return 1;
1559 #endif /* def HAVE_THREAD */
1561 PyDoc_STRVAR(module_doc,
1562 "Implementation module for SSL socket operations. See the socket module\n\
1563 for documentation.");
1565 PyMODINIT_FUNC
1566 init_ssl(void)
1568 PyObject *m, *d;
1570 Py_TYPE(&PySSL_Type) = &PyType_Type;
1572 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
1573 if (m == NULL)
1574 return;
1575 d = PyModule_GetDict(m);
1577 /* Load _socket module and its C API */
1578 if (PySocketModule_ImportModuleAndAPI())
1579 return;
1581 /* Init OpenSSL */
1582 SSL_load_error_strings();
1583 #ifdef WITH_THREAD
1584 /* note that this will start threading if not already started */
1585 if (!_setup_ssl_threads()) {
1586 return;
1588 #endif
1589 SSLeay_add_ssl_algorithms();
1591 /* Add symbols to module dict */
1592 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
1593 PySocketModule.error,
1594 NULL);
1595 if (PySSLErrorObject == NULL)
1596 return;
1597 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
1598 return;
1599 if (PyDict_SetItemString(d, "SSLType",
1600 (PyObject *)&PySSL_Type) != 0)
1601 return;
1602 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
1603 PY_SSL_ERROR_ZERO_RETURN);
1604 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
1605 PY_SSL_ERROR_WANT_READ);
1606 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
1607 PY_SSL_ERROR_WANT_WRITE);
1608 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
1609 PY_SSL_ERROR_WANT_X509_LOOKUP);
1610 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
1611 PY_SSL_ERROR_SYSCALL);
1612 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
1613 PY_SSL_ERROR_SSL);
1614 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1615 PY_SSL_ERROR_WANT_CONNECT);
1616 /* non ssl.h errorcodes */
1617 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1618 PY_SSL_ERROR_EOF);
1619 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1620 PY_SSL_ERROR_INVALID_ERROR_CODE);
1621 /* cert requirements */
1622 PyModule_AddIntConstant(m, "CERT_NONE",
1623 PY_SSL_CERT_NONE);
1624 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1625 PY_SSL_CERT_OPTIONAL);
1626 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1627 PY_SSL_CERT_REQUIRED);
1629 /* protocol versions */
1630 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1631 PY_SSL_VERSION_SSL2);
1632 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1633 PY_SSL_VERSION_SSL3);
1634 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1635 PY_SSL_VERSION_SSL23);
1636 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1637 PY_SSL_VERSION_TLS1);