source: python/trunk/Modules/_ssl.c

Last change on this file was 391, checked in by dmik, 11 years ago

python: Merge vendor 2.7.6 to trunk.

  • Property svn:eol-style set to native
File size: 56.1 KB
RevLine 
[2]1/* SSL socket module
2
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.
7
8 This module is imported by ssl.py. It should *not* be used
9 directly.
10
11 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
12
[391]13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
[2]15*/
16
17#include "Python.h"
18
19#ifdef WITH_THREAD
20#include "pythread.h"
[391]21
22
[2]23#define PySSL_BEGIN_ALLOW_THREADS { \
[391]24 PyThreadState *_save = NULL; \
25 if (_ssl_locks_count>0) {_save = PyEval_SaveThread();}
26#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)};
27#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()};
28#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \
29 }
[2]30
[391]31#else /* no WITH_THREAD */
[2]32
33#define PySSL_BEGIN_ALLOW_THREADS
34#define PySSL_BLOCK_THREADS
35#define PySSL_UNBLOCK_THREADS
36#define PySSL_END_ALLOW_THREADS
37
38#endif
39
40enum py_ssl_error {
[391]41 /* these mirror ssl.h */
42 PY_SSL_ERROR_NONE,
43 PY_SSL_ERROR_SSL,
44 PY_SSL_ERROR_WANT_READ,
45 PY_SSL_ERROR_WANT_WRITE,
46 PY_SSL_ERROR_WANT_X509_LOOKUP,
47 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
48 PY_SSL_ERROR_ZERO_RETURN,
49 PY_SSL_ERROR_WANT_CONNECT,
50 /* start of non ssl.h errorcodes */
51 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
52 PY_SSL_ERROR_INVALID_ERROR_CODE
[2]53};
54
55enum py_ssl_server_or_client {
[391]56 PY_SSL_CLIENT,
57 PY_SSL_SERVER
[2]58};
59
60enum py_ssl_cert_requirements {
[391]61 PY_SSL_CERT_NONE,
62 PY_SSL_CERT_OPTIONAL,
63 PY_SSL_CERT_REQUIRED
[2]64};
65
66enum py_ssl_version {
[391]67#ifndef OPENSSL_NO_SSL2
68 PY_SSL_VERSION_SSL2,
69#endif
70 PY_SSL_VERSION_SSL3=1,
71 PY_SSL_VERSION_SSL23,
72 PY_SSL_VERSION_TLS1
[2]73};
74
75/* Include symbols from _socket module */
76#include "socketmodule.h"
77
78#if defined(HAVE_POLL_H)
79#include <poll.h>
80#elif defined(HAVE_SYS_POLL_H)
81#include <sys/poll.h>
82#endif
83
84/* Include OpenSSL header files */
85#include "openssl/rsa.h"
86#include "openssl/crypto.h"
87#include "openssl/x509.h"
88#include "openssl/x509v3.h"
89#include "openssl/pem.h"
90#include "openssl/ssl.h"
91#include "openssl/err.h"
92#include "openssl/rand.h"
93
94/* SSL error object */
95static PyObject *PySSLErrorObject;
96
97#ifdef WITH_THREAD
98
99/* serves as a flag to see whether we've initialized the SSL thread support. */
100/* 0 means no, greater than 0 means yes */
101
102static unsigned int _ssl_locks_count = 0;
103
104#endif /* def WITH_THREAD */
105
106/* SSL socket object */
107
108#define X509_NAME_MAXLEN 256
109
110/* RAND_* APIs got added to OpenSSL in 0.9.5 */
111#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
112# define HAVE_OPENSSL_RAND 1
113#else
114# undef HAVE_OPENSSL_RAND
115#endif
116
117typedef struct {
[391]118 PyObject_HEAD
119 PySocketSockObject *Socket; /* Socket on which we're layered */
120 SSL_CTX* ctx;
121 SSL* ssl;
122 X509* peer_cert;
123 char server[X509_NAME_MAXLEN];
124 char issuer[X509_NAME_MAXLEN];
125 int shutdown_seen_zero;
[2]126
127} PySSLObject;
128
129static PyTypeObject PySSL_Type;
130static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args);
131static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args);
132static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
[391]133 int writing);
[2]134static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args);
135static PyObject *PySSL_cipher(PySSLObject *self);
136
[391]137#define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type)
[2]138
139typedef enum {
[391]140 SOCKET_IS_NONBLOCKING,
141 SOCKET_IS_BLOCKING,
142 SOCKET_HAS_TIMED_OUT,
143 SOCKET_HAS_BEEN_CLOSED,
144 SOCKET_TOO_LARGE_FOR_SELECT,
145 SOCKET_OPERATION_OK
[2]146} timeout_state;
147
148/* Wrap error strings with filename and line # */
149#define STRINGIFY1(x) #x
150#define STRINGIFY2(x) STRINGIFY1(x)
151#define ERRSTR1(x,y,z) (x ":" y ": " z)
152#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
153
154/* XXX It might be helpful to augment the error message generated
155 below with the name of the SSL function that generated the error.
156 I expect it's obvious most of the time.
157*/
158
159static PyObject *
160PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno)
161{
[391]162 PyObject *v;
163 char buf[2048];
164 char *errstr;
165 int err;
166 enum py_ssl_error p = PY_SSL_ERROR_NONE;
[2]167
[391]168 assert(ret <= 0);
[2]169
[391]170 if (obj->ssl != NULL) {
171 err = SSL_get_error(obj->ssl, ret);
[2]172
[391]173 switch (err) {
174 case SSL_ERROR_ZERO_RETURN:
175 errstr = "TLS/SSL connection has been closed";
176 p = PY_SSL_ERROR_ZERO_RETURN;
177 break;
178 case SSL_ERROR_WANT_READ:
179 errstr = "The operation did not complete (read)";
180 p = PY_SSL_ERROR_WANT_READ;
181 break;
182 case SSL_ERROR_WANT_WRITE:
183 p = PY_SSL_ERROR_WANT_WRITE;
184 errstr = "The operation did not complete (write)";
185 break;
186 case SSL_ERROR_WANT_X509_LOOKUP:
187 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
188 errstr = "The operation did not complete (X509 lookup)";
189 break;
190 case SSL_ERROR_WANT_CONNECT:
191 p = PY_SSL_ERROR_WANT_CONNECT;
192 errstr = "The operation did not complete (connect)";
193 break;
194 case SSL_ERROR_SYSCALL:
195 {
196 unsigned long e = ERR_get_error();
197 if (e == 0) {
198 if (ret == 0 || !obj->Socket) {
199 p = PY_SSL_ERROR_EOF;
200 errstr = "EOF occurred in violation of protocol";
201 } else if (ret == -1) {
202 /* underlying BIO reported an I/O error */
203 ERR_clear_error();
204 return obj->Socket->errorhandler();
205 } else { /* possible? */
206 p = PY_SSL_ERROR_SYSCALL;
207 errstr = "Some I/O error occurred";
208 }
209 } else {
210 p = PY_SSL_ERROR_SYSCALL;
211 /* XXX Protected by global interpreter lock */
212 errstr = ERR_error_string(e, NULL);
213 }
214 break;
215 }
216 case SSL_ERROR_SSL:
217 {
218 unsigned long e = ERR_get_error();
219 p = PY_SSL_ERROR_SSL;
220 if (e != 0)
221 /* XXX Protected by global interpreter lock */
222 errstr = ERR_error_string(e, NULL);
223 else { /* possible? */
224 errstr = "A failure in the SSL library occurred";
225 }
226 break;
227 }
228 default:
229 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
230 errstr = "Invalid error code";
231 }
232 } else {
233 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
234 }
235 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
236 ERR_clear_error();
237 v = Py_BuildValue("(is)", p, buf);
238 if (v != NULL) {
239 PyErr_SetObject(PySSLErrorObject, v);
240 Py_DECREF(v);
241 }
242 return NULL;
[2]243}
244
245static PyObject *
246_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
247
[391]248 char buf[2048];
249 PyObject *v;
[2]250
[391]251 if (errstr == NULL) {
252 errcode = ERR_peek_last_error();
253 errstr = ERR_error_string(errcode, NULL);
254 }
255 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
256 ERR_clear_error();
257 v = Py_BuildValue("(is)", errcode, buf);
258 if (v != NULL) {
259 PyErr_SetObject(PySSLErrorObject, v);
260 Py_DECREF(v);
261 }
262 return NULL;
[2]263}
264
265static PySSLObject *
266newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file,
[391]267 enum py_ssl_server_or_client socket_type,
268 enum py_ssl_cert_requirements certreq,
269 enum py_ssl_version proto_version,
270 char *cacerts_file, char *ciphers)
[2]271{
[391]272 PySSLObject *self;
273 char *errstr = NULL;
274 int ret;
275 int verification_mode;
[2]276
[391]277 self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */
278 if (self == NULL)
279 return NULL;
280 memset(self->server, '\0', sizeof(char) * X509_NAME_MAXLEN);
281 memset(self->issuer, '\0', sizeof(char) * X509_NAME_MAXLEN);
282 self->peer_cert = NULL;
283 self->ssl = NULL;
284 self->ctx = NULL;
285 self->Socket = NULL;
286 self->shutdown_seen_zero = 0;
[2]287
[391]288 /* Make sure the SSL error state is initialized */
289 (void) ERR_get_state();
290 ERR_clear_error();
[2]291
[391]292 if ((key_file && !cert_file) || (!key_file && cert_file)) {
293 errstr = ERRSTR("Both the key & certificate files "
294 "must be specified");
295 goto fail;
296 }
[2]297
[391]298 if ((socket_type == PY_SSL_SERVER) &&
299 ((key_file == NULL) || (cert_file == NULL))) {
300 errstr = ERRSTR("Both the key & certificate files "
301 "must be specified for server-side operation");
302 goto fail;
303 }
[2]304
[391]305 PySSL_BEGIN_ALLOW_THREADS
306 if (proto_version == PY_SSL_VERSION_TLS1)
307 self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */
308 else if (proto_version == PY_SSL_VERSION_SSL3)
309 self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */
310#ifndef OPENSSL_NO_SSL2
311 else if (proto_version == PY_SSL_VERSION_SSL2)
312 self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */
313#endif
314 else if (proto_version == PY_SSL_VERSION_SSL23)
315 self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
316 PySSL_END_ALLOW_THREADS
[2]317
[391]318 if (self->ctx == NULL) {
319 errstr = ERRSTR("Invalid SSL protocol variant specified.");
320 goto fail;
321 }
[2]322
[391]323 if (ciphers != NULL) {
324 ret = SSL_CTX_set_cipher_list(self->ctx, ciphers);
325 if (ret == 0) {
326 errstr = ERRSTR("No cipher can be selected.");
327 goto fail;
328 }
329 }
[2]330
[391]331 if (certreq != PY_SSL_CERT_NONE) {
332 if (cacerts_file == NULL) {
333 errstr = ERRSTR("No root certificates specified for "
334 "verification of other-side certificates.");
335 goto fail;
336 } else {
337 PySSL_BEGIN_ALLOW_THREADS
338 ret = SSL_CTX_load_verify_locations(self->ctx,
339 cacerts_file,
340 NULL);
341 PySSL_END_ALLOW_THREADS
342 if (ret != 1) {
343 _setSSLError(NULL, 0, __FILE__, __LINE__);
344 goto fail;
345 }
346 }
347 }
348 if (key_file) {
349 PySSL_BEGIN_ALLOW_THREADS
350 ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
351 SSL_FILETYPE_PEM);
352 PySSL_END_ALLOW_THREADS
353 if (ret != 1) {
354 _setSSLError(NULL, ret, __FILE__, __LINE__);
355 goto fail;
356 }
[2]357
[391]358 PySSL_BEGIN_ALLOW_THREADS
359 ret = SSL_CTX_use_certificate_chain_file(self->ctx,
360 cert_file);
361 PySSL_END_ALLOW_THREADS
362 if (ret != 1) {
363 /*
364 fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
365 ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
366 */
367 if (ERR_peek_last_error() != 0) {
368 _setSSLError(NULL, ret, __FILE__, __LINE__);
369 goto fail;
370 }
371 }
372 }
[2]373
[391]374 /* ssl compatibility */
375 SSL_CTX_set_options(self->ctx,
376 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
[2]377
[391]378 verification_mode = SSL_VERIFY_NONE;
379 if (certreq == PY_SSL_CERT_OPTIONAL)
380 verification_mode = SSL_VERIFY_PEER;
381 else if (certreq == PY_SSL_CERT_REQUIRED)
382 verification_mode = (SSL_VERIFY_PEER |
383 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
384 SSL_CTX_set_verify(self->ctx, verification_mode,
385 NULL); /* set verify lvl */
[2]386
[391]387 PySSL_BEGIN_ALLOW_THREADS
388 self->ssl = SSL_new(self->ctx); /* New ssl struct */
389 PySSL_END_ALLOW_THREADS
390 SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */
391#ifdef SSL_MODE_AUTO_RETRY
392 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
393#endif
[2]394
[391]395 /* If the socket is in non-blocking mode or timeout mode, set the BIO
396 * to non-blocking mode (blocking is the default)
397 */
398 if (Sock->sock_timeout >= 0.0) {
399 /* Set both the read and write BIO's to non-blocking mode */
400 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
401 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
402 }
[2]403
[391]404 PySSL_BEGIN_ALLOW_THREADS
405 if (socket_type == PY_SSL_CLIENT)
406 SSL_set_connect_state(self->ssl);
407 else
408 SSL_set_accept_state(self->ssl);
409 PySSL_END_ALLOW_THREADS
410
411 self->Socket = Sock;
412 Py_INCREF(self->Socket);
413 return self;
[2]414 fail:
[391]415 if (errstr)
416 PyErr_SetString(PySSLErrorObject, errstr);
417 Py_DECREF(self);
418 return NULL;
[2]419}
420
421static PyObject *
422PySSL_sslwrap(PyObject *self, PyObject *args)
423{
[391]424 PySocketSockObject *Sock;
425 int server_side = 0;
426 int verification_mode = PY_SSL_CERT_NONE;
427 int protocol = PY_SSL_VERSION_SSL23;
428 char *key_file = NULL;
429 char *cert_file = NULL;
430 char *cacerts_file = NULL;
431 char *ciphers = NULL;
[2]432
[391]433 if (!PyArg_ParseTuple(args, "O!i|zziizz:sslwrap",
434 PySocketModule.Sock_Type,
435 &Sock,
436 &server_side,
437 &key_file, &cert_file,
438 &verification_mode, &protocol,
439 &cacerts_file, &ciphers))
440 return NULL;
[2]441
[391]442 /*
443 fprintf(stderr,
444 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
445 "protocol %d, certs %p\n",
446 server_side, key_file, cert_file, verification_mode,
447 protocol, cacerts_file);
448 */
[2]449
[391]450 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
451 server_side, verification_mode,
452 protocol, cacerts_file,
453 ciphers);
[2]454}
455
456PyDoc_STRVAR(ssl_doc,
457"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
[391]458" cacertsfile, ciphers]) -> sslobject");
[2]459
460/* SSL object methods */
461
462static PyObject *PySSL_SSLdo_handshake(PySSLObject *self)
463{
[391]464 int ret;
465 int err;
466 int sockstate, nonblocking;
[2]467
[391]468 /* just in case the blocking state of the socket has been changed */
469 nonblocking = (self->Socket->sock_timeout >= 0.0);
470 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
471 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
[2]472
[391]473 /* Actually negotiate SSL connection */
474 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
475 do {
476 PySSL_BEGIN_ALLOW_THREADS
477 ret = SSL_do_handshake(self->ssl);
478 err = SSL_get_error(self->ssl, ret);
479 PySSL_END_ALLOW_THREADS
480 if(PyErr_CheckSignals()) {
481 return NULL;
482 }
483 if (err == SSL_ERROR_WANT_READ) {
484 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
485 } else if (err == SSL_ERROR_WANT_WRITE) {
486 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
487 } else {
488 sockstate = SOCKET_OPERATION_OK;
489 }
490 if (sockstate == SOCKET_HAS_TIMED_OUT) {
491 PyErr_SetString(PySSLErrorObject,
492 ERRSTR("The handshake operation timed out"));
493 return NULL;
494 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
495 PyErr_SetString(PySSLErrorObject,
496 ERRSTR("Underlying socket has been closed."));
497 return NULL;
498 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
499 PyErr_SetString(PySSLErrorObject,
500 ERRSTR("Underlying socket too large for select()."));
501 return NULL;
502 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
503 break;
504 }
505 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
506 if (ret < 1)
507 return PySSL_SetError(self, ret, __FILE__, __LINE__);
[2]508
[391]509 if (self->peer_cert)
510 X509_free (self->peer_cert);
511 PySSL_BEGIN_ALLOW_THREADS
512 if ((self->peer_cert = SSL_get_peer_certificate(self->ssl))) {
513 X509_NAME_oneline(X509_get_subject_name(self->peer_cert),
514 self->server, X509_NAME_MAXLEN);
515 X509_NAME_oneline(X509_get_issuer_name(self->peer_cert),
516 self->issuer, X509_NAME_MAXLEN);
517 }
518 PySSL_END_ALLOW_THREADS
519
520 Py_INCREF(Py_None);
521 return Py_None;
[2]522}
523
524static PyObject *
525PySSL_server(PySSLObject *self)
526{
[391]527 return PyString_FromString(self->server);
[2]528}
529
530static PyObject *
531PySSL_issuer(PySSLObject *self)
532{
[391]533 return PyString_FromString(self->issuer);
[2]534}
535
536static PyObject *
537_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
538
[391]539 char namebuf[X509_NAME_MAXLEN];
540 int buflen;
541 PyObject *name_obj;
542 PyObject *value_obj;
543 PyObject *attr;
544 unsigned char *valuebuf = NULL;
[2]545
[391]546 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
547 if (buflen < 0) {
548 _setSSLError(NULL, 0, __FILE__, __LINE__);
549 goto fail;
550 }
551 name_obj = PyString_FromStringAndSize(namebuf, buflen);
552 if (name_obj == NULL)
553 goto fail;
[2]554
[391]555 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
556 if (buflen < 0) {
557 _setSSLError(NULL, 0, __FILE__, __LINE__);
558 Py_DECREF(name_obj);
559 goto fail;
560 }
561 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
562 buflen, "strict");
563 OPENSSL_free(valuebuf);
564 if (value_obj == NULL) {
565 Py_DECREF(name_obj);
566 goto fail;
567 }
568 attr = PyTuple_New(2);
569 if (attr == NULL) {
570 Py_DECREF(name_obj);
571 Py_DECREF(value_obj);
572 goto fail;
573 }
574 PyTuple_SET_ITEM(attr, 0, name_obj);
575 PyTuple_SET_ITEM(attr, 1, value_obj);
576 return attr;
577
[2]578 fail:
[391]579 return NULL;
[2]580}
581
582static PyObject *
583_create_tuple_for_X509_NAME (X509_NAME *xname)
584{
[391]585 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
586 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
587 PyObject *rdnt;
588 PyObject *attr = NULL; /* tuple to hold an attribute */
589 int entry_count = X509_NAME_entry_count(xname);
590 X509_NAME_ENTRY *entry;
591 ASN1_OBJECT *name;
592 ASN1_STRING *value;
593 int index_counter;
594 int rdn_level = -1;
595 int retcode;
[2]596
[391]597 dn = PyList_New(0);
598 if (dn == NULL)
599 return NULL;
600 /* now create another tuple to hold the top-level RDN */
601 rdn = PyList_New(0);
602 if (rdn == NULL)
603 goto fail0;
[2]604
[391]605 for (index_counter = 0;
606 index_counter < entry_count;
607 index_counter++)
608 {
609 entry = X509_NAME_get_entry(xname, index_counter);
[2]610
[391]611 /* check to see if we've gotten to a new RDN */
612 if (rdn_level >= 0) {
613 if (rdn_level != entry->set) {
614 /* yes, new RDN */
615 /* add old RDN to DN */
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;
624 /* create new RDN */
625 rdn = PyList_New(0);
626 if (rdn == NULL)
627 goto fail0;
628 }
629 }
630 rdn_level = entry->set;
[2]631
[391]632 /* now add this attribute to the current RDN */
633 name = X509_NAME_ENTRY_get_object(entry);
634 value = X509_NAME_ENTRY_get_data(entry);
635 attr = _create_tuple_for_attribute(name, value);
636 /*
637 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
638 entry->set,
639 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
640 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
641 */
642 if (attr == NULL)
643 goto fail1;
644 retcode = PyList_Append(rdn, attr);
645 Py_DECREF(attr);
646 if (retcode < 0)
647 goto fail1;
648 }
649 /* now, there's typically a dangling RDN */
650 if (rdn != NULL) {
651 if (PyList_GET_SIZE(rdn) > 0) {
652 rdnt = PyList_AsTuple(rdn);
653 Py_DECREF(rdn);
654 if (rdnt == NULL)
655 goto fail0;
656 retcode = PyList_Append(dn, rdnt);
657 Py_DECREF(rdnt);
658 if (retcode < 0)
659 goto fail0;
660 }
661 else {
662 Py_DECREF(rdn);
663 }
664 }
[2]665
[391]666 /* convert list to tuple */
667 rdnt = PyList_AsTuple(dn);
668 Py_DECREF(dn);
669 if (rdnt == NULL)
670 return NULL;
671 return rdnt;
[2]672
673 fail1:
[391]674 Py_XDECREF(rdn);
[2]675
676 fail0:
[391]677 Py_XDECREF(dn);
678 return NULL;
[2]679}
680
681static PyObject *
682_get_peer_alt_names (X509 *certificate) {
683
[391]684 /* this code follows the procedure outlined in
685 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
686 function to extract the STACK_OF(GENERAL_NAME),
687 then iterates through the stack to add the
688 names. */
[2]689
[391]690 int i, j;
691 PyObject *peer_alt_names = Py_None;
692 PyObject *v = NULL, *t;
693 X509_EXTENSION *ext = NULL;
694 GENERAL_NAMES *names = NULL;
695 GENERAL_NAME *name;
696 const X509V3_EXT_METHOD *method;
697 BIO *biobuf = NULL;
698 char buf[2048];
699 char *vptr;
700 int len;
701 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
702#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
703 const unsigned char *p;
704#else
705 unsigned char *p;
706#endif
[2]707
[391]708 if (certificate == NULL)
709 return peer_alt_names;
[2]710
[391]711 /* get a memory buffer */
712 biobuf = BIO_new(BIO_s_mem());
[2]713
[391]714 i = -1;
715 while ((i = X509_get_ext_by_NID(
716 certificate, NID_subject_alt_name, i)) >= 0) {
[2]717
[391]718 if (peer_alt_names == Py_None) {
719 peer_alt_names = PyList_New(0);
720 if (peer_alt_names == NULL)
721 goto fail;
722 }
[2]723
[391]724 /* now decode the altName */
725 ext = X509_get_ext(certificate, i);
726 if(!(method = X509V3_EXT_get(ext))) {
727 PyErr_SetString(PySSLErrorObject,
728 ERRSTR("No method for internalizing subjectAltName!"));
729 goto fail;
730 }
[2]731
[391]732 p = ext->value->data;
733 if (method->it)
734 names = (GENERAL_NAMES*) (ASN1_item_d2i(NULL,
735 &p,
736 ext->value->length,
737 ASN1_ITEM_ptr(method->it)));
738 else
739 names = (GENERAL_NAMES*) (method->d2i(NULL,
740 &p,
741 ext->value->length));
[2]742
[391]743 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
744 /* get a rendering of each name in the set of names */
745 int gntype;
746 ASN1_STRING *as = NULL;
[2]747
[391]748 name = sk_GENERAL_NAME_value(names, j);
749 gntype = name->type;
750 switch (gntype) {
751 case GEN_DIRNAME:
752 /* we special-case DirName as a tuple of
753 tuples of attributes */
[2]754
[391]755 t = PyTuple_New(2);
756 if (t == NULL) {
757 goto fail;
758 }
[2]759
[391]760 v = PyString_FromString("DirName");
761 if (v == NULL) {
762 Py_DECREF(t);
763 goto fail;
764 }
765 PyTuple_SET_ITEM(t, 0, v);
[2]766
[391]767 v = _create_tuple_for_X509_NAME (name->d.dirn);
768 if (v == NULL) {
769 Py_DECREF(t);
770 goto fail;
771 }
772 PyTuple_SET_ITEM(t, 1, v);
773 break;
[2]774
[391]775 case GEN_EMAIL:
776 case GEN_DNS:
777 case GEN_URI:
778 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
779 correctly, CVE-2013-4238 */
780 t = PyTuple_New(2);
781 if (t == NULL)
782 goto fail;
783 switch (gntype) {
784 case GEN_EMAIL:
785 v = PyString_FromString("email");
786 as = name->d.rfc822Name;
787 break;
788 case GEN_DNS:
789 v = PyString_FromString("DNS");
790 as = name->d.dNSName;
791 break;
792 case GEN_URI:
793 v = PyString_FromString("URI");
794 as = name->d.uniformResourceIdentifier;
795 break;
796 }
797 if (v == NULL) {
798 Py_DECREF(t);
799 goto fail;
800 }
801 PyTuple_SET_ITEM(t, 0, v);
802 v = PyString_FromStringAndSize((char *)ASN1_STRING_data(as),
803 ASN1_STRING_length(as));
804 if (v == NULL) {
805 Py_DECREF(t);
806 goto fail;
807 }
808 PyTuple_SET_ITEM(t, 1, v);
809 break;
[2]810
[391]811 default:
812 /* for everything else, we use the OpenSSL print form */
813 switch (gntype) {
814 /* check for new general name type */
815 case GEN_OTHERNAME:
816 case GEN_X400:
817 case GEN_EDIPARTY:
818 case GEN_IPADD:
819 case GEN_RID:
820 break;
821 default:
822 if (PyErr_Warn(PyExc_RuntimeWarning,
823 "Unknown general name type") == -1) {
824 goto fail;
825 }
826 break;
827 }
828 (void) BIO_reset(biobuf);
829 GENERAL_NAME_print(biobuf, name);
830 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
831 if (len < 0) {
832 _setSSLError(NULL, 0, __FILE__, __LINE__);
833 goto fail;
834 }
835 vptr = strchr(buf, ':');
836 if (vptr == NULL)
837 goto fail;
838 t = PyTuple_New(2);
839 if (t == NULL)
840 goto fail;
841 v = PyString_FromStringAndSize(buf, (vptr - buf));
842 if (v == NULL) {
843 Py_DECREF(t);
844 goto fail;
845 }
846 PyTuple_SET_ITEM(t, 0, v);
847 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
848 if (v == NULL) {
849 Py_DECREF(t);
850 goto fail;
851 }
852 PyTuple_SET_ITEM(t, 1, v);
853 break;
854 }
[2]855
[391]856 /* and add that rendering to the list */
[2]857
[391]858 if (PyList_Append(peer_alt_names, t) < 0) {
859 Py_DECREF(t);
860 goto fail;
861 }
862 Py_DECREF(t);
863 }
864 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
865 }
866 BIO_free(biobuf);
867 if (peer_alt_names != Py_None) {
868 v = PyList_AsTuple(peer_alt_names);
869 Py_DECREF(peer_alt_names);
870 return v;
871 } else {
872 return peer_alt_names;
873 }
[2]874
[391]875
[2]876 fail:
[391]877 if (biobuf != NULL)
878 BIO_free(biobuf);
[2]879
[391]880 if (peer_alt_names != Py_None) {
881 Py_XDECREF(peer_alt_names);
882 }
[2]883
[391]884 return NULL;
[2]885}
886
887static PyObject *
888_decode_certificate (X509 *certificate, int verbose) {
889
[391]890 PyObject *retval = NULL;
891 BIO *biobuf = NULL;
892 PyObject *peer;
893 PyObject *peer_alt_names = NULL;
894 PyObject *issuer;
895 PyObject *version;
896 PyObject *sn_obj;
897 ASN1_INTEGER *serialNumber;
898 char buf[2048];
899 int len;
900 ASN1_TIME *notBefore, *notAfter;
901 PyObject *pnotBefore, *pnotAfter;
[2]902
[391]903 retval = PyDict_New();
904 if (retval == NULL)
905 return NULL;
[2]906
[391]907 peer = _create_tuple_for_X509_NAME(
908 X509_get_subject_name(certificate));
909 if (peer == NULL)
910 goto fail0;
911 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
912 Py_DECREF(peer);
913 goto fail0;
914 }
915 Py_DECREF(peer);
[2]916
[391]917 if (verbose) {
918 issuer = _create_tuple_for_X509_NAME(
919 X509_get_issuer_name(certificate));
920 if (issuer == NULL)
921 goto fail0;
922 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
923 Py_DECREF(issuer);
924 goto fail0;
925 }
926 Py_DECREF(issuer);
[2]927
[391]928 version = PyInt_FromLong(X509_get_version(certificate) + 1);
929 if (PyDict_SetItemString(retval, "version", version) < 0) {
930 Py_DECREF(version);
931 goto fail0;
932 }
933 Py_DECREF(version);
934 }
[2]935
[391]936 /* get a memory buffer */
937 biobuf = BIO_new(BIO_s_mem());
[2]938
[391]939 if (verbose) {
[2]940
[391]941 (void) BIO_reset(biobuf);
942 serialNumber = X509_get_serialNumber(certificate);
943 /* should not exceed 20 octets, 160 bits, so buf is big enough */
944 i2a_ASN1_INTEGER(biobuf, serialNumber);
945 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
946 if (len < 0) {
947 _setSSLError(NULL, 0, __FILE__, __LINE__);
948 goto fail1;
949 }
950 sn_obj = PyString_FromStringAndSize(buf, len);
951 if (sn_obj == NULL)
952 goto fail1;
953 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
954 Py_DECREF(sn_obj);
955 goto fail1;
956 }
957 Py_DECREF(sn_obj);
[2]958
[391]959 (void) BIO_reset(biobuf);
960 notBefore = X509_get_notBefore(certificate);
961 ASN1_TIME_print(biobuf, notBefore);
962 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
963 if (len < 0) {
964 _setSSLError(NULL, 0, __FILE__, __LINE__);
965 goto fail1;
966 }
967 pnotBefore = PyString_FromStringAndSize(buf, len);
968 if (pnotBefore == NULL)
969 goto fail1;
970 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
971 Py_DECREF(pnotBefore);
972 goto fail1;
973 }
974 Py_DECREF(pnotBefore);
975 }
[2]976
[391]977 (void) BIO_reset(biobuf);
978 notAfter = X509_get_notAfter(certificate);
979 ASN1_TIME_print(biobuf, notAfter);
980 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
981 if (len < 0) {
982 _setSSLError(NULL, 0, __FILE__, __LINE__);
983 goto fail1;
984 }
985 pnotAfter = PyString_FromStringAndSize(buf, len);
986 if (pnotAfter == NULL)
987 goto fail1;
988 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
989 Py_DECREF(pnotAfter);
990 goto fail1;
991 }
992 Py_DECREF(pnotAfter);
993
994 /* Now look for subjectAltName */
995
996 peer_alt_names = _get_peer_alt_names(certificate);
997 if (peer_alt_names == NULL)
998 goto fail1;
999 else if (peer_alt_names != Py_None) {
1000 if (PyDict_SetItemString(retval, "subjectAltName",
1001 peer_alt_names) < 0) {
1002 Py_DECREF(peer_alt_names);
1003 goto fail1;
1004 }
1005 Py_DECREF(peer_alt_names);
1006 }
1007
1008 BIO_free(biobuf);
1009 return retval;
1010
[2]1011 fail1:
[391]1012 if (biobuf != NULL)
1013 BIO_free(biobuf);
[2]1014 fail0:
[391]1015 Py_XDECREF(retval);
1016 return NULL;
[2]1017}
1018
1019
1020static PyObject *
1021PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1022
[391]1023 PyObject *retval = NULL;
1024 char *filename = NULL;
1025 X509 *x=NULL;
1026 BIO *cert;
1027 int verbose = 1;
[2]1028
[391]1029 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", &filename, &verbose))
1030 return NULL;
[2]1031
[391]1032 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1033 PyErr_SetString(PySSLErrorObject, "Can't malloc memory to read file");
1034 goto fail0;
1035 }
[2]1036
[391]1037 if (BIO_read_filename(cert,filename) <= 0) {
1038 PyErr_SetString(PySSLErrorObject, "Can't open file");
1039 goto fail0;
1040 }
[2]1041
[391]1042 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1043 if (x == NULL) {
1044 PyErr_SetString(PySSLErrorObject, "Error decoding PEM-encoded file");
1045 goto fail0;
1046 }
[2]1047
[391]1048 retval = _decode_certificate(x, verbose);
1049 X509_free(x);
[2]1050
1051 fail0:
[391]1052
1053 if (cert != NULL) BIO_free(cert);
1054 return retval;
[2]1055}
1056
1057
1058static PyObject *
1059PySSL_peercert(PySSLObject *self, PyObject *args)
1060{
[391]1061 PyObject *retval = NULL;
1062 int len;
1063 int verification;
1064 PyObject *binary_mode = Py_None;
1065 int b;
[2]1066
[391]1067 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1068 return NULL;
[2]1069
[391]1070 if (!self->peer_cert)
1071 Py_RETURN_NONE;
[2]1072
[391]1073 b = PyObject_IsTrue(binary_mode);
1074 if (b < 0)
1075 return NULL;
1076 if (b) {
1077 /* return cert in DER-encoded format */
[2]1078
[391]1079 unsigned char *bytes_buf = NULL;
[2]1080
[391]1081 bytes_buf = NULL;
1082 len = i2d_X509(self->peer_cert, &bytes_buf);
1083 if (len < 0) {
1084 PySSL_SetError(self, len, __FILE__, __LINE__);
1085 return NULL;
1086 }
1087 retval = PyString_FromStringAndSize((const char *) bytes_buf, len);
1088 OPENSSL_free(bytes_buf);
1089 return retval;
[2]1090
[391]1091 } else {
[2]1092
[391]1093 verification = SSL_CTX_get_verify_mode(self->ctx);
1094 if ((verification & SSL_VERIFY_PEER) == 0)
1095 return PyDict_New();
1096 else
1097 return _decode_certificate (self->peer_cert, 0);
1098 }
[2]1099}
1100
1101PyDoc_STRVAR(PySSL_peercert_doc,
1102"peer_certificate([der=False]) -> certificate\n\
1103\n\
1104Returns the certificate for the peer. If no certificate was provided,\n\
1105returns None. If a certificate was provided, but not validated, returns\n\
1106an empty dictionary. Otherwise returns a dict containing information\n\
1107about the peer certificate.\n\
1108\n\
1109If the optional argument is True, returns a DER-encoded copy of the\n\
1110peer certificate, or None if no certificate was provided. This will\n\
1111return the certificate even if it wasn't validated.");
1112
1113static PyObject *PySSL_cipher (PySSLObject *self) {
1114
[391]1115 PyObject *retval, *v;
1116 const SSL_CIPHER *current;
1117 char *cipher_name;
1118 char *cipher_protocol;
[2]1119
[391]1120 if (self->ssl == NULL)
1121 Py_RETURN_NONE;
1122 current = SSL_get_current_cipher(self->ssl);
1123 if (current == NULL)
1124 Py_RETURN_NONE;
[2]1125
[391]1126 retval = PyTuple_New(3);
1127 if (retval == NULL)
1128 return NULL;
[2]1129
[391]1130 cipher_name = (char *) SSL_CIPHER_get_name(current);
1131 if (cipher_name == NULL) {
1132 Py_INCREF(Py_None);
1133 PyTuple_SET_ITEM(retval, 0, Py_None);
1134 } else {
1135 v = PyString_FromString(cipher_name);
1136 if (v == NULL)
1137 goto fail0;
1138 PyTuple_SET_ITEM(retval, 0, v);
1139 }
1140 cipher_protocol = SSL_CIPHER_get_version(current);
1141 if (cipher_protocol == NULL) {
1142 Py_INCREF(Py_None);
1143 PyTuple_SET_ITEM(retval, 1, Py_None);
1144 } else {
1145 v = PyString_FromString(cipher_protocol);
1146 if (v == NULL)
1147 goto fail0;
1148 PyTuple_SET_ITEM(retval, 1, v);
1149 }
1150 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1151 if (v == NULL)
1152 goto fail0;
1153 PyTuple_SET_ITEM(retval, 2, v);
1154 return retval;
1155
[2]1156 fail0:
[391]1157 Py_DECREF(retval);
1158 return NULL;
[2]1159}
1160
1161static void PySSL_dealloc(PySSLObject *self)
1162{
[391]1163 if (self->peer_cert) /* Possible not to have one? */
1164 X509_free (self->peer_cert);
1165 if (self->ssl)
1166 SSL_free(self->ssl);
1167 if (self->ctx)
1168 SSL_CTX_free(self->ctx);
1169 Py_XDECREF(self->Socket);
1170 PyObject_Del(self);
[2]1171}
1172
1173/* If the socket has a timeout, do a select()/poll() on the socket.
1174 The argument writing indicates the direction.
1175 Returns one of the possibilities in the timeout_state enum (above).
1176 */
1177
1178static int
1179check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
1180{
[391]1181 fd_set fds;
1182 struct timeval tv;
1183 int rc;
[2]1184
[391]1185 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1186 if (s->sock_timeout < 0.0)
1187 return SOCKET_IS_BLOCKING;
1188 else if (s->sock_timeout == 0.0)
1189 return SOCKET_IS_NONBLOCKING;
[2]1190
[391]1191 /* Guard against closed socket */
1192 if (s->sock_fd < 0)
1193 return SOCKET_HAS_BEEN_CLOSED;
[2]1194
[391]1195 /* Prefer poll, if available, since you can poll() any fd
1196 * which can't be done with select(). */
[2]1197#ifdef HAVE_POLL
[391]1198 {
1199 struct pollfd pollfd;
1200 int timeout;
[2]1201
[391]1202 pollfd.fd = s->sock_fd;
1203 pollfd.events = writing ? POLLOUT : POLLIN;
[2]1204
[391]1205 /* s->sock_timeout is in seconds, timeout in ms */
1206 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1207 PySSL_BEGIN_ALLOW_THREADS
1208 rc = poll(&pollfd, 1, timeout);
1209 PySSL_END_ALLOW_THREADS
[2]1210
[391]1211 goto normal_return;
1212 }
[2]1213#endif
1214
[391]1215 /* Guard against socket too large for select*/
1216 if (!_PyIsSelectable_fd(s->sock_fd))
1217 return SOCKET_TOO_LARGE_FOR_SELECT;
[2]1218
[391]1219 /* Construct the arguments to select */
1220 tv.tv_sec = (int)s->sock_timeout;
1221 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1222 FD_ZERO(&fds);
1223 FD_SET(s->sock_fd, &fds);
[2]1224
[391]1225 /* See if the socket is ready */
1226 PySSL_BEGIN_ALLOW_THREADS
1227 if (writing)
1228 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1229 else
1230 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1231 PySSL_END_ALLOW_THREADS
[2]1232
1233#ifdef HAVE_POLL
1234normal_return:
1235#endif
[391]1236 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1237 (when we are able to write or when there's something to read) */
1238 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
[2]1239}
1240
1241static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1242{
[391]1243 Py_buffer buf;
1244 int len;
1245 int sockstate;
1246 int err;
1247 int nonblocking;
[2]1248
[391]1249 if (!PyArg_ParseTuple(args, "s*:write", &buf))
1250 return NULL;
[2]1251
[391]1252 if (buf.len > INT_MAX) {
1253 PyErr_Format(PyExc_OverflowError,
1254 "string longer than %d bytes", INT_MAX);
1255 goto error;
1256 }
[2]1257
[391]1258 /* just in case the blocking state of the socket has been changed */
1259 nonblocking = (self->Socket->sock_timeout >= 0.0);
1260 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1261 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1262
1263 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1264 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1265 PyErr_SetString(PySSLErrorObject,
1266 "The write operation timed out");
1267 goto error;
1268 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1269 PyErr_SetString(PySSLErrorObject,
1270 "Underlying socket has been closed.");
1271 goto error;
1272 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1273 PyErr_SetString(PySSLErrorObject,
1274 "Underlying socket too large for select().");
1275 goto error;
1276 }
1277 do {
1278 PySSL_BEGIN_ALLOW_THREADS
1279 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
1280 err = SSL_get_error(self->ssl, len);
1281 PySSL_END_ALLOW_THREADS
1282 if (PyErr_CheckSignals()) {
1283 goto error;
1284 }
1285 if (err == SSL_ERROR_WANT_READ) {
1286 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1287 } else if (err == SSL_ERROR_WANT_WRITE) {
1288 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1289 } else {
1290 sockstate = SOCKET_OPERATION_OK;
1291 }
1292 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1293 PyErr_SetString(PySSLErrorObject,
1294 "The write operation timed out");
1295 goto error;
1296 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1297 PyErr_SetString(PySSLErrorObject,
1298 "Underlying socket has been closed.");
1299 goto error;
1300 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1301 break;
1302 }
1303 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1304
1305 PyBuffer_Release(&buf);
1306 if (len > 0)
1307 return PyInt_FromLong(len);
1308 else
1309 return PySSL_SetError(self, len, __FILE__, __LINE__);
1310
1311error:
1312 PyBuffer_Release(&buf);
1313 return NULL;
[2]1314}
1315
1316PyDoc_STRVAR(PySSL_SSLwrite_doc,
1317"write(s) -> len\n\
1318\n\
1319Writes the string s into the SSL object. Returns the number\n\
1320of bytes written.");
1321
1322static PyObject *PySSL_SSLpending(PySSLObject *self)
1323{
[391]1324 int count = 0;
[2]1325
[391]1326 PySSL_BEGIN_ALLOW_THREADS
1327 count = SSL_pending(self->ssl);
1328 PySSL_END_ALLOW_THREADS
1329 if (count < 0)
1330 return PySSL_SetError(self, count, __FILE__, __LINE__);
1331 else
1332 return PyInt_FromLong(count);
[2]1333}
1334
1335PyDoc_STRVAR(PySSL_SSLpending_doc,
1336"pending() -> count\n\
1337\n\
1338Returns the number of already decrypted bytes available for read,\n\
1339pending on the connection.\n");
1340
1341static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1342{
[391]1343 PyObject *buf;
1344 int count = 0;
1345 int len = 1024;
1346 int sockstate;
1347 int err;
1348 int nonblocking;
[2]1349
[391]1350 if (!PyArg_ParseTuple(args, "|i:read", &len))
1351 return NULL;
[2]1352
[391]1353 if (!(buf = PyString_FromStringAndSize((char *) 0, len)))
1354 return NULL;
[2]1355
[391]1356 /* just in case the blocking state of the socket has been changed */
1357 nonblocking = (self->Socket->sock_timeout >= 0.0);
1358 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1359 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
[2]1360
[391]1361 /* first check if there are bytes ready to be read */
1362 PySSL_BEGIN_ALLOW_THREADS
1363 count = SSL_pending(self->ssl);
1364 PySSL_END_ALLOW_THREADS
[2]1365
[391]1366 if (!count) {
1367 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1368 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1369 PyErr_SetString(PySSLErrorObject,
1370 "The read operation timed out");
1371 Py_DECREF(buf);
1372 return NULL;
1373 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1374 PyErr_SetString(PySSLErrorObject,
1375 "Underlying socket too large for select().");
1376 Py_DECREF(buf);
1377 return NULL;
1378 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1379 if (SSL_get_shutdown(self->ssl) !=
1380 SSL_RECEIVED_SHUTDOWN)
1381 {
1382 Py_DECREF(buf);
1383 PyErr_SetString(PySSLErrorObject,
1384 "Socket closed without SSL shutdown handshake");
1385 return NULL;
1386 } else {
1387 /* should contain a zero-length string */
1388 _PyString_Resize(&buf, 0);
1389 return buf;
1390 }
1391 }
1392 }
1393 do {
1394 PySSL_BEGIN_ALLOW_THREADS
1395 count = SSL_read(self->ssl, PyString_AsString(buf), len);
1396 err = SSL_get_error(self->ssl, count);
1397 PySSL_END_ALLOW_THREADS
1398 if(PyErr_CheckSignals()) {
1399 Py_DECREF(buf);
1400 return NULL;
1401 }
1402 if (err == SSL_ERROR_WANT_READ) {
1403 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1404 } else if (err == SSL_ERROR_WANT_WRITE) {
1405 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1406 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1407 (SSL_get_shutdown(self->ssl) ==
1408 SSL_RECEIVED_SHUTDOWN))
1409 {
1410 _PyString_Resize(&buf, 0);
1411 return buf;
1412 } else {
1413 sockstate = SOCKET_OPERATION_OK;
1414 }
1415 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1416 PyErr_SetString(PySSLErrorObject,
1417 "The read operation timed out");
1418 Py_DECREF(buf);
1419 return NULL;
1420 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1421 break;
1422 }
1423 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1424 if (count <= 0) {
1425 Py_DECREF(buf);
1426 return PySSL_SetError(self, count, __FILE__, __LINE__);
1427 }
1428 if (count != len)
1429 _PyString_Resize(&buf, count);
1430 return buf;
[2]1431}
1432
1433PyDoc_STRVAR(PySSL_SSLread_doc,
1434"read([len]) -> string\n\
1435\n\
1436Read up to len bytes from the SSL socket.");
1437
1438static PyObject *PySSL_SSLshutdown(PySSLObject *self)
1439{
[391]1440 int err, ssl_err, sockstate, nonblocking;
1441 int zeros = 0;
[2]1442
[391]1443 /* Guard against closed socket */
1444 if (self->Socket->sock_fd < 0) {
1445 PyErr_SetString(PySSLErrorObject,
1446 "Underlying socket has been closed.");
1447 return NULL;
1448 }
[2]1449
[391]1450 /* Just in case the blocking state of the socket has been changed */
1451 nonblocking = (self->Socket->sock_timeout >= 0.0);
1452 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1453 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
[2]1454
[391]1455 while (1) {
1456 PySSL_BEGIN_ALLOW_THREADS
1457 /* Disable read-ahead so that unwrap can work correctly.
1458 * Otherwise OpenSSL might read in too much data,
1459 * eating clear text data that happens to be
1460 * transmitted after the SSL shutdown.
1461 * Should be safe to call repeatedly every time this
1462 * function is used and the shutdown_seen_zero != 0
1463 * condition is met.
1464 */
1465 if (self->shutdown_seen_zero)
1466 SSL_set_read_ahead(self->ssl, 0);
1467 err = SSL_shutdown(self->ssl);
1468 PySSL_END_ALLOW_THREADS
1469 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1470 if (err > 0)
1471 break;
1472 if (err == 0) {
1473 /* Don't loop endlessly; instead preserve legacy
1474 behaviour of trying SSL_shutdown() only twice.
1475 This looks necessary for OpenSSL < 0.9.8m */
1476 if (++zeros > 1)
1477 break;
1478 /* Shutdown was sent, now try receiving */
1479 self->shutdown_seen_zero = 1;
1480 continue;
1481 }
1482
1483 /* Possibly retry shutdown until timeout or failure */
1484 ssl_err = SSL_get_error(self->ssl, err);
1485 if (ssl_err == SSL_ERROR_WANT_READ)
1486 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1487 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1488 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1489 else
1490 break;
1491 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1492 if (ssl_err == SSL_ERROR_WANT_READ)
1493 PyErr_SetString(PySSLErrorObject,
1494 "The read operation timed out");
1495 else
1496 PyErr_SetString(PySSLErrorObject,
1497 "The write operation timed out");
1498 return NULL;
1499 }
1500 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1501 PyErr_SetString(PySSLErrorObject,
1502 "Underlying socket too large for select().");
1503 return NULL;
1504 }
1505 else if (sockstate != SOCKET_OPERATION_OK)
1506 /* Retain the SSL error code */
1507 break;
1508 }
1509
1510 if (err < 0)
1511 return PySSL_SetError(self, err, __FILE__, __LINE__);
1512 else {
1513 Py_INCREF(self->Socket);
1514 return (PyObject *) (self->Socket);
1515 }
[2]1516}
1517
1518PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1519"shutdown(s) -> socket\n\
1520\n\
1521Does the SSL shutdown handshake with the remote end, and returns\n\
1522the underlying socket object.");
1523
1524static PyMethodDef PySSLMethods[] = {
[391]1525 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1526 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1527 PySSL_SSLwrite_doc},
1528 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1529 PySSL_SSLread_doc},
1530 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1531 PySSL_SSLpending_doc},
1532 {"server", (PyCFunction)PySSL_server, METH_NOARGS},
1533 {"issuer", (PyCFunction)PySSL_issuer, METH_NOARGS},
1534 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1535 PySSL_peercert_doc},
1536 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1537 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1538 PySSL_SSLshutdown_doc},
1539 {NULL, NULL}
[2]1540};
1541
1542static PyObject *PySSL_getattr(PySSLObject *self, char *name)
1543{
[391]1544 return Py_FindMethod(PySSLMethods, (PyObject *)self, name);
[2]1545}
1546
1547static PyTypeObject PySSL_Type = {
[391]1548 PyVarObject_HEAD_INIT(NULL, 0)
1549 "ssl.SSLContext", /*tp_name*/
1550 sizeof(PySSLObject), /*tp_basicsize*/
1551 0, /*tp_itemsize*/
1552 /* methods */
1553 (destructor)PySSL_dealloc, /*tp_dealloc*/
1554 0, /*tp_print*/
1555 (getattrfunc)PySSL_getattr, /*tp_getattr*/
1556 0, /*tp_setattr*/
1557 0, /*tp_compare*/
1558 0, /*tp_repr*/
1559 0, /*tp_as_number*/
1560 0, /*tp_as_sequence*/
1561 0, /*tp_as_mapping*/
1562 0, /*tp_hash*/
[2]1563};
1564
1565#ifdef HAVE_OPENSSL_RAND
1566
1567/* helper routines for seeding the SSL PRNG */
1568static PyObject *
1569PySSL_RAND_add(PyObject *self, PyObject *args)
1570{
1571 char *buf;
1572 int len;
1573 double entropy;
1574
1575 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
[391]1576 return NULL;
[2]1577 RAND_add(buf, len, entropy);
1578 Py_INCREF(Py_None);
1579 return Py_None;
1580}
1581
1582PyDoc_STRVAR(PySSL_RAND_add_doc,
1583"RAND_add(string, entropy)\n\
1584\n\
1585Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
1586bound on the entropy contained in string. See RFC 1750.");
1587
1588static PyObject *
1589PySSL_RAND_status(PyObject *self)
1590{
1591 return PyInt_FromLong(RAND_status());
1592}
1593
1594PyDoc_STRVAR(PySSL_RAND_status_doc,
1595"RAND_status() -> 0 or 1\n\
1596\n\
1597Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1598It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1599using the ssl() function.");
1600
1601static PyObject *
1602PySSL_RAND_egd(PyObject *self, PyObject *arg)
1603{
1604 int bytes;
1605
1606 if (!PyString_Check(arg))
[391]1607 return PyErr_Format(PyExc_TypeError,
1608 "RAND_egd() expected string, found %s",
1609 Py_TYPE(arg)->tp_name);
[2]1610 bytes = RAND_egd(PyString_AS_STRING(arg));
1611 if (bytes == -1) {
[391]1612 PyErr_SetString(PySSLErrorObject,
1613 "EGD connection failed or EGD did not return "
1614 "enough data to seed the PRNG");
1615 return NULL;
[2]1616 }
1617 return PyInt_FromLong(bytes);
1618}
1619
1620PyDoc_STRVAR(PySSL_RAND_egd_doc,
1621"RAND_egd(path) -> bytes\n\
1622\n\
1623Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1624Returns number of bytes read. Raises SSLError if connection to EGD\n\
[391]1625fails or if it does not provide enough data to seed PRNG.");
[2]1626
[391]1627#endif /* HAVE_OPENSSL_RAND */
[2]1628
[391]1629
[2]1630/* List of functions exported by this module. */
1631
1632static PyMethodDef PySSL_methods[] = {
[391]1633 {"sslwrap", PySSL_sslwrap,
1634 METH_VARARGS, ssl_doc},
1635 {"_test_decode_cert", PySSL_test_decode_certificate,
1636 METH_VARARGS},
[2]1637#ifdef HAVE_OPENSSL_RAND
[391]1638 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1639 PySSL_RAND_add_doc},
1640 {"RAND_egd", PySSL_RAND_egd, METH_O,
1641 PySSL_RAND_egd_doc},
1642 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1643 PySSL_RAND_status_doc},
[2]1644#endif
[391]1645 {NULL, NULL} /* Sentinel */
[2]1646};
1647
1648
1649#ifdef WITH_THREAD
1650
1651/* an implementation of OpenSSL threading operations in terms
1652 of the Python C thread library */
1653
1654static PyThread_type_lock *_ssl_locks = NULL;
1655
[391]1656#if OPENSSL_VERSION_NUMBER >= 0x10000000
1657/* use new CRYPTO_THREADID API. */
1658static void
1659_ssl_threadid_callback(CRYPTO_THREADID *id)
1660{
1661 CRYPTO_THREADID_set_numeric(id,
1662 (unsigned long)PyThread_get_thread_ident());
[2]1663}
[391]1664#else
1665/* deprecated CRYPTO_set_id_callback() API. */
1666static unsigned long
1667_ssl_thread_id_function (void) {
1668 return PyThread_get_thread_ident();
1669}
1670#endif
[2]1671
1672static void _ssl_thread_locking_function (int mode, int n, const char *file, int line) {
[391]1673 /* this function is needed to perform locking on shared data
1674 structures. (Note that OpenSSL uses a number of global data
1675 structures that will be implicitly shared whenever multiple threads
1676 use OpenSSL.) Multi-threaded applications will crash at random if
1677 it is not set.
[2]1678
[391]1679 locking_function() must be able to handle up to CRYPTO_num_locks()
1680 different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and
1681 releases it otherwise.
[2]1682
[391]1683 file and line are the file number of the function setting the
1684 lock. They can be useful for debugging.
1685 */
[2]1686
[391]1687 if ((_ssl_locks == NULL) ||
1688 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1689 return;
[2]1690
[391]1691 if (mode & CRYPTO_LOCK) {
1692 PyThread_acquire_lock(_ssl_locks[n], 1);
1693 } else {
1694 PyThread_release_lock(_ssl_locks[n]);
1695 }
[2]1696}
1697
1698static int _setup_ssl_threads(void) {
1699
[391]1700 unsigned int i;
[2]1701
[391]1702 if (_ssl_locks == NULL) {
1703 _ssl_locks_count = CRYPTO_num_locks();
1704 _ssl_locks = (PyThread_type_lock *)
1705 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1706 if (_ssl_locks == NULL)
1707 return 0;
1708 memset(_ssl_locks, 0, sizeof(PyThread_type_lock) * _ssl_locks_count);
1709 for (i = 0; i < _ssl_locks_count; i++) {
1710 _ssl_locks[i] = PyThread_allocate_lock();
1711 if (_ssl_locks[i] == NULL) {
1712 unsigned int j;
1713 for (j = 0; j < i; j++) {
1714 PyThread_free_lock(_ssl_locks[j]);
1715 }
1716 free(_ssl_locks);
1717 return 0;
1718 }
1719 }
1720 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1721#if OPENSSL_VERSION_NUMBER >= 0x10000000
1722 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
1723#else
1724 CRYPTO_set_id_callback(_ssl_thread_id_function);
1725#endif
1726 }
1727 return 1;
[2]1728}
1729
[391]1730#endif /* def HAVE_THREAD */
[2]1731
1732PyDoc_STRVAR(module_doc,
1733"Implementation module for SSL socket operations. See the socket module\n\
1734for documentation.");
1735
1736PyMODINIT_FUNC
1737init_ssl(void)
1738{
[391]1739 PyObject *m, *d, *r;
1740 unsigned long libver;
1741 unsigned int major, minor, fix, patch, status;
[2]1742
[391]1743 Py_TYPE(&PySSL_Type) = &PyType_Type;
[2]1744
[391]1745 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
1746 if (m == NULL)
1747 return;
1748 d = PyModule_GetDict(m);
[2]1749
[391]1750 /* Load _socket module and its C API */
1751 if (PySocketModule_ImportModuleAndAPI())
1752 return;
[2]1753
[391]1754 /* Init OpenSSL */
1755 SSL_load_error_strings();
1756 SSL_library_init();
[2]1757#ifdef WITH_THREAD
[391]1758 /* note that this will start threading if not already started */
1759 if (!_setup_ssl_threads()) {
1760 return;
1761 }
[2]1762#endif
[391]1763 OpenSSL_add_all_algorithms();
[2]1764
[391]1765 /* Add symbols to module dict */
1766 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
1767 PySocketModule.error,
1768 NULL);
1769 if (PySSLErrorObject == NULL)
1770 return;
1771 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
1772 return;
1773 if (PyDict_SetItemString(d, "SSLType",
1774 (PyObject *)&PySSL_Type) != 0)
1775 return;
1776 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
1777 PY_SSL_ERROR_ZERO_RETURN);
1778 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
1779 PY_SSL_ERROR_WANT_READ);
1780 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
1781 PY_SSL_ERROR_WANT_WRITE);
1782 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
1783 PY_SSL_ERROR_WANT_X509_LOOKUP);
1784 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
1785 PY_SSL_ERROR_SYSCALL);
1786 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
1787 PY_SSL_ERROR_SSL);
1788 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1789 PY_SSL_ERROR_WANT_CONNECT);
1790 /* non ssl.h errorcodes */
1791 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1792 PY_SSL_ERROR_EOF);
1793 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1794 PY_SSL_ERROR_INVALID_ERROR_CODE);
1795 /* cert requirements */
1796 PyModule_AddIntConstant(m, "CERT_NONE",
1797 PY_SSL_CERT_NONE);
1798 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1799 PY_SSL_CERT_OPTIONAL);
1800 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1801 PY_SSL_CERT_REQUIRED);
[2]1802
[391]1803 /* protocol versions */
1804#ifndef OPENSSL_NO_SSL2
1805 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1806 PY_SSL_VERSION_SSL2);
1807#endif
1808 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1809 PY_SSL_VERSION_SSL3);
1810 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1811 PY_SSL_VERSION_SSL23);
1812 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1813 PY_SSL_VERSION_TLS1);
1814
1815 /* OpenSSL version */
1816 /* SSLeay() gives us the version of the library linked against,
1817 which could be different from the headers version.
1818 */
1819 libver = SSLeay();
1820 r = PyLong_FromUnsignedLong(libver);
1821 if (r == NULL)
1822 return;
1823 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
1824 return;
1825 status = libver & 0xF;
1826 libver >>= 4;
1827 patch = libver & 0xFF;
1828 libver >>= 8;
1829 fix = libver & 0xFF;
1830 libver >>= 8;
1831 minor = libver & 0xFF;
1832 libver >>= 8;
1833 major = libver & 0xFF;
1834 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
1835 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
1836 return;
1837 r = PyString_FromString(SSLeay_version(SSLEAY_VERSION));
1838 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
1839 return;
1840
[2]1841}
Note: See TracBrowser for help on using the repository browser.