Issue #7117: Update float formatting testcases to match those in py3k.
[python.git] / Modules / _ssl.c
blob87408c927913acc16d8967fdd652d70c254a6842
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 Py_buffer buf;
1148 int len;
1149 int sockstate;
1150 int err;
1151 int nonblocking;
1153 if (!PyArg_ParseTuple(args, "s*:write", &buf))
1154 return NULL;
1156 /* just in case the blocking state of the socket has been changed */
1157 nonblocking = (self->Socket->sock_timeout >= 0.0);
1158 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1159 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1161 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1162 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1163 PyErr_SetString(PySSLErrorObject,
1164 "The write operation timed out");
1165 goto error;
1166 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1167 PyErr_SetString(PySSLErrorObject,
1168 "Underlying socket has been closed.");
1169 goto error;
1170 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1171 PyErr_SetString(PySSLErrorObject,
1172 "Underlying socket too large for select().");
1173 goto error;
1175 do {
1176 err = 0;
1177 PySSL_BEGIN_ALLOW_THREADS
1178 len = SSL_write(self->ssl, buf.buf, buf.len);
1179 err = SSL_get_error(self->ssl, len);
1180 PySSL_END_ALLOW_THREADS
1181 if (PyErr_CheckSignals()) {
1182 goto error;
1184 if (err == SSL_ERROR_WANT_READ) {
1185 sockstate =
1186 check_socket_and_wait_for_timeout(self->Socket, 0);
1187 } else if (err == SSL_ERROR_WANT_WRITE) {
1188 sockstate =
1189 check_socket_and_wait_for_timeout(self->Socket, 1);
1190 } else {
1191 sockstate = SOCKET_OPERATION_OK;
1193 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1194 PyErr_SetString(PySSLErrorObject,
1195 "The write operation timed out");
1196 goto error;
1197 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1198 PyErr_SetString(PySSLErrorObject,
1199 "Underlying socket has been closed.");
1200 goto error;
1201 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1202 break;
1204 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1206 PyBuffer_Release(&buf);
1207 if (len > 0)
1208 return PyInt_FromLong(len);
1209 else
1210 return PySSL_SetError(self, len, __FILE__, __LINE__);
1212 error:
1213 PyBuffer_Release(&buf);
1214 return NULL;
1217 PyDoc_STRVAR(PySSL_SSLwrite_doc,
1218 "write(s) -> len\n\
1220 Writes the string s into the SSL object. Returns the number\n\
1221 of bytes written.");
1223 static PyObject *PySSL_SSLpending(PySSLObject *self)
1225 int count = 0;
1227 PySSL_BEGIN_ALLOW_THREADS
1228 count = SSL_pending(self->ssl);
1229 PySSL_END_ALLOW_THREADS
1230 if (count < 0)
1231 return PySSL_SetError(self, count, __FILE__, __LINE__);
1232 else
1233 return PyInt_FromLong(count);
1236 PyDoc_STRVAR(PySSL_SSLpending_doc,
1237 "pending() -> count\n\
1239 Returns the number of already decrypted bytes available for read,\n\
1240 pending on the connection.\n");
1242 static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1244 PyObject *buf;
1245 int count = 0;
1246 int len = 1024;
1247 int sockstate;
1248 int err;
1249 int nonblocking;
1251 if (!PyArg_ParseTuple(args, "|i:read", &len))
1252 return NULL;
1254 if (!(buf = PyString_FromStringAndSize((char *) 0, len)))
1255 return NULL;
1257 /* just in case the blocking state of the socket has been changed */
1258 nonblocking = (self->Socket->sock_timeout >= 0.0);
1259 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1260 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1262 /* first check if there are bytes ready to be read */
1263 PySSL_BEGIN_ALLOW_THREADS
1264 count = SSL_pending(self->ssl);
1265 PySSL_END_ALLOW_THREADS
1267 if (!count) {
1268 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1269 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1270 PyErr_SetString(PySSLErrorObject,
1271 "The read operation timed out");
1272 Py_DECREF(buf);
1273 return NULL;
1274 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1275 PyErr_SetString(PySSLErrorObject,
1276 "Underlying socket too large for select().");
1277 Py_DECREF(buf);
1278 return NULL;
1279 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1280 if (SSL_get_shutdown(self->ssl) !=
1281 SSL_RECEIVED_SHUTDOWN)
1283 Py_DECREF(buf);
1284 PyErr_SetString(PySSLErrorObject,
1285 "Socket closed without SSL shutdown handshake");
1286 return NULL;
1287 } else {
1288 /* should contain a zero-length string */
1289 _PyString_Resize(&buf, 0);
1290 return buf;
1294 do {
1295 err = 0;
1296 PySSL_BEGIN_ALLOW_THREADS
1297 count = SSL_read(self->ssl, PyString_AsString(buf), len);
1298 err = SSL_get_error(self->ssl, count);
1299 PySSL_END_ALLOW_THREADS
1300 if(PyErr_CheckSignals()) {
1301 Py_DECREF(buf);
1302 return NULL;
1304 if (err == SSL_ERROR_WANT_READ) {
1305 sockstate =
1306 check_socket_and_wait_for_timeout(self->Socket, 0);
1307 } else if (err == SSL_ERROR_WANT_WRITE) {
1308 sockstate =
1309 check_socket_and_wait_for_timeout(self->Socket, 1);
1310 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1311 (SSL_get_shutdown(self->ssl) ==
1312 SSL_RECEIVED_SHUTDOWN))
1314 _PyString_Resize(&buf, 0);
1315 return buf;
1316 } else {
1317 sockstate = SOCKET_OPERATION_OK;
1319 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1320 PyErr_SetString(PySSLErrorObject,
1321 "The read operation timed out");
1322 Py_DECREF(buf);
1323 return NULL;
1324 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1325 break;
1327 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1328 if (count <= 0) {
1329 Py_DECREF(buf);
1330 return PySSL_SetError(self, count, __FILE__, __LINE__);
1332 if (count != len)
1333 _PyString_Resize(&buf, count);
1334 return buf;
1337 PyDoc_STRVAR(PySSL_SSLread_doc,
1338 "read([len]) -> string\n\
1340 Read up to len bytes from the SSL socket.");
1342 static PyObject *PySSL_SSLshutdown(PySSLObject *self)
1344 int err;
1346 /* Guard against closed socket */
1347 if (self->Socket->sock_fd < 0) {
1348 PyErr_SetString(PySSLErrorObject,
1349 "Underlying socket has been closed.");
1350 return NULL;
1353 PySSL_BEGIN_ALLOW_THREADS
1354 err = SSL_shutdown(self->ssl);
1355 if (err == 0) {
1356 /* we need to call it again to finish the shutdown */
1357 err = SSL_shutdown(self->ssl);
1359 PySSL_END_ALLOW_THREADS
1361 if (err < 0)
1362 return PySSL_SetError(self, err, __FILE__, __LINE__);
1363 else {
1364 Py_INCREF(self->Socket);
1365 return (PyObject *) (self->Socket);
1369 PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1370 "shutdown(s) -> socket\n\
1372 Does the SSL shutdown handshake with the remote end, and returns\n\
1373 the underlying socket object.");
1375 static PyMethodDef PySSLMethods[] = {
1376 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1377 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1378 PySSL_SSLwrite_doc},
1379 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1380 PySSL_SSLread_doc},
1381 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1382 PySSL_SSLpending_doc},
1383 {"server", (PyCFunction)PySSL_server, METH_NOARGS},
1384 {"issuer", (PyCFunction)PySSL_issuer, METH_NOARGS},
1385 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1386 PySSL_peercert_doc},
1387 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1388 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1389 PySSL_SSLshutdown_doc},
1390 {NULL, NULL}
1393 static PyObject *PySSL_getattr(PySSLObject *self, char *name)
1395 return Py_FindMethod(PySSLMethods, (PyObject *)self, name);
1398 static PyTypeObject PySSL_Type = {
1399 PyVarObject_HEAD_INIT(NULL, 0)
1400 "ssl.SSLContext", /*tp_name*/
1401 sizeof(PySSLObject), /*tp_basicsize*/
1402 0, /*tp_itemsize*/
1403 /* methods */
1404 (destructor)PySSL_dealloc, /*tp_dealloc*/
1405 0, /*tp_print*/
1406 (getattrfunc)PySSL_getattr, /*tp_getattr*/
1407 0, /*tp_setattr*/
1408 0, /*tp_compare*/
1409 0, /*tp_repr*/
1410 0, /*tp_as_number*/
1411 0, /*tp_as_sequence*/
1412 0, /*tp_as_mapping*/
1413 0, /*tp_hash*/
1416 #ifdef HAVE_OPENSSL_RAND
1418 /* helper routines for seeding the SSL PRNG */
1419 static PyObject *
1420 PySSL_RAND_add(PyObject *self, PyObject *args)
1422 char *buf;
1423 int len;
1424 double entropy;
1426 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
1427 return NULL;
1428 RAND_add(buf, len, entropy);
1429 Py_INCREF(Py_None);
1430 return Py_None;
1433 PyDoc_STRVAR(PySSL_RAND_add_doc,
1434 "RAND_add(string, entropy)\n\
1436 Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
1437 bound on the entropy contained in string. See RFC 1750.");
1439 static PyObject *
1440 PySSL_RAND_status(PyObject *self)
1442 return PyInt_FromLong(RAND_status());
1445 PyDoc_STRVAR(PySSL_RAND_status_doc,
1446 "RAND_status() -> 0 or 1\n\
1448 Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1449 It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1450 using the ssl() function.");
1452 static PyObject *
1453 PySSL_RAND_egd(PyObject *self, PyObject *arg)
1455 int bytes;
1457 if (!PyString_Check(arg))
1458 return PyErr_Format(PyExc_TypeError,
1459 "RAND_egd() expected string, found %s",
1460 Py_TYPE(arg)->tp_name);
1461 bytes = RAND_egd(PyString_AS_STRING(arg));
1462 if (bytes == -1) {
1463 PyErr_SetString(PySSLErrorObject,
1464 "EGD connection failed or EGD did not return "
1465 "enough data to seed the PRNG");
1466 return NULL;
1468 return PyInt_FromLong(bytes);
1471 PyDoc_STRVAR(PySSL_RAND_egd_doc,
1472 "RAND_egd(path) -> bytes\n\
1474 Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1475 Returns number of bytes read. Raises SSLError if connection to EGD\n\
1476 fails or if it does provide enough data to seed PRNG.");
1478 #endif
1480 /* List of functions exported by this module. */
1482 static PyMethodDef PySSL_methods[] = {
1483 {"sslwrap", PySSL_sslwrap,
1484 METH_VARARGS, ssl_doc},
1485 {"_test_decode_cert", PySSL_test_decode_certificate,
1486 METH_VARARGS},
1487 #ifdef HAVE_OPENSSL_RAND
1488 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1489 PySSL_RAND_add_doc},
1490 {"RAND_egd", PySSL_RAND_egd, METH_O,
1491 PySSL_RAND_egd_doc},
1492 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1493 PySSL_RAND_status_doc},
1494 #endif
1495 {NULL, NULL} /* Sentinel */
1499 #ifdef WITH_THREAD
1501 /* an implementation of OpenSSL threading operations in terms
1502 of the Python C thread library */
1504 static PyThread_type_lock *_ssl_locks = NULL;
1506 static unsigned long _ssl_thread_id_function (void) {
1507 return PyThread_get_thread_ident();
1510 static void _ssl_thread_locking_function (int mode, int n, const char *file, int line) {
1511 /* this function is needed to perform locking on shared data
1512 structures. (Note that OpenSSL uses a number of global data
1513 structures that will be implicitly shared whenever multiple threads
1514 use OpenSSL.) Multi-threaded applications will crash at random if
1515 it is not set.
1517 locking_function() must be able to handle up to CRYPTO_num_locks()
1518 different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and
1519 releases it otherwise.
1521 file and line are the file number of the function setting the
1522 lock. They can be useful for debugging.
1525 if ((_ssl_locks == NULL) ||
1526 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1527 return;
1529 if (mode & CRYPTO_LOCK) {
1530 PyThread_acquire_lock(_ssl_locks[n], 1);
1531 } else {
1532 PyThread_release_lock(_ssl_locks[n]);
1536 static int _setup_ssl_threads(void) {
1538 unsigned int i;
1540 if (_ssl_locks == NULL) {
1541 _ssl_locks_count = CRYPTO_num_locks();
1542 _ssl_locks = (PyThread_type_lock *)
1543 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1544 if (_ssl_locks == NULL)
1545 return 0;
1546 memset(_ssl_locks, 0, sizeof(PyThread_type_lock) * _ssl_locks_count);
1547 for (i = 0; i < _ssl_locks_count; i++) {
1548 _ssl_locks[i] = PyThread_allocate_lock();
1549 if (_ssl_locks[i] == NULL) {
1550 unsigned int j;
1551 for (j = 0; j < i; j++) {
1552 PyThread_free_lock(_ssl_locks[j]);
1554 free(_ssl_locks);
1555 return 0;
1558 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1559 CRYPTO_set_id_callback(_ssl_thread_id_function);
1561 return 1;
1564 #endif /* def HAVE_THREAD */
1566 PyDoc_STRVAR(module_doc,
1567 "Implementation module for SSL socket operations. See the socket module\n\
1568 for documentation.");
1570 PyMODINIT_FUNC
1571 init_ssl(void)
1573 PyObject *m, *d;
1575 Py_TYPE(&PySSL_Type) = &PyType_Type;
1577 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
1578 if (m == NULL)
1579 return;
1580 d = PyModule_GetDict(m);
1582 /* Load _socket module and its C API */
1583 if (PySocketModule_ImportModuleAndAPI())
1584 return;
1586 /* Init OpenSSL */
1587 SSL_load_error_strings();
1588 #ifdef WITH_THREAD
1589 /* note that this will start threading if not already started */
1590 if (!_setup_ssl_threads()) {
1591 return;
1593 #endif
1594 SSLeay_add_ssl_algorithms();
1596 /* Add symbols to module dict */
1597 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
1598 PySocketModule.error,
1599 NULL);
1600 if (PySSLErrorObject == NULL)
1601 return;
1602 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
1603 return;
1604 if (PyDict_SetItemString(d, "SSLType",
1605 (PyObject *)&PySSL_Type) != 0)
1606 return;
1607 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
1608 PY_SSL_ERROR_ZERO_RETURN);
1609 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
1610 PY_SSL_ERROR_WANT_READ);
1611 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
1612 PY_SSL_ERROR_WANT_WRITE);
1613 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
1614 PY_SSL_ERROR_WANT_X509_LOOKUP);
1615 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
1616 PY_SSL_ERROR_SYSCALL);
1617 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
1618 PY_SSL_ERROR_SSL);
1619 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1620 PY_SSL_ERROR_WANT_CONNECT);
1621 /* non ssl.h errorcodes */
1622 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1623 PY_SSL_ERROR_EOF);
1624 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1625 PY_SSL_ERROR_INVALID_ERROR_CODE);
1626 /* cert requirements */
1627 PyModule_AddIntConstant(m, "CERT_NONE",
1628 PY_SSL_CERT_NONE);
1629 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1630 PY_SSL_CERT_OPTIONAL);
1631 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1632 PY_SSL_CERT_REQUIRED);
1634 /* protocol versions */
1635 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1636 PY_SSL_VERSION_SSL2);
1637 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1638 PY_SSL_VERSION_SSL3);
1639 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1640 PY_SSL_VERSION_SSL23);
1641 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1642 PY_SSL_VERSION_TLS1);