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