Python-2.7.3/Modules/_ssl.c

No issues found

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