Blocked revisions 79401 via svnmerge
[python/dscho.git] / Modules / _ssl.c
blob45c44f888fdb9587c10059da0ff6896598079ebf
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_NO_SOCKET, /* socket has been GC'd */
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 static PySocketModule_APIObject PySocketModule;
76 #if defined(HAVE_POLL_H)
77 #include <poll.h>
78 #elif defined(HAVE_SYS_POLL_H)
79 #include <sys/poll.h>
80 #endif
82 /* Include OpenSSL header files */
83 #include "openssl/rsa.h"
84 #include "openssl/crypto.h"
85 #include "openssl/x509.h"
86 #include "openssl/x509v3.h"
87 #include "openssl/pem.h"
88 #include "openssl/ssl.h"
89 #include "openssl/err.h"
90 #include "openssl/rand.h"
92 /* SSL error object */
93 static PyObject *PySSLErrorObject;
95 #ifdef WITH_THREAD
97 /* serves as a flag to see whether we've initialized the SSL thread support. */
98 /* 0 means no, greater than 0 means yes */
100 static unsigned int _ssl_locks_count = 0;
102 #endif /* def WITH_THREAD */
104 /* SSL socket object */
106 #define X509_NAME_MAXLEN 256
108 /* RAND_* APIs got added to OpenSSL in 0.9.5 */
109 #if OPENSSL_VERSION_NUMBER >= 0x0090500fL
110 # define HAVE_OPENSSL_RAND 1
111 #else
112 # undef HAVE_OPENSSL_RAND
113 #endif
115 typedef struct {
116 PyObject_HEAD
117 PyObject *Socket; /* weakref to socket on which we're layered */
118 SSL_CTX* ctx;
119 SSL* ssl;
120 X509* peer_cert;
122 } PySSLObject;
124 static PyTypeObject PySSL_Type;
125 static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args);
126 static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args);
127 static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
128 int writing);
129 static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args);
130 static PyObject *PySSL_cipher(PySSLObject *self);
132 #define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type)
134 typedef enum {
135 SOCKET_IS_NONBLOCKING,
136 SOCKET_IS_BLOCKING,
137 SOCKET_HAS_TIMED_OUT,
138 SOCKET_HAS_BEEN_CLOSED,
139 SOCKET_TOO_LARGE_FOR_SELECT,
140 SOCKET_OPERATION_OK
141 } timeout_state;
143 /* Wrap error strings with filename and line # */
144 #define STRINGIFY1(x) #x
145 #define STRINGIFY2(x) STRINGIFY1(x)
146 #define ERRSTR1(x,y,z) (x ":" y ": " z)
147 #define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
149 /* XXX It might be helpful to augment the error message generated
150 below with the name of the SSL function that generated the error.
151 I expect it's obvious most of the time.
154 static PyObject *
155 PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno)
157 PyObject *v;
158 char buf[2048];
159 char *errstr;
160 int err;
161 enum py_ssl_error p = PY_SSL_ERROR_NONE;
163 assert(ret <= 0);
165 if (obj->ssl != NULL) {
166 err = SSL_get_error(obj->ssl, ret);
168 switch (err) {
169 case SSL_ERROR_ZERO_RETURN:
170 errstr = "TLS/SSL connection has been closed";
171 p = PY_SSL_ERROR_ZERO_RETURN;
172 break;
173 case SSL_ERROR_WANT_READ:
174 errstr = "The operation did not complete (read)";
175 p = PY_SSL_ERROR_WANT_READ;
176 break;
177 case SSL_ERROR_WANT_WRITE:
178 p = PY_SSL_ERROR_WANT_WRITE;
179 errstr = "The operation did not complete (write)";
180 break;
181 case SSL_ERROR_WANT_X509_LOOKUP:
182 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
183 errstr =
184 "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 PySocketSockObject *s
195 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
196 if (ret == 0 || (((PyObject *)s) == Py_None)) {
197 p = PY_SSL_ERROR_EOF;
198 errstr =
199 "EOF occurred in violation of protocol";
200 } else if (ret == -1) {
201 /* underlying BIO reported an I/O error */
202 return s->errorhandler();
203 } else { /* possible? */
204 p = PY_SSL_ERROR_SYSCALL;
205 errstr = "Some I/O error occurred";
207 } else {
208 p = PY_SSL_ERROR_SYSCALL;
209 /* XXX Protected by global interpreter lock */
210 errstr = ERR_error_string(e, NULL);
212 break;
214 case SSL_ERROR_SSL:
216 unsigned long e = ERR_get_error();
217 p = PY_SSL_ERROR_SSL;
218 if (e != 0)
219 /* XXX Protected by global interpreter lock */
220 errstr = ERR_error_string(e, NULL);
221 else { /* possible? */
222 errstr =
223 "A failure in the SSL library occurred";
225 break;
227 default:
228 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
229 errstr = "Invalid error code";
231 } else {
232 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
234 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
235 v = Py_BuildValue("(is)", p, buf);
236 if (v != NULL) {
237 PyErr_SetObject(PySSLErrorObject, v);
238 Py_DECREF(v);
240 return NULL;
243 static PyObject *
244 _setSSLError (char *errstr, int errcode, char *filename, int lineno) {
246 char buf[2048];
247 PyObject *v;
249 if (errstr == NULL) {
250 errcode = ERR_peek_last_error();
251 errstr = ERR_error_string(errcode, NULL);
253 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
254 v = Py_BuildValue("(is)", errcode, buf);
255 if (v != NULL) {
256 PyErr_SetObject(PySSLErrorObject, v);
257 Py_DECREF(v);
259 return NULL;
262 static PySSLObject *
263 newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file,
264 enum py_ssl_server_or_client socket_type,
265 enum py_ssl_cert_requirements certreq,
266 enum py_ssl_version proto_version,
267 char *cacerts_file)
269 PySSLObject *self;
270 char *errstr = NULL;
271 int ret;
272 int verification_mode;
274 self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */
275 if (self == NULL)
276 return NULL;
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 self->Socket = PyWeakref_NewRef((PyObject *) Sock, Py_None);
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 PySocketSockObject *sock
450 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
451 if (((PyObject*)sock) == Py_None) {
452 _setSSLError("Underlying socket connection gone",
453 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
454 return NULL;
457 PySSL_BEGIN_ALLOW_THREADS
458 ret = SSL_do_handshake(self->ssl);
459 err = SSL_get_error(self->ssl, ret);
460 PySSL_END_ALLOW_THREADS
461 if(PyErr_CheckSignals()) {
462 return NULL;
464 if (err == SSL_ERROR_WANT_READ) {
465 sockstate = check_socket_and_wait_for_timeout(sock, 0);
466 } else if (err == SSL_ERROR_WANT_WRITE) {
467 sockstate = check_socket_and_wait_for_timeout(sock, 1);
468 } else {
469 sockstate = SOCKET_OPERATION_OK;
471 if (sockstate == SOCKET_HAS_TIMED_OUT) {
472 PyErr_SetString(PySSLErrorObject,
473 ERRSTR("The handshake operation timed out"));
474 return NULL;
475 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
476 PyErr_SetString(PySSLErrorObject,
477 ERRSTR("Underlying socket has been closed."));
478 return NULL;
479 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
480 PyErr_SetString(PySSLErrorObject,
481 ERRSTR("Underlying socket too large for select()."));
482 return NULL;
483 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
484 break;
486 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
487 if (ret < 1)
488 return PySSL_SetError(self, ret, __FILE__, __LINE__);
489 self->ssl->debug = 1;
491 if (self->peer_cert)
492 X509_free (self->peer_cert);
493 PySSL_BEGIN_ALLOW_THREADS
494 self->peer_cert = SSL_get_peer_certificate(self->ssl);
495 PySSL_END_ALLOW_THREADS
497 Py_INCREF(Py_None);
498 return Py_None;
501 static PyObject *
502 _create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
504 char namebuf[X509_NAME_MAXLEN];
505 int buflen;
506 PyObject *name_obj;
507 PyObject *value_obj;
508 PyObject *attr;
509 unsigned char *valuebuf = NULL;
511 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
512 if (buflen < 0) {
513 _setSSLError(NULL, 0, __FILE__, __LINE__);
514 goto fail;
516 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
517 if (name_obj == NULL)
518 goto fail;
520 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
521 if (buflen < 0) {
522 _setSSLError(NULL, 0, __FILE__, __LINE__);
523 Py_DECREF(name_obj);
524 goto fail;
526 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
527 buflen, "strict");
528 OPENSSL_free(valuebuf);
529 if (value_obj == NULL) {
530 Py_DECREF(name_obj);
531 goto fail;
533 attr = PyTuple_New(2);
534 if (attr == NULL) {
535 Py_DECREF(name_obj);
536 Py_DECREF(value_obj);
537 goto fail;
539 PyTuple_SET_ITEM(attr, 0, name_obj);
540 PyTuple_SET_ITEM(attr, 1, value_obj);
541 return attr;
543 fail:
544 return NULL;
547 static PyObject *
548 _create_tuple_for_X509_NAME (X509_NAME *xname)
550 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
551 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
552 PyObject *rdnt;
553 PyObject *attr = NULL; /* tuple to hold an attribute */
554 int entry_count = X509_NAME_entry_count(xname);
555 X509_NAME_ENTRY *entry;
556 ASN1_OBJECT *name;
557 ASN1_STRING *value;
558 int index_counter;
559 int rdn_level = -1;
560 int retcode;
562 dn = PyList_New(0);
563 if (dn == NULL)
564 return NULL;
565 /* now create another tuple to hold the top-level RDN */
566 rdn = PyList_New(0);
567 if (rdn == NULL)
568 goto fail0;
570 for (index_counter = 0;
571 index_counter < entry_count;
572 index_counter++)
574 entry = X509_NAME_get_entry(xname, index_counter);
576 /* check to see if we've gotten to a new RDN */
577 if (rdn_level >= 0) {
578 if (rdn_level != entry->set) {
579 /* yes, new RDN */
580 /* add old RDN to DN */
581 rdnt = PyList_AsTuple(rdn);
582 Py_DECREF(rdn);
583 if (rdnt == NULL)
584 goto fail0;
585 retcode = PyList_Append(dn, rdnt);
586 Py_DECREF(rdnt);
587 if (retcode < 0)
588 goto fail0;
589 /* create new RDN */
590 rdn = PyList_New(0);
591 if (rdn == NULL)
592 goto fail0;
595 rdn_level = entry->set;
597 /* now add this attribute to the current RDN */
598 name = X509_NAME_ENTRY_get_object(entry);
599 value = X509_NAME_ENTRY_get_data(entry);
600 attr = _create_tuple_for_attribute(name, value);
602 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
603 entry->set,
604 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
605 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
607 if (attr == NULL)
608 goto fail1;
609 retcode = PyList_Append(rdn, attr);
610 Py_DECREF(attr);
611 if (retcode < 0)
612 goto fail1;
614 /* now, there's typically a dangling RDN */
615 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
616 rdnt = PyList_AsTuple(rdn);
617 Py_DECREF(rdn);
618 if (rdnt == NULL)
619 goto fail0;
620 retcode = PyList_Append(dn, rdnt);
621 Py_DECREF(rdnt);
622 if (retcode < 0)
623 goto fail0;
626 /* convert list to tuple */
627 rdnt = PyList_AsTuple(dn);
628 Py_DECREF(dn);
629 if (rdnt == NULL)
630 return NULL;
631 return rdnt;
633 fail1:
634 Py_XDECREF(rdn);
636 fail0:
637 Py_XDECREF(dn);
638 return NULL;
641 static PyObject *
642 _get_peer_alt_names (X509 *certificate) {
644 /* this code follows the procedure outlined in
645 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
646 function to extract the STACK_OF(GENERAL_NAME),
647 then iterates through the stack to add the
648 names. */
650 int i, j;
651 PyObject *peer_alt_names = Py_None;
652 PyObject *v, *t;
653 X509_EXTENSION *ext = NULL;
654 GENERAL_NAMES *names = NULL;
655 GENERAL_NAME *name;
656 X509V3_EXT_METHOD *method;
657 BIO *biobuf = NULL;
658 char buf[2048];
659 char *vptr;
660 int len;
661 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
662 #if OPENSSL_VERSION_NUMBER >= 0x009060dfL
663 const unsigned char *p;
664 #else
665 unsigned char *p;
666 #endif
668 if (certificate == NULL)
669 return peer_alt_names;
671 /* get a memory buffer */
672 biobuf = BIO_new(BIO_s_mem());
674 i = 0;
675 while ((i = X509_get_ext_by_NID(
676 certificate, NID_subject_alt_name, i)) >= 0) {
678 if (peer_alt_names == Py_None) {
679 peer_alt_names = PyList_New(0);
680 if (peer_alt_names == NULL)
681 goto fail;
684 /* now decode the altName */
685 ext = X509_get_ext(certificate, i);
686 if(!(method = X509V3_EXT_get(ext))) {
687 PyErr_SetString
688 (PySSLErrorObject,
689 ERRSTR("No method for internalizing subjectAltName!"));
690 goto fail;
693 p = ext->value->data;
694 if (method->it)
695 names = (GENERAL_NAMES*)
696 (ASN1_item_d2i(NULL,
698 ext->value->length,
699 ASN1_ITEM_ptr(method->it)));
700 else
701 names = (GENERAL_NAMES*)
702 (method->d2i(NULL,
704 ext->value->length));
706 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
708 /* get a rendering of each name in the set of names */
710 name = sk_GENERAL_NAME_value(names, j);
711 if (name->type == GEN_DIRNAME) {
713 /* we special-case DirName as a tuple of
714 tuples of attributes */
716 t = PyTuple_New(2);
717 if (t == NULL) {
718 goto fail;
721 v = PyUnicode_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 = PyUnicode_FromStringAndSize(buf, (vptr - buf));
753 if (v == NULL) {
754 Py_DECREF(t);
755 goto fail;
757 PyTuple_SET_ITEM(t, 0, v);
758 v = PyUnicode_FromStringAndSize((vptr + 1),
759 (len - (vptr - buf + 1)));
760 if (v == NULL) {
761 Py_DECREF(t);
762 goto fail;
764 PyTuple_SET_ITEM(t, 1, v);
767 /* and add that rendering to the list */
769 if (PyList_Append(peer_alt_names, t) < 0) {
770 Py_DECREF(t);
771 goto fail;
773 Py_DECREF(t);
776 BIO_free(biobuf);
777 if (peer_alt_names != Py_None) {
778 v = PyList_AsTuple(peer_alt_names);
779 Py_DECREF(peer_alt_names);
780 return v;
781 } else {
782 return peer_alt_names;
786 fail:
787 if (biobuf != NULL)
788 BIO_free(biobuf);
790 if (peer_alt_names != Py_None) {
791 Py_XDECREF(peer_alt_names);
794 return NULL;
797 static PyObject *
798 _decode_certificate (X509 *certificate, int verbose) {
800 PyObject *retval = NULL;
801 BIO *biobuf = NULL;
802 PyObject *peer;
803 PyObject *peer_alt_names = NULL;
804 PyObject *issuer;
805 PyObject *version;
806 PyObject *sn_obj;
807 ASN1_INTEGER *serialNumber;
808 char buf[2048];
809 int len;
810 ASN1_TIME *notBefore, *notAfter;
811 PyObject *pnotBefore, *pnotAfter;
813 retval = PyDict_New();
814 if (retval == NULL)
815 return NULL;
817 peer = _create_tuple_for_X509_NAME(
818 X509_get_subject_name(certificate));
819 if (peer == NULL)
820 goto fail0;
821 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
822 Py_DECREF(peer);
823 goto fail0;
825 Py_DECREF(peer);
827 if (verbose) {
828 issuer = _create_tuple_for_X509_NAME(
829 X509_get_issuer_name(certificate));
830 if (issuer == NULL)
831 goto fail0;
832 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
833 Py_DECREF(issuer);
834 goto fail0;
836 Py_DECREF(issuer);
838 version = PyLong_FromLong(X509_get_version(certificate) + 1);
839 if (PyDict_SetItemString(retval, "version", version) < 0) {
840 Py_DECREF(version);
841 goto fail0;
843 Py_DECREF(version);
846 /* get a memory buffer */
847 biobuf = BIO_new(BIO_s_mem());
849 if (verbose) {
851 (void) BIO_reset(biobuf);
852 serialNumber = X509_get_serialNumber(certificate);
853 /* should not exceed 20 octets, 160 bits, so buf is big enough */
854 i2a_ASN1_INTEGER(biobuf, serialNumber);
855 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
856 if (len < 0) {
857 _setSSLError(NULL, 0, __FILE__, __LINE__);
858 goto fail1;
860 sn_obj = PyUnicode_FromStringAndSize(buf, len);
861 if (sn_obj == NULL)
862 goto fail1;
863 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
864 Py_DECREF(sn_obj);
865 goto fail1;
867 Py_DECREF(sn_obj);
869 (void) BIO_reset(biobuf);
870 notBefore = X509_get_notBefore(certificate);
871 ASN1_TIME_print(biobuf, notBefore);
872 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
873 if (len < 0) {
874 _setSSLError(NULL, 0, __FILE__, __LINE__);
875 goto fail1;
877 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
878 if (pnotBefore == NULL)
879 goto fail1;
880 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
881 Py_DECREF(pnotBefore);
882 goto fail1;
884 Py_DECREF(pnotBefore);
887 (void) BIO_reset(biobuf);
888 notAfter = X509_get_notAfter(certificate);
889 ASN1_TIME_print(biobuf, notAfter);
890 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
891 if (len < 0) {
892 _setSSLError(NULL, 0, __FILE__, __LINE__);
893 goto fail1;
895 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
896 if (pnotAfter == NULL)
897 goto fail1;
898 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
899 Py_DECREF(pnotAfter);
900 goto fail1;
902 Py_DECREF(pnotAfter);
904 /* Now look for subjectAltName */
906 peer_alt_names = _get_peer_alt_names(certificate);
907 if (peer_alt_names == NULL)
908 goto fail1;
909 else if (peer_alt_names != Py_None) {
910 if (PyDict_SetItemString(retval, "subjectAltName",
911 peer_alt_names) < 0) {
912 Py_DECREF(peer_alt_names);
913 goto fail1;
915 Py_DECREF(peer_alt_names);
918 BIO_free(biobuf);
919 return retval;
921 fail1:
922 if (biobuf != NULL)
923 BIO_free(biobuf);
924 fail0:
925 Py_XDECREF(retval);
926 return NULL;
930 static PyObject *
931 PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
933 PyObject *retval = NULL;
934 char *filename = NULL;
935 X509 *x=NULL;
936 BIO *cert;
937 int verbose = 1;
939 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate",
940 &filename, &verbose))
941 return NULL;
943 if ((cert=BIO_new(BIO_s_file())) == NULL) {
944 PyErr_SetString(PySSLErrorObject,
945 "Can't malloc memory to read file");
946 goto fail0;
949 if (BIO_read_filename(cert,filename) <= 0) {
950 PyErr_SetString(PySSLErrorObject,
951 "Can't open file");
952 goto fail0;
955 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
956 if (x == NULL) {
957 PyErr_SetString(PySSLErrorObject,
958 "Error decoding PEM-encoded file");
959 goto fail0;
962 retval = _decode_certificate(x, verbose);
964 fail0:
966 if (cert != NULL) BIO_free(cert);
967 return retval;
971 static PyObject *
972 PySSL_peercert(PySSLObject *self, PyObject *args)
974 PyObject *retval = NULL;
975 int len;
976 int verification;
977 PyObject *binary_mode = Py_None;
979 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
980 return NULL;
982 if (!self->peer_cert)
983 Py_RETURN_NONE;
985 if (PyObject_IsTrue(binary_mode)) {
986 /* return cert in DER-encoded format */
988 unsigned char *bytes_buf = NULL;
990 bytes_buf = NULL;
991 len = i2d_X509(self->peer_cert, &bytes_buf);
992 if (len < 0) {
993 PySSL_SetError(self, len, __FILE__, __LINE__);
994 return NULL;
996 /* this is actually an immutable bytes sequence */
997 retval = PyBytes_FromStringAndSize
998 ((const char *) bytes_buf, len);
999 OPENSSL_free(bytes_buf);
1000 return retval;
1002 } else {
1004 verification = SSL_CTX_get_verify_mode(self->ctx);
1005 if ((verification & SSL_VERIFY_PEER) == 0)
1006 return PyDict_New();
1007 else
1008 return _decode_certificate (self->peer_cert, 0);
1012 PyDoc_STRVAR(PySSL_peercert_doc,
1013 "peer_certificate([der=False]) -> certificate\n\
1015 Returns the certificate for the peer. If no certificate was provided,\n\
1016 returns None. If a certificate was provided, but not validated, returns\n\
1017 an empty dictionary. Otherwise returns a dict containing information\n\
1018 about the peer certificate.\n\
1020 If the optional argument is True, returns a DER-encoded copy of the\n\
1021 peer certificate, or None if no certificate was provided. This will\n\
1022 return the certificate even if it wasn't validated.");
1024 static PyObject *PySSL_cipher (PySSLObject *self) {
1026 PyObject *retval, *v;
1027 SSL_CIPHER *current;
1028 char *cipher_name;
1029 char *cipher_protocol;
1031 if (self->ssl == NULL)
1032 return Py_None;
1033 current = SSL_get_current_cipher(self->ssl);
1034 if (current == NULL)
1035 return Py_None;
1037 retval = PyTuple_New(3);
1038 if (retval == NULL)
1039 return NULL;
1041 cipher_name = (char *) SSL_CIPHER_get_name(current);
1042 if (cipher_name == NULL) {
1043 PyTuple_SET_ITEM(retval, 0, Py_None);
1044 } else {
1045 v = PyUnicode_FromString(cipher_name);
1046 if (v == NULL)
1047 goto fail0;
1048 PyTuple_SET_ITEM(retval, 0, v);
1050 cipher_protocol = SSL_CIPHER_get_version(current);
1051 if (cipher_protocol == NULL) {
1052 PyTuple_SET_ITEM(retval, 1, Py_None);
1053 } else {
1054 v = PyUnicode_FromString(cipher_protocol);
1055 if (v == NULL)
1056 goto fail0;
1057 PyTuple_SET_ITEM(retval, 1, v);
1059 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1060 if (v == NULL)
1061 goto fail0;
1062 PyTuple_SET_ITEM(retval, 2, v);
1063 return retval;
1065 fail0:
1066 Py_DECREF(retval);
1067 return NULL;
1070 static void PySSL_dealloc(PySSLObject *self)
1072 if (self->peer_cert) /* Possible not to have one? */
1073 X509_free (self->peer_cert);
1074 if (self->ssl)
1075 SSL_free(self->ssl);
1076 if (self->ctx)
1077 SSL_CTX_free(self->ctx);
1078 Py_XDECREF(self->Socket);
1079 PyObject_Del(self);
1082 /* If the socket has a timeout, do a select()/poll() on the socket.
1083 The argument writing indicates the direction.
1084 Returns one of the possibilities in the timeout_state enum (above).
1087 static int
1088 check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
1090 fd_set fds;
1091 struct timeval tv;
1092 int rc;
1094 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1095 if (s->sock_timeout < 0.0)
1096 return SOCKET_IS_BLOCKING;
1097 else if (s->sock_timeout == 0.0)
1098 return SOCKET_IS_NONBLOCKING;
1100 /* Guard against closed socket */
1101 if (s->sock_fd < 0)
1102 return SOCKET_HAS_BEEN_CLOSED;
1104 /* Prefer poll, if available, since you can poll() any fd
1105 * which can't be done with select(). */
1106 #ifdef HAVE_POLL
1108 struct pollfd pollfd;
1109 int timeout;
1111 pollfd.fd = s->sock_fd;
1112 pollfd.events = writing ? POLLOUT : POLLIN;
1114 /* s->sock_timeout is in seconds, timeout in ms */
1115 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1116 PySSL_BEGIN_ALLOW_THREADS
1117 rc = poll(&pollfd, 1, timeout);
1118 PySSL_END_ALLOW_THREADS
1120 goto normal_return;
1122 #endif
1124 /* Guard against socket too large for select*/
1125 #ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
1126 if (s->sock_fd >= FD_SETSIZE)
1127 return SOCKET_TOO_LARGE_FOR_SELECT;
1128 #endif
1130 /* Construct the arguments to select */
1131 tv.tv_sec = (int)s->sock_timeout;
1132 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1133 FD_ZERO(&fds);
1134 FD_SET(s->sock_fd, &fds);
1136 /* See if the socket is ready */
1137 PySSL_BEGIN_ALLOW_THREADS
1138 if (writing)
1139 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1140 else
1141 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1142 PySSL_END_ALLOW_THREADS
1144 #ifdef HAVE_POLL
1145 normal_return:
1146 #endif
1147 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1148 (when we are able to write or when there's something to read) */
1149 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
1152 static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1154 char *data;
1155 int len;
1156 int count;
1157 int sockstate;
1158 int err;
1159 int nonblocking;
1160 PySocketSockObject *sock
1161 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
1163 if (((PyObject*)sock) == Py_None) {
1164 _setSSLError("Underlying socket connection gone",
1165 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1166 return NULL;
1169 if (!PyArg_ParseTuple(args, "y#:write", &data, &count))
1170 return NULL;
1172 /* just in case the blocking state of the socket has been changed */
1173 nonblocking = (sock->sock_timeout >= 0.0);
1174 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1175 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1177 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1178 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1179 PyErr_SetString(PySSLErrorObject,
1180 "The write operation timed out");
1181 return NULL;
1182 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1183 PyErr_SetString(PySSLErrorObject,
1184 "Underlying socket has been closed.");
1185 return NULL;
1186 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1187 PyErr_SetString(PySSLErrorObject,
1188 "Underlying socket too large for select().");
1189 return NULL;
1191 do {
1192 err = 0;
1193 PySSL_BEGIN_ALLOW_THREADS
1194 len = SSL_write(self->ssl, data, count);
1195 err = SSL_get_error(self->ssl, len);
1196 PySSL_END_ALLOW_THREADS
1197 if(PyErr_CheckSignals()) {
1198 return NULL;
1200 if (err == SSL_ERROR_WANT_READ) {
1201 sockstate =
1202 check_socket_and_wait_for_timeout(sock, 0);
1203 } else if (err == SSL_ERROR_WANT_WRITE) {
1204 sockstate =
1205 check_socket_and_wait_for_timeout(sock, 1);
1206 } else {
1207 sockstate = SOCKET_OPERATION_OK;
1209 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1210 PyErr_SetString(PySSLErrorObject,
1211 "The write operation timed out");
1212 return NULL;
1213 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1214 PyErr_SetString(PySSLErrorObject,
1215 "Underlying socket has been closed.");
1216 return NULL;
1217 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1218 break;
1220 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1221 if (len > 0)
1222 return PyLong_FromLong(len);
1223 else
1224 return PySSL_SetError(self, len, __FILE__, __LINE__);
1227 PyDoc_STRVAR(PySSL_SSLwrite_doc,
1228 "write(s) -> len\n\
1230 Writes the string s into the SSL object. Returns the number\n\
1231 of bytes written.");
1233 static PyObject *PySSL_SSLpending(PySSLObject *self)
1235 int count = 0;
1237 PySSL_BEGIN_ALLOW_THREADS
1238 count = SSL_pending(self->ssl);
1239 PySSL_END_ALLOW_THREADS
1240 if (count < 0)
1241 return PySSL_SetError(self, count, __FILE__, __LINE__);
1242 else
1243 return PyLong_FromLong(count);
1246 PyDoc_STRVAR(PySSL_SSLpending_doc,
1247 "pending() -> count\n\
1249 Returns the number of already decrypted bytes available for read,\n\
1250 pending on the connection.\n");
1252 static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1254 PyObject *dest = NULL;
1255 Py_buffer buf;
1256 int buf_passed = 0;
1257 int count = -1;
1258 char *mem;
1259 /* XXX this should use Py_ssize_t */
1260 int len = 1024;
1261 int sockstate;
1262 int err;
1263 int nonblocking;
1264 PySocketSockObject *sock
1265 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
1267 if (((PyObject*)sock) == Py_None) {
1268 _setSSLError("Underlying socket connection gone",
1269 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1270 return NULL;
1273 if (!PyArg_ParseTuple(args, "|Oi:read", &dest, &count))
1274 return NULL;
1275 if ((dest == NULL) || (dest == Py_None)) {
1276 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
1277 return NULL;
1278 mem = PyByteArray_AS_STRING(dest);
1279 } else if (PyLong_Check(dest)) {
1280 len = PyLong_AS_LONG(dest);
1281 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
1282 return NULL;
1283 mem = PyByteArray_AS_STRING(dest);
1284 } else {
1285 if (PyObject_GetBuffer(dest, &buf, PyBUF_CONTIG) < 0)
1286 return NULL;
1287 mem = buf.buf;
1288 len = buf.len;
1289 if ((count > 0) && (count <= len))
1290 len = count;
1291 buf_passed = 1;
1294 /* just in case the blocking state of the socket has been changed */
1295 nonblocking = (sock->sock_timeout >= 0.0);
1296 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1297 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1299 /* first check if there are bytes ready to be read */
1300 PySSL_BEGIN_ALLOW_THREADS
1301 count = SSL_pending(self->ssl);
1302 PySSL_END_ALLOW_THREADS
1304 if (!count) {
1305 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1306 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1307 PyErr_SetString(PySSLErrorObject,
1308 "The read operation timed out");
1309 goto error;
1310 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1311 PyErr_SetString(PySSLErrorObject,
1312 "Underlying socket too large for select().");
1313 goto error;
1314 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1315 count = 0;
1316 goto done;
1319 do {
1320 err = 0;
1321 PySSL_BEGIN_ALLOW_THREADS
1322 count = SSL_read(self->ssl, mem, len);
1323 err = SSL_get_error(self->ssl, count);
1324 PySSL_END_ALLOW_THREADS
1325 if (PyErr_CheckSignals())
1326 goto error;
1327 if (err == SSL_ERROR_WANT_READ) {
1328 sockstate =
1329 check_socket_and_wait_for_timeout(sock, 0);
1330 } else if (err == SSL_ERROR_WANT_WRITE) {
1331 sockstate =
1332 check_socket_and_wait_for_timeout(sock, 1);
1333 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1334 (SSL_get_shutdown(self->ssl) ==
1335 SSL_RECEIVED_SHUTDOWN))
1337 count = 0;
1338 goto done;
1339 } else {
1340 sockstate = SOCKET_OPERATION_OK;
1342 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1343 PyErr_SetString(PySSLErrorObject,
1344 "The read operation timed out");
1345 goto error;
1346 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1347 break;
1349 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1350 if (count <= 0) {
1351 PySSL_SetError(self, count, __FILE__, __LINE__);
1352 goto error;
1354 done:
1355 if (!buf_passed) {
1356 PyObject *res = PyBytes_FromStringAndSize(mem, count);
1357 Py_DECREF(dest);
1358 return res;
1359 } else {
1360 PyBuffer_Release(&buf);
1361 return PyLong_FromLong(count);
1363 error:
1364 if (!buf_passed) {
1365 Py_DECREF(dest);
1366 } else {
1367 PyBuffer_Release(&buf);
1369 return NULL;
1372 PyDoc_STRVAR(PySSL_SSLread_doc,
1373 "read([len]) -> string\n\
1375 Read up to len bytes from the SSL socket.");
1377 static PyObject *PySSL_SSLshutdown(PySSLObject *self)
1379 int err;
1380 PySocketSockObject *sock
1381 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
1383 /* Guard against closed socket */
1384 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1385 _setSSLError("Underlying socket connection gone",
1386 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1387 return NULL;
1390 PySSL_BEGIN_ALLOW_THREADS
1391 err = SSL_shutdown(self->ssl);
1392 if (err == 0) {
1393 /* we need to call it again to finish the shutdown */
1394 err = SSL_shutdown(self->ssl);
1396 PySSL_END_ALLOW_THREADS
1398 if (err < 0)
1399 return PySSL_SetError(self, err, __FILE__, __LINE__);
1400 else {
1401 Py_INCREF(sock);
1402 return (PyObject *) sock;
1406 PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1407 "shutdown(s) -> socket\n\
1409 Does the SSL shutdown handshake with the remote end, and returns\n\
1410 the underlying socket object.");
1413 static PyMethodDef PySSLMethods[] = {
1414 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1415 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1416 PySSL_SSLwrite_doc},
1417 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1418 PySSL_SSLread_doc},
1419 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1420 PySSL_SSLpending_doc},
1421 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1422 PySSL_peercert_doc},
1423 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1424 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1425 PySSL_SSLshutdown_doc},
1426 {NULL, NULL}
1429 static PyTypeObject PySSL_Type = {
1430 PyVarObject_HEAD_INIT(NULL, 0)
1431 "ssl.SSLContext", /*tp_name*/
1432 sizeof(PySSLObject), /*tp_basicsize*/
1433 0, /*tp_itemsize*/
1434 /* methods */
1435 (destructor)PySSL_dealloc, /*tp_dealloc*/
1436 0, /*tp_print*/
1437 0, /*tp_getattr*/
1438 0, /*tp_setattr*/
1439 0, /*tp_reserved*/
1440 0, /*tp_repr*/
1441 0, /*tp_as_number*/
1442 0, /*tp_as_sequence*/
1443 0, /*tp_as_mapping*/
1444 0, /*tp_hash*/
1445 0, /*tp_call*/
1446 0, /*tp_str*/
1447 0, /*tp_getattro*/
1448 0, /*tp_setattro*/
1449 0, /*tp_as_buffer*/
1450 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1451 0, /*tp_doc*/
1452 0, /*tp_traverse*/
1453 0, /*tp_clear*/
1454 0, /*tp_richcompare*/
1455 0, /*tp_weaklistoffset*/
1456 0, /*tp_iter*/
1457 0, /*tp_iternext*/
1458 PySSLMethods, /*tp_methods*/
1461 #ifdef HAVE_OPENSSL_RAND
1463 /* helper routines for seeding the SSL PRNG */
1464 static PyObject *
1465 PySSL_RAND_add(PyObject *self, PyObject *args)
1467 char *buf;
1468 int len;
1469 double entropy;
1471 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
1472 return NULL;
1473 RAND_add(buf, len, entropy);
1474 Py_INCREF(Py_None);
1475 return Py_None;
1478 PyDoc_STRVAR(PySSL_RAND_add_doc,
1479 "RAND_add(string, entropy)\n\
1481 Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
1482 bound on the entropy contained in string. See RFC 1750.");
1484 static PyObject *
1485 PySSL_RAND_status(PyObject *self)
1487 return PyLong_FromLong(RAND_status());
1490 PyDoc_STRVAR(PySSL_RAND_status_doc,
1491 "RAND_status() -> 0 or 1\n\
1493 Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1494 It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1495 using the ssl() function.");
1497 static PyObject *
1498 PySSL_RAND_egd(PyObject *self, PyObject *arg)
1500 int bytes;
1502 if (!PyUnicode_Check(arg))
1503 return PyErr_Format(PyExc_TypeError,
1504 "RAND_egd() expected string, found %s",
1505 Py_TYPE(arg)->tp_name);
1506 bytes = RAND_egd(_PyUnicode_AsString(arg));
1507 if (bytes == -1) {
1508 PyErr_SetString(PySSLErrorObject,
1509 "EGD connection failed or EGD did not return "
1510 "enough data to seed the PRNG");
1511 return NULL;
1513 return PyLong_FromLong(bytes);
1516 PyDoc_STRVAR(PySSL_RAND_egd_doc,
1517 "RAND_egd(path) -> bytes\n\
1519 Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1520 Returns number of bytes read. Raises SSLError if connection to EGD\n\
1521 fails or if it does provide enough data to seed PRNG.");
1523 #endif
1527 /* List of functions exported by this module. */
1529 static PyMethodDef PySSL_methods[] = {
1530 {"sslwrap", PySSL_sslwrap,
1531 METH_VARARGS, ssl_doc},
1532 {"_test_decode_cert", PySSL_test_decode_certificate,
1533 METH_VARARGS},
1534 #ifdef HAVE_OPENSSL_RAND
1535 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1536 PySSL_RAND_add_doc},
1537 {"RAND_egd", PySSL_RAND_egd, METH_O,
1538 PySSL_RAND_egd_doc},
1539 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1540 PySSL_RAND_status_doc},
1541 #endif
1542 {NULL, NULL} /* Sentinel */
1546 #ifdef WITH_THREAD
1548 /* an implementation of OpenSSL threading operations in terms
1549 of the Python C thread library */
1551 static PyThread_type_lock *_ssl_locks = NULL;
1553 static unsigned long _ssl_thread_id_function (void) {
1554 return PyThread_get_thread_ident();
1557 static void _ssl_thread_locking_function
1558 (int mode, int n, const char *file, int line) {
1559 /* this function is needed to perform locking on shared data
1560 structures. (Note that OpenSSL uses a number of global data
1561 structures that will be implicitly shared whenever multiple
1562 threads use OpenSSL.) Multi-threaded applications will
1563 crash at random if it is not set.
1565 locking_function() must be able to handle up to
1566 CRYPTO_num_locks() different mutex locks. It sets the n-th
1567 lock if mode & CRYPTO_LOCK, and releases it otherwise.
1569 file and line are the file number of the function setting the
1570 lock. They can be useful for debugging.
1573 if ((_ssl_locks == NULL) ||
1574 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1575 return;
1577 if (mode & CRYPTO_LOCK) {
1578 PyThread_acquire_lock(_ssl_locks[n], 1);
1579 } else {
1580 PyThread_release_lock(_ssl_locks[n]);
1584 static int _setup_ssl_threads(void) {
1586 unsigned int i;
1588 if (_ssl_locks == NULL) {
1589 _ssl_locks_count = CRYPTO_num_locks();
1590 _ssl_locks = (PyThread_type_lock *)
1591 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1592 if (_ssl_locks == NULL)
1593 return 0;
1594 memset(_ssl_locks, 0,
1595 sizeof(PyThread_type_lock) * _ssl_locks_count);
1596 for (i = 0; i < _ssl_locks_count; i++) {
1597 _ssl_locks[i] = PyThread_allocate_lock();
1598 if (_ssl_locks[i] == NULL) {
1599 unsigned int j;
1600 for (j = 0; j < i; j++) {
1601 PyThread_free_lock(_ssl_locks[j]);
1603 free(_ssl_locks);
1604 return 0;
1607 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1608 CRYPTO_set_id_callback(_ssl_thread_id_function);
1610 return 1;
1613 #endif /* def HAVE_THREAD */
1615 PyDoc_STRVAR(module_doc,
1616 "Implementation module for SSL socket operations. See the socket module\n\
1617 for documentation.");
1620 static struct PyModuleDef _sslmodule = {
1621 PyModuleDef_HEAD_INIT,
1622 "_ssl",
1623 module_doc,
1625 PySSL_methods,
1626 NULL,
1627 NULL,
1628 NULL,
1629 NULL
1632 PyMODINIT_FUNC
1633 PyInit__ssl(void)
1635 PyObject *m, *d;
1636 PySocketModule_APIObject *socket_api;
1638 if (PyType_Ready(&PySSL_Type) < 0)
1639 return NULL;
1641 m = PyModule_Create(&_sslmodule);
1642 if (m == NULL)
1643 return NULL;
1644 d = PyModule_GetDict(m);
1646 /* Load _socket module and its C API */
1647 socket_api = PySocketModule_ImportModuleAndAPI();
1648 if (!socket_api)
1649 return NULL;
1650 PySocketModule = *socket_api;
1652 /* Init OpenSSL */
1653 SSL_load_error_strings();
1654 #ifdef WITH_THREAD
1655 /* note that this will start threading if not already started */
1656 if (!_setup_ssl_threads()) {
1657 return NULL;
1659 #endif
1660 SSLeay_add_ssl_algorithms();
1662 /* Add symbols to module dict */
1663 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
1664 PySocketModule.error,
1665 NULL);
1666 if (PySSLErrorObject == NULL)
1667 return NULL;
1668 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
1669 return NULL;
1670 if (PyDict_SetItemString(d, "SSLType",
1671 (PyObject *)&PySSL_Type) != 0)
1672 return NULL;
1673 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
1674 PY_SSL_ERROR_ZERO_RETURN);
1675 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
1676 PY_SSL_ERROR_WANT_READ);
1677 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
1678 PY_SSL_ERROR_WANT_WRITE);
1679 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
1680 PY_SSL_ERROR_WANT_X509_LOOKUP);
1681 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
1682 PY_SSL_ERROR_SYSCALL);
1683 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
1684 PY_SSL_ERROR_SSL);
1685 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1686 PY_SSL_ERROR_WANT_CONNECT);
1687 /* non ssl.h errorcodes */
1688 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1689 PY_SSL_ERROR_EOF);
1690 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1691 PY_SSL_ERROR_INVALID_ERROR_CODE);
1692 /* cert requirements */
1693 PyModule_AddIntConstant(m, "CERT_NONE",
1694 PY_SSL_CERT_NONE);
1695 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1696 PY_SSL_CERT_OPTIONAL);
1697 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1698 PY_SSL_CERT_REQUIRED);
1700 /* protocol versions */
1701 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1702 PY_SSL_VERSION_SSL2);
1703 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1704 PY_SSL_VERSION_SSL3);
1705 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1706 PY_SSL_VERSION_SSL23);
1707 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1708 PY_SSL_VERSION_TLS1);
1709 return m;