• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #define PY_SSIZE_T_CLEAN
18 #include "Python.h"
19 
20 #ifdef WITH_THREAD
21 #include "pythread.h"
22 
23 
24 #define PySSL_BEGIN_ALLOW_THREADS_S(save) \
25     do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
26 #define PySSL_END_ALLOW_THREADS_S(save) \
27     do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
28 #define PySSL_BEGIN_ALLOW_THREADS { \
29             PyThreadState *_save = NULL;  \
30             PySSL_BEGIN_ALLOW_THREADS_S(_save);
31 #define PySSL_BLOCK_THREADS     PySSL_END_ALLOW_THREADS_S(_save);
32 #define PySSL_UNBLOCK_THREADS   PySSL_BEGIN_ALLOW_THREADS_S(_save);
33 #define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
34 
35 #else   /* no WITH_THREAD */
36 
37 #define PySSL_BEGIN_ALLOW_THREADS_S(save)
38 #define PySSL_END_ALLOW_THREADS_S(save)
39 #define PySSL_BEGIN_ALLOW_THREADS
40 #define PySSL_BLOCK_THREADS
41 #define PySSL_UNBLOCK_THREADS
42 #define PySSL_END_ALLOW_THREADS
43 
44 #endif
45 
46 /* Include symbols from _socket module */
47 #include "socketmodule.h"
48 
49 #if defined(HAVE_POLL_H)
50 #include <poll.h>
51 #elif defined(HAVE_SYS_POLL_H)
52 #include <sys/poll.h>
53 #endif
54 
55 /* Don't warn about deprecated functions */
56 #ifdef __GNUC__
57 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
58 #endif
59 #ifdef __clang__
60 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
61 #endif
62 
63 /* Include OpenSSL header files */
64 #include "openssl/rsa.h"
65 #include "openssl/crypto.h"
66 #include "openssl/x509.h"
67 #include "openssl/x509v3.h"
68 #include "openssl/pem.h"
69 #include "openssl/ssl.h"
70 #include "openssl/err.h"
71 #include "openssl/rand.h"
72 
73 /* SSL error object */
74 static PyObject *PySSLErrorObject;
75 static PyObject *PySSLZeroReturnErrorObject;
76 static PyObject *PySSLWantReadErrorObject;
77 static PyObject *PySSLWantWriteErrorObject;
78 static PyObject *PySSLSyscallErrorObject;
79 static PyObject *PySSLEOFErrorObject;
80 
81 /* Error mappings */
82 static PyObject *err_codes_to_names;
83 static PyObject *err_names_to_codes;
84 static PyObject *lib_codes_to_names;
85 
86 struct py_ssl_error_code {
87     const char *mnemonic;
88     int library, reason;
89 };
90 struct py_ssl_library_code {
91     const char *library;
92     int code;
93 };
94 
95 /* Include generated data (error codes) */
96 #include "_ssl_data.h"
97 
98 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
99 #  define OPENSSL_VERSION_1_1 1
100 #endif
101 
102 /* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
103     http://www.openssl.org/news/changelog.html
104  */
105 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
106 # define HAVE_TLSv1_2 1
107 #else
108 # define HAVE_TLSv1_2 0
109 #endif
110 
111 /* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
112  * This includes the SSL_set_SSL_CTX() function.
113  */
114 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
115 # define HAVE_SNI 1
116 #else
117 # define HAVE_SNI 0
118 #endif
119 
120 /* ALPN added in OpenSSL 1.0.2 */
121 #if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
122 # define HAVE_ALPN
123 #endif
124 
125 #ifndef INVALID_SOCKET /* MS defines this */
126 #define INVALID_SOCKET (-1)
127 #endif
128 
129 #ifdef OPENSSL_VERSION_1_1
130 /* OpenSSL 1.1.0+ */
131 #ifndef OPENSSL_NO_SSL2
132 #define OPENSSL_NO_SSL2
133 #endif
134 #else /* OpenSSL < 1.1.0 */
135 #if defined(WITH_THREAD)
136 #define HAVE_OPENSSL_CRYPTO_LOCK
137 #endif
138 
139 #define TLS_method SSLv23_method
140 
X509_NAME_ENTRY_set(const X509_NAME_ENTRY * ne)141 static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
142 {
143     return ne->set;
144 }
145 
146 #ifndef OPENSSL_NO_COMP
COMP_get_type(const COMP_METHOD * meth)147 static int COMP_get_type(const COMP_METHOD *meth)
148 {
149     return meth->type;
150 }
151 #endif
152 
SSL_CTX_get_default_passwd_cb(SSL_CTX * ctx)153 static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
154 {
155     return ctx->default_passwd_callback;
156 }
157 
SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX * ctx)158 static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
159 {
160     return ctx->default_passwd_callback_userdata;
161 }
162 
X509_OBJECT_get_type(X509_OBJECT * x)163 static int X509_OBJECT_get_type(X509_OBJECT *x)
164 {
165     return x->type;
166 }
167 
X509_OBJECT_get0_X509(X509_OBJECT * x)168 static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
169 {
170     return x->data.x509;
171 }
172 
STACK_OF(X509_OBJECT)173 static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
174     return store->objs;
175 }
176 
X509_STORE_get0_param(X509_STORE * store)177 static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
178 {
179     return store->param;
180 }
181 #endif /* OpenSSL < 1.1.0 or LibreSSL */
182 
183 
184 enum py_ssl_error {
185     /* these mirror ssl.h */
186     PY_SSL_ERROR_NONE,
187     PY_SSL_ERROR_SSL,
188     PY_SSL_ERROR_WANT_READ,
189     PY_SSL_ERROR_WANT_WRITE,
190     PY_SSL_ERROR_WANT_X509_LOOKUP,
191     PY_SSL_ERROR_SYSCALL,     /* look at error stack/return value/errno */
192     PY_SSL_ERROR_ZERO_RETURN,
193     PY_SSL_ERROR_WANT_CONNECT,
194     /* start of non ssl.h errorcodes */
195     PY_SSL_ERROR_EOF,         /* special case of SSL_ERROR_SYSCALL */
196     PY_SSL_ERROR_NO_SOCKET,   /* socket has been GC'd */
197     PY_SSL_ERROR_INVALID_ERROR_CODE
198 };
199 
200 enum py_ssl_server_or_client {
201     PY_SSL_CLIENT,
202     PY_SSL_SERVER
203 };
204 
205 enum py_ssl_cert_requirements {
206     PY_SSL_CERT_NONE,
207     PY_SSL_CERT_OPTIONAL,
208     PY_SSL_CERT_REQUIRED
209 };
210 
211 enum py_ssl_version {
212     PY_SSL_VERSION_SSL2,
213     PY_SSL_VERSION_SSL3=1,
214     PY_SSL_VERSION_TLS,
215 #if HAVE_TLSv1_2
216     PY_SSL_VERSION_TLS1,
217     PY_SSL_VERSION_TLS1_1,
218     PY_SSL_VERSION_TLS1_2
219 #else
220     PY_SSL_VERSION_TLS1
221 #endif
222 };
223 
224 #ifdef WITH_THREAD
225 
226 /* serves as a flag to see whether we've initialized the SSL thread support. */
227 /* 0 means no, greater than 0 means yes */
228 
229 static unsigned int _ssl_locks_count = 0;
230 
231 #endif /* def WITH_THREAD */
232 
233 /* SSL socket object */
234 
235 #define X509_NAME_MAXLEN 256
236 
237 /* RAND_* APIs got added to OpenSSL in 0.9.5 */
238 #if OPENSSL_VERSION_NUMBER >= 0x0090500fL
239 # define HAVE_OPENSSL_RAND 1
240 #else
241 # undef HAVE_OPENSSL_RAND
242 #endif
243 
244 /* SSL_CTX_clear_options() and SSL_clear_options() were first added in
245  * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
246  * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
247 #if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
248 # define HAVE_SSL_CTX_CLEAR_OPTIONS
249 #else
250 # undef HAVE_SSL_CTX_CLEAR_OPTIONS
251 #endif
252 
253 /* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
254  * older SSL, but let's be safe */
255 #define PySSL_CB_MAXLEN 128
256 
257 /* SSL_get_finished got added to OpenSSL in 0.9.5 */
258 #if OPENSSL_VERSION_NUMBER >= 0x0090500fL
259 # define HAVE_OPENSSL_FINISHED 1
260 #else
261 # define HAVE_OPENSSL_FINISHED 0
262 #endif
263 
264 /* ECDH support got added to OpenSSL in 0.9.8 */
265 #if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
266 # define OPENSSL_NO_ECDH
267 #endif
268 
269 /* compression support got added to OpenSSL in 0.9.8 */
270 #if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
271 # define OPENSSL_NO_COMP
272 #endif
273 
274 /* X509_VERIFY_PARAM got added to OpenSSL in 0.9.8 */
275 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
276 # define HAVE_OPENSSL_VERIFY_PARAM
277 #endif
278 
279 
280 typedef struct {
281     PyObject_HEAD
282     SSL_CTX *ctx;
283 #ifdef OPENSSL_NPN_NEGOTIATED
284     unsigned char *npn_protocols;
285     int npn_protocols_len;
286 #endif
287 #ifdef HAVE_ALPN
288     unsigned char *alpn_protocols;
289     int alpn_protocols_len;
290 #endif
291 #ifndef OPENSSL_NO_TLSEXT
292     PyObject *set_hostname;
293 #endif
294     int check_hostname;
295 } PySSLContext;
296 
297 typedef struct {
298     PyObject_HEAD
299     PySocketSockObject *Socket;
300     PyObject *ssl_sock;
301     SSL *ssl;
302     PySSLContext *ctx; /* weakref to SSL context */
303     X509 *peer_cert;
304     char shutdown_seen_zero;
305     char handshake_done;
306     enum py_ssl_server_or_client socket_type;
307 } PySSLSocket;
308 
309 static PyTypeObject PySSLContext_Type;
310 static PyTypeObject PySSLSocket_Type;
311 
312 static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
313 static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
314 static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
315                                              int writing);
316 static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
317 static PyObject *PySSL_cipher(PySSLSocket *self);
318 
319 #define PySSLContext_Check(v)   (Py_TYPE(v) == &PySSLContext_Type)
320 #define PySSLSocket_Check(v)    (Py_TYPE(v) == &PySSLSocket_Type)
321 
322 typedef enum {
323     SOCKET_IS_NONBLOCKING,
324     SOCKET_IS_BLOCKING,
325     SOCKET_HAS_TIMED_OUT,
326     SOCKET_HAS_BEEN_CLOSED,
327     SOCKET_TOO_LARGE_FOR_SELECT,
328     SOCKET_OPERATION_OK
329 } timeout_state;
330 
331 /* Wrap error strings with filename and line # */
332 #define STRINGIFY1(x) #x
333 #define STRINGIFY2(x) STRINGIFY1(x)
334 #define ERRSTR1(x,y,z) (x ":" y ": " z)
335 #define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
336 
337 
338 /*
339  * SSL errors.
340  */
341 
342 PyDoc_STRVAR(SSLError_doc,
343 "An error occurred in the SSL implementation.");
344 
345 PyDoc_STRVAR(SSLZeroReturnError_doc,
346 "SSL/TLS session closed cleanly.");
347 
348 PyDoc_STRVAR(SSLWantReadError_doc,
349 "Non-blocking SSL socket needs to read more data\n"
350 "before the requested operation can be completed.");
351 
352 PyDoc_STRVAR(SSLWantWriteError_doc,
353 "Non-blocking SSL socket needs to write more data\n"
354 "before the requested operation can be completed.");
355 
356 PyDoc_STRVAR(SSLSyscallError_doc,
357 "System error when attempting SSL operation.");
358 
359 PyDoc_STRVAR(SSLEOFError_doc,
360 "SSL/TLS connection terminated abruptly.");
361 
362 
363 static PyObject *
SSLError_str(PyEnvironmentErrorObject * self)364 SSLError_str(PyEnvironmentErrorObject *self)
365 {
366     if (self->strerror != NULL) {
367         Py_INCREF(self->strerror);
368         return self->strerror;
369     }
370     else
371         return PyObject_Str(self->args);
372 }
373 
374 static void
fill_and_set_sslerror(PyObject * type,int ssl_errno,const char * errstr,int lineno,unsigned long errcode)375 fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
376                       int lineno, unsigned long errcode)
377 {
378     PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
379     PyObject *init_value, *msg, *key;
380 
381     if (errcode != 0) {
382         int lib, reason;
383 
384         lib = ERR_GET_LIB(errcode);
385         reason = ERR_GET_REASON(errcode);
386         key = Py_BuildValue("ii", lib, reason);
387         if (key == NULL)
388             goto fail;
389         reason_obj = PyDict_GetItem(err_codes_to_names, key);
390         Py_DECREF(key);
391         if (reason_obj == NULL) {
392             /* XXX if reason < 100, it might reflect a library number (!!) */
393             PyErr_Clear();
394         }
395         key = PyLong_FromLong(lib);
396         if (key == NULL)
397             goto fail;
398         lib_obj = PyDict_GetItem(lib_codes_to_names, key);
399         Py_DECREF(key);
400         if (lib_obj == NULL) {
401             PyErr_Clear();
402         }
403         if (errstr == NULL)
404             errstr = ERR_reason_error_string(errcode);
405     }
406     if (errstr == NULL)
407         errstr = "unknown error";
408 
409     if (reason_obj && lib_obj)
410         msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
411                                    lib_obj, reason_obj, errstr, lineno);
412     else if (lib_obj)
413         msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
414                                    lib_obj, errstr, lineno);
415     else
416         msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
417     if (msg == NULL)
418         goto fail;
419 
420     init_value = Py_BuildValue("iN", ssl_errno, msg);
421     if (init_value == NULL)
422         goto fail;
423 
424     err_value = PyObject_CallObject(type, init_value);
425     Py_DECREF(init_value);
426     if (err_value == NULL)
427         goto fail;
428 
429     if (reason_obj == NULL)
430         reason_obj = Py_None;
431     if (PyObject_SetAttrString(err_value, "reason", reason_obj))
432         goto fail;
433     if (lib_obj == NULL)
434         lib_obj = Py_None;
435     if (PyObject_SetAttrString(err_value, "library", lib_obj))
436         goto fail;
437     PyErr_SetObject(type, err_value);
438 fail:
439     Py_XDECREF(err_value);
440 }
441 
442 static PyObject *
PySSL_SetError(PySSLSocket * obj,int ret,char * filename,int lineno)443 PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
444 {
445     PyObject *type = PySSLErrorObject;
446     char *errstr = NULL;
447     int err;
448     enum py_ssl_error p = PY_SSL_ERROR_NONE;
449     unsigned long e = 0;
450 
451     assert(ret <= 0);
452     e = ERR_peek_last_error();
453 
454     if (obj->ssl != NULL) {
455         err = SSL_get_error(obj->ssl, ret);
456 
457         switch (err) {
458         case SSL_ERROR_ZERO_RETURN:
459             errstr = "TLS/SSL connection has been closed (EOF)";
460             type = PySSLZeroReturnErrorObject;
461             p = PY_SSL_ERROR_ZERO_RETURN;
462             break;
463         case SSL_ERROR_WANT_READ:
464             errstr = "The operation did not complete (read)";
465             type = PySSLWantReadErrorObject;
466             p = PY_SSL_ERROR_WANT_READ;
467             break;
468         case SSL_ERROR_WANT_WRITE:
469             p = PY_SSL_ERROR_WANT_WRITE;
470             type = PySSLWantWriteErrorObject;
471             errstr = "The operation did not complete (write)";
472             break;
473         case SSL_ERROR_WANT_X509_LOOKUP:
474             p = PY_SSL_ERROR_WANT_X509_LOOKUP;
475             errstr = "The operation did not complete (X509 lookup)";
476             break;
477         case SSL_ERROR_WANT_CONNECT:
478             p = PY_SSL_ERROR_WANT_CONNECT;
479             errstr = "The operation did not complete (connect)";
480             break;
481         case SSL_ERROR_SYSCALL:
482         {
483             if (e == 0) {
484                 PySocketSockObject *s = obj->Socket;
485                 if (ret == 0) {
486                     p = PY_SSL_ERROR_EOF;
487                     type = PySSLEOFErrorObject;
488                     errstr = "EOF occurred in violation of protocol";
489                 } else if (ret == -1) {
490                     /* underlying BIO reported an I/O error */
491                     Py_INCREF(s);
492                     ERR_clear_error();
493                     s->errorhandler();
494                     Py_DECREF(s);
495                     return NULL;
496                 } else { /* possible? */
497                     p = PY_SSL_ERROR_SYSCALL;
498                     type = PySSLSyscallErrorObject;
499                     errstr = "Some I/O error occurred";
500                 }
501             } else {
502                 p = PY_SSL_ERROR_SYSCALL;
503             }
504             break;
505         }
506         case SSL_ERROR_SSL:
507         {
508             p = PY_SSL_ERROR_SSL;
509             if (e == 0)
510                 /* possible? */
511                 errstr = "A failure in the SSL library occurred";
512             break;
513         }
514         default:
515             p = PY_SSL_ERROR_INVALID_ERROR_CODE;
516             errstr = "Invalid error code";
517         }
518     }
519     fill_and_set_sslerror(type, p, errstr, lineno, e);
520     ERR_clear_error();
521     return NULL;
522 }
523 
524 static PyObject *
_setSSLError(char * errstr,int errcode,char * filename,int lineno)525 _setSSLError (char *errstr, int errcode, char *filename, int lineno) {
526 
527     if (errstr == NULL)
528         errcode = ERR_peek_last_error();
529     else
530         errcode = 0;
531     fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
532     ERR_clear_error();
533     return NULL;
534 }
535 
536 /*
537  * SSL objects
538  */
539 
540 static PySSLSocket *
newPySSLSocket(PySSLContext * sslctx,PySocketSockObject * sock,enum py_ssl_server_or_client socket_type,char * server_hostname,PyObject * ssl_sock)541 newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
542                enum py_ssl_server_or_client socket_type,
543                char *server_hostname, PyObject *ssl_sock)
544 {
545     PySSLSocket *self;
546     SSL_CTX *ctx = sslctx->ctx;
547     long mode;
548 
549     self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
550     if (self == NULL)
551         return NULL;
552 
553     self->peer_cert = NULL;
554     self->ssl = NULL;
555     self->Socket = NULL;
556     self->ssl_sock = NULL;
557     self->ctx = sslctx;
558     self->shutdown_seen_zero = 0;
559     self->handshake_done = 0;
560     Py_INCREF(sslctx);
561 
562     /* Make sure the SSL error state is initialized */
563     (void) ERR_get_state();
564     ERR_clear_error();
565 
566     PySSL_BEGIN_ALLOW_THREADS
567     self->ssl = SSL_new(ctx);
568     PySSL_END_ALLOW_THREADS
569     SSL_set_app_data(self->ssl,self);
570     SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
571     mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
572 #ifdef SSL_MODE_AUTO_RETRY
573     mode |= SSL_MODE_AUTO_RETRY;
574 #endif
575     SSL_set_mode(self->ssl, mode);
576 
577 #if HAVE_SNI
578     if (server_hostname != NULL)
579         SSL_set_tlsext_host_name(self->ssl, server_hostname);
580 #endif
581 
582     /* If the socket is in non-blocking mode or timeout mode, set the BIO
583      * to non-blocking mode (blocking is the default)
584      */
585     if (sock->sock_timeout >= 0.0) {
586         BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
587         BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
588     }
589 
590     PySSL_BEGIN_ALLOW_THREADS
591     if (socket_type == PY_SSL_CLIENT)
592         SSL_set_connect_state(self->ssl);
593     else
594         SSL_set_accept_state(self->ssl);
595     PySSL_END_ALLOW_THREADS
596 
597     self->socket_type = socket_type;
598     self->Socket = sock;
599     Py_INCREF(self->Socket);
600     if (ssl_sock != Py_None) {
601         self->ssl_sock = PyWeakref_NewRef(ssl_sock, NULL);
602         if (self->ssl_sock == NULL) {
603             Py_DECREF(self);
604             return NULL;
605         }
606     }
607     return self;
608 }
609 
610 
611 /* SSL object methods */
612 
PySSL_SSLdo_handshake(PySSLSocket * self)613 static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
614 {
615     int ret;
616     int err;
617     int sockstate, nonblocking;
618     PySocketSockObject *sock = self->Socket;
619 
620     Py_INCREF(sock);
621 
622     /* just in case the blocking state of the socket has been changed */
623     nonblocking = (sock->sock_timeout >= 0.0);
624     BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
625     BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
626 
627     /* Actually negotiate SSL connection */
628     /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
629     do {
630         PySSL_BEGIN_ALLOW_THREADS
631         ret = SSL_do_handshake(self->ssl);
632         err = SSL_get_error(self->ssl, ret);
633         PySSL_END_ALLOW_THREADS
634         if (PyErr_CheckSignals())
635             goto error;
636         if (err == SSL_ERROR_WANT_READ) {
637             sockstate = check_socket_and_wait_for_timeout(sock, 0);
638         } else if (err == SSL_ERROR_WANT_WRITE) {
639             sockstate = check_socket_and_wait_for_timeout(sock, 1);
640         } else {
641             sockstate = SOCKET_OPERATION_OK;
642         }
643         if (sockstate == SOCKET_HAS_TIMED_OUT) {
644             PyErr_SetString(PySSLErrorObject,
645                             ERRSTR("The handshake operation timed out"));
646             goto error;
647         } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
648             PyErr_SetString(PySSLErrorObject,
649                             ERRSTR("Underlying socket has been closed."));
650             goto error;
651         } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
652             PyErr_SetString(PySSLErrorObject,
653                             ERRSTR("Underlying socket too large for select()."));
654             goto error;
655         } else if (sockstate == SOCKET_IS_NONBLOCKING) {
656             break;
657         }
658     } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
659     Py_DECREF(sock);
660     if (ret < 1)
661         return PySSL_SetError(self, ret, __FILE__, __LINE__);
662 
663     if (self->peer_cert)
664         X509_free (self->peer_cert);
665     PySSL_BEGIN_ALLOW_THREADS
666     self->peer_cert = SSL_get_peer_certificate(self->ssl);
667     PySSL_END_ALLOW_THREADS
668     self->handshake_done = 1;
669 
670     Py_INCREF(Py_None);
671     return Py_None;
672 
673 error:
674     Py_DECREF(sock);
675     return NULL;
676 }
677 
678 static PyObject *
_create_tuple_for_attribute(ASN1_OBJECT * name,ASN1_STRING * value)679 _create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
680 
681     char namebuf[X509_NAME_MAXLEN];
682     int buflen;
683     PyObject *name_obj;
684     PyObject *value_obj;
685     PyObject *attr;
686     unsigned char *valuebuf = NULL;
687 
688     buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
689     if (buflen < 0) {
690         _setSSLError(NULL, 0, __FILE__, __LINE__);
691         goto fail;
692     }
693     name_obj = PyString_FromStringAndSize(namebuf, buflen);
694     if (name_obj == NULL)
695         goto fail;
696 
697     buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
698     if (buflen < 0) {
699         _setSSLError(NULL, 0, __FILE__, __LINE__);
700         Py_DECREF(name_obj);
701         goto fail;
702     }
703     value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
704                                      buflen, "strict");
705     OPENSSL_free(valuebuf);
706     if (value_obj == NULL) {
707         Py_DECREF(name_obj);
708         goto fail;
709     }
710     attr = PyTuple_New(2);
711     if (attr == NULL) {
712         Py_DECREF(name_obj);
713         Py_DECREF(value_obj);
714         goto fail;
715     }
716     PyTuple_SET_ITEM(attr, 0, name_obj);
717     PyTuple_SET_ITEM(attr, 1, value_obj);
718     return attr;
719 
720   fail:
721     return NULL;
722 }
723 
724 static PyObject *
_create_tuple_for_X509_NAME(X509_NAME * xname)725 _create_tuple_for_X509_NAME (X509_NAME *xname)
726 {
727     PyObject *dn = NULL;    /* tuple which represents the "distinguished name" */
728     PyObject *rdn = NULL;   /* tuple to hold a "relative distinguished name" */
729     PyObject *rdnt;
730     PyObject *attr = NULL;   /* tuple to hold an attribute */
731     int entry_count = X509_NAME_entry_count(xname);
732     X509_NAME_ENTRY *entry;
733     ASN1_OBJECT *name;
734     ASN1_STRING *value;
735     int index_counter;
736     int rdn_level = -1;
737     int retcode;
738 
739     dn = PyList_New(0);
740     if (dn == NULL)
741         return NULL;
742     /* now create another tuple to hold the top-level RDN */
743     rdn = PyList_New(0);
744     if (rdn == NULL)
745         goto fail0;
746 
747     for (index_counter = 0;
748          index_counter < entry_count;
749          index_counter++)
750     {
751         entry = X509_NAME_get_entry(xname, index_counter);
752 
753         /* check to see if we've gotten to a new RDN */
754         if (rdn_level >= 0) {
755             if (rdn_level != X509_NAME_ENTRY_set(entry)) {
756                 /* yes, new RDN */
757                 /* add old RDN to DN */
758                 rdnt = PyList_AsTuple(rdn);
759                 Py_DECREF(rdn);
760                 if (rdnt == NULL)
761                     goto fail0;
762                 retcode = PyList_Append(dn, rdnt);
763                 Py_DECREF(rdnt);
764                 if (retcode < 0)
765                     goto fail0;
766                 /* create new RDN */
767                 rdn = PyList_New(0);
768                 if (rdn == NULL)
769                     goto fail0;
770             }
771         }
772         rdn_level = X509_NAME_ENTRY_set(entry);
773 
774         /* now add this attribute to the current RDN */
775         name = X509_NAME_ENTRY_get_object(entry);
776         value = X509_NAME_ENTRY_get_data(entry);
777         attr = _create_tuple_for_attribute(name, value);
778         /*
779         fprintf(stderr, "RDN level %d, attribute %s: %s\n",
780             entry->set,
781             PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
782             PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
783         */
784         if (attr == NULL)
785             goto fail1;
786         retcode = PyList_Append(rdn, attr);
787         Py_DECREF(attr);
788         if (retcode < 0)
789             goto fail1;
790     }
791     /* now, there's typically a dangling RDN */
792     if (rdn != NULL) {
793         if (PyList_GET_SIZE(rdn) > 0) {
794             rdnt = PyList_AsTuple(rdn);
795             Py_DECREF(rdn);
796             if (rdnt == NULL)
797                 goto fail0;
798             retcode = PyList_Append(dn, rdnt);
799             Py_DECREF(rdnt);
800             if (retcode < 0)
801                 goto fail0;
802         }
803         else {
804             Py_DECREF(rdn);
805         }
806     }
807 
808     /* convert list to tuple */
809     rdnt = PyList_AsTuple(dn);
810     Py_DECREF(dn);
811     if (rdnt == NULL)
812         return NULL;
813     return rdnt;
814 
815   fail1:
816     Py_XDECREF(rdn);
817 
818   fail0:
819     Py_XDECREF(dn);
820     return NULL;
821 }
822 
823 static PyObject *
_get_peer_alt_names(X509 * certificate)824 _get_peer_alt_names (X509 *certificate) {
825 
826     /* this code follows the procedure outlined in
827        OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
828        function to extract the STACK_OF(GENERAL_NAME),
829        then iterates through the stack to add the
830        names. */
831 
832     int i, j;
833     PyObject *peer_alt_names = Py_None;
834     PyObject *v = NULL, *t;
835     X509_EXTENSION *ext = NULL;
836     GENERAL_NAMES *names = NULL;
837     GENERAL_NAME *name;
838     const X509V3_EXT_METHOD *method;
839     BIO *biobuf = NULL;
840     char buf[2048];
841     char *vptr;
842     int len;
843     /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
844 #if OPENSSL_VERSION_NUMBER >= 0x009060dfL
845     const unsigned char *p;
846 #else
847     unsigned char *p;
848 #endif
849 
850     if (certificate == NULL)
851         return peer_alt_names;
852 
853     /* get a memory buffer */
854     biobuf = BIO_new(BIO_s_mem());
855 
856     i = -1;
857     while ((i = X509_get_ext_by_NID(
858                     certificate, NID_subject_alt_name, i)) >= 0) {
859 
860         if (peer_alt_names == Py_None) {
861             peer_alt_names = PyList_New(0);
862             if (peer_alt_names == NULL)
863                 goto fail;
864         }
865 
866         /* now decode the altName */
867         ext = X509_get_ext(certificate, i);
868         if(!(method = X509V3_EXT_get(ext))) {
869             PyErr_SetString
870               (PySSLErrorObject,
871                ERRSTR("No method for internalizing subjectAltName!"));
872             goto fail;
873         }
874 
875         p = X509_EXTENSION_get_data(ext)->data;
876         if (method->it)
877             names = (GENERAL_NAMES*)
878               (ASN1_item_d2i(NULL,
879                              &p,
880                              X509_EXTENSION_get_data(ext)->length,
881                              ASN1_ITEM_ptr(method->it)));
882         else
883             names = (GENERAL_NAMES*)
884               (method->d2i(NULL,
885                            &p,
886                            X509_EXTENSION_get_data(ext)->length));
887 
888         for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
889             /* get a rendering of each name in the set of names */
890             int gntype;
891             ASN1_STRING *as = NULL;
892 
893             name = sk_GENERAL_NAME_value(names, j);
894             gntype = name->type;
895             switch (gntype) {
896             case GEN_DIRNAME:
897                 /* we special-case DirName as a tuple of
898                    tuples of attributes */
899 
900                 t = PyTuple_New(2);
901                 if (t == NULL) {
902                     goto fail;
903                 }
904 
905                 v = PyString_FromString("DirName");
906                 if (v == NULL) {
907                     Py_DECREF(t);
908                     goto fail;
909                 }
910                 PyTuple_SET_ITEM(t, 0, v);
911 
912                 v = _create_tuple_for_X509_NAME (name->d.dirn);
913                 if (v == NULL) {
914                     Py_DECREF(t);
915                     goto fail;
916                 }
917                 PyTuple_SET_ITEM(t, 1, v);
918                 break;
919 
920             case GEN_EMAIL:
921             case GEN_DNS:
922             case GEN_URI:
923                 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
924                    correctly, CVE-2013-4238 */
925                 t = PyTuple_New(2);
926                 if (t == NULL)
927                     goto fail;
928                 switch (gntype) {
929                 case GEN_EMAIL:
930                     v = PyString_FromString("email");
931                     as = name->d.rfc822Name;
932                     break;
933                 case GEN_DNS:
934                     v = PyString_FromString("DNS");
935                     as = name->d.dNSName;
936                     break;
937                 case GEN_URI:
938                     v = PyString_FromString("URI");
939                     as = name->d.uniformResourceIdentifier;
940                     break;
941                 }
942                 if (v == NULL) {
943                     Py_DECREF(t);
944                     goto fail;
945                 }
946                 PyTuple_SET_ITEM(t, 0, v);
947                 v = PyString_FromStringAndSize((char *)ASN1_STRING_data(as),
948                                                ASN1_STRING_length(as));
949                 if (v == NULL) {
950                     Py_DECREF(t);
951                     goto fail;
952                 }
953                 PyTuple_SET_ITEM(t, 1, v);
954                 break;
955 
956             case GEN_RID:
957                 t = PyTuple_New(2);
958                 if (t == NULL)
959                     goto fail;
960 
961                 v = PyUnicode_FromString("Registered ID");
962                 if (v == NULL) {
963                     Py_DECREF(t);
964                     goto fail;
965                 }
966                 PyTuple_SET_ITEM(t, 0, v);
967 
968                 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
969                 if (len < 0) {
970                     Py_DECREF(t);
971                     _setSSLError(NULL, 0, __FILE__, __LINE__);
972                     goto fail;
973                 } else if (len >= (int)sizeof(buf)) {
974                     v = PyUnicode_FromString("<INVALID>");
975                 } else {
976                     v = PyUnicode_FromStringAndSize(buf, len);
977                 }
978                 if (v == NULL) {
979                     Py_DECREF(t);
980                     goto fail;
981                 }
982                 PyTuple_SET_ITEM(t, 1, v);
983                 break;
984 
985             default:
986                 /* for everything else, we use the OpenSSL print form */
987                 switch (gntype) {
988                     /* check for new general name type */
989                     case GEN_OTHERNAME:
990                     case GEN_X400:
991                     case GEN_EDIPARTY:
992                     case GEN_IPADD:
993                     case GEN_RID:
994                         break;
995                     default:
996                         if (PyErr_Warn(PyExc_RuntimeWarning,
997                                        "Unknown general name type") == -1) {
998                             goto fail;
999                         }
1000                         break;
1001                 }
1002                 (void) BIO_reset(biobuf);
1003                 GENERAL_NAME_print(biobuf, name);
1004                 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1005                 if (len < 0) {
1006                     _setSSLError(NULL, 0, __FILE__, __LINE__);
1007                     goto fail;
1008                 }
1009                 vptr = strchr(buf, ':');
1010                 if (vptr == NULL) {
1011                     PyErr_Format(PyExc_ValueError,
1012                                  "Invalid value %.200s",
1013                                  buf);
1014                     goto fail;
1015                 }
1016                 t = PyTuple_New(2);
1017                 if (t == NULL)
1018                     goto fail;
1019                 v = PyString_FromStringAndSize(buf, (vptr - buf));
1020                 if (v == NULL) {
1021                     Py_DECREF(t);
1022                     goto fail;
1023                 }
1024                 PyTuple_SET_ITEM(t, 0, v);
1025                 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
1026                 if (v == NULL) {
1027                     Py_DECREF(t);
1028                     goto fail;
1029                 }
1030                 PyTuple_SET_ITEM(t, 1, v);
1031                 break;
1032             }
1033 
1034             /* and add that rendering to the list */
1035 
1036             if (PyList_Append(peer_alt_names, t) < 0) {
1037                 Py_DECREF(t);
1038                 goto fail;
1039             }
1040             Py_DECREF(t);
1041         }
1042         sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
1043     }
1044     BIO_free(biobuf);
1045     if (peer_alt_names != Py_None) {
1046         v = PyList_AsTuple(peer_alt_names);
1047         Py_DECREF(peer_alt_names);
1048         return v;
1049     } else {
1050         return peer_alt_names;
1051     }
1052 
1053 
1054   fail:
1055     if (biobuf != NULL)
1056         BIO_free(biobuf);
1057 
1058     if (peer_alt_names != Py_None) {
1059         Py_XDECREF(peer_alt_names);
1060     }
1061 
1062     return NULL;
1063 }
1064 
1065 static PyObject *
_get_aia_uri(X509 * certificate,int nid)1066 _get_aia_uri(X509 *certificate, int nid) {
1067     PyObject *lst = NULL, *ostr = NULL;
1068     int i, result;
1069     AUTHORITY_INFO_ACCESS *info;
1070 
1071     info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
1072     if (info == NULL)
1073         return Py_None;
1074     if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1075         AUTHORITY_INFO_ACCESS_free(info);
1076         return Py_None;
1077     }
1078 
1079     if ((lst = PyList_New(0)) == NULL) {
1080         goto fail;
1081     }
1082 
1083     for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1084         ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1085         ASN1_IA5STRING *uri;
1086 
1087         if ((OBJ_obj2nid(ad->method) != nid) ||
1088                 (ad->location->type != GEN_URI)) {
1089             continue;
1090         }
1091         uri = ad->location->d.uniformResourceIdentifier;
1092         ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1093                                            uri->length);
1094         if (ostr == NULL) {
1095             goto fail;
1096         }
1097         result = PyList_Append(lst, ostr);
1098         Py_DECREF(ostr);
1099         if (result < 0) {
1100             goto fail;
1101         }
1102     }
1103     AUTHORITY_INFO_ACCESS_free(info);
1104 
1105     /* convert to tuple or None */
1106     if (PyList_Size(lst) == 0) {
1107         Py_DECREF(lst);
1108         return Py_None;
1109     } else {
1110         PyObject *tup;
1111         tup = PyList_AsTuple(lst);
1112         Py_DECREF(lst);
1113         return tup;
1114     }
1115 
1116   fail:
1117     AUTHORITY_INFO_ACCESS_free(info);
1118     Py_XDECREF(lst);
1119     return NULL;
1120 }
1121 
1122 static PyObject *
_get_crl_dp(X509 * certificate)1123 _get_crl_dp(X509 *certificate) {
1124     STACK_OF(DIST_POINT) *dps;
1125     int i, j;
1126     PyObject *lst, *res = NULL;
1127 
1128 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
1129     /* Calls x509v3_cache_extensions and sets up crldp */
1130     X509_check_ca(certificate);
1131 #endif
1132     dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
1133 
1134     if (dps == NULL)
1135         return Py_None;
1136 
1137     lst = PyList_New(0);
1138     if (lst == NULL)
1139         goto done;
1140 
1141     for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1142         DIST_POINT *dp;
1143         STACK_OF(GENERAL_NAME) *gns;
1144 
1145         dp = sk_DIST_POINT_value(dps, i);
1146         gns = dp->distpoint->name.fullname;
1147 
1148         for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1149             GENERAL_NAME *gn;
1150             ASN1_IA5STRING *uri;
1151             PyObject *ouri;
1152             int err;
1153 
1154             gn = sk_GENERAL_NAME_value(gns, j);
1155             if (gn->type != GEN_URI) {
1156                 continue;
1157             }
1158             uri = gn->d.uniformResourceIdentifier;
1159             ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1160                                                uri->length);
1161             if (ouri == NULL)
1162                 goto done;
1163 
1164             err = PyList_Append(lst, ouri);
1165             Py_DECREF(ouri);
1166             if (err < 0)
1167                 goto done;
1168         }
1169     }
1170 
1171     /* Convert to tuple. */
1172     res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1173 
1174   done:
1175     Py_XDECREF(lst);
1176 #if OPENSSL_VERSION_NUMBER < 0x10001000L
1177     sk_DIST_POINT_free(dps);
1178 #endif
1179     return res;
1180 }
1181 
1182 static PyObject *
_decode_certificate(X509 * certificate)1183 _decode_certificate(X509 *certificate) {
1184 
1185     PyObject *retval = NULL;
1186     BIO *biobuf = NULL;
1187     PyObject *peer;
1188     PyObject *peer_alt_names = NULL;
1189     PyObject *issuer;
1190     PyObject *version;
1191     PyObject *sn_obj;
1192     PyObject *obj;
1193     ASN1_INTEGER *serialNumber;
1194     char buf[2048];
1195     int len, result;
1196     ASN1_TIME *notBefore, *notAfter;
1197     PyObject *pnotBefore, *pnotAfter;
1198 
1199     retval = PyDict_New();
1200     if (retval == NULL)
1201         return NULL;
1202 
1203     peer = _create_tuple_for_X509_NAME(
1204         X509_get_subject_name(certificate));
1205     if (peer == NULL)
1206         goto fail0;
1207     if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1208         Py_DECREF(peer);
1209         goto fail0;
1210     }
1211     Py_DECREF(peer);
1212 
1213     issuer = _create_tuple_for_X509_NAME(
1214         X509_get_issuer_name(certificate));
1215     if (issuer == NULL)
1216         goto fail0;
1217     if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
1218         Py_DECREF(issuer);
1219         goto fail0;
1220     }
1221     Py_DECREF(issuer);
1222 
1223     version = PyLong_FromLong(X509_get_version(certificate) + 1);
1224     if (version == NULL)
1225         goto fail0;
1226     if (PyDict_SetItemString(retval, "version", version) < 0) {
1227         Py_DECREF(version);
1228         goto fail0;
1229     }
1230     Py_DECREF(version);
1231 
1232     /* get a memory buffer */
1233     biobuf = BIO_new(BIO_s_mem());
1234 
1235     (void) BIO_reset(biobuf);
1236     serialNumber = X509_get_serialNumber(certificate);
1237     /* should not exceed 20 octets, 160 bits, so buf is big enough */
1238     i2a_ASN1_INTEGER(biobuf, serialNumber);
1239     len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1240     if (len < 0) {
1241         _setSSLError(NULL, 0, __FILE__, __LINE__);
1242         goto fail1;
1243     }
1244     sn_obj = PyUnicode_FromStringAndSize(buf, len);
1245     if (sn_obj == NULL)
1246         goto fail1;
1247     if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1248         Py_DECREF(sn_obj);
1249         goto fail1;
1250     }
1251     Py_DECREF(sn_obj);
1252 
1253     (void) BIO_reset(biobuf);
1254     notBefore = X509_get_notBefore(certificate);
1255     ASN1_TIME_print(biobuf, notBefore);
1256     len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1257     if (len < 0) {
1258         _setSSLError(NULL, 0, __FILE__, __LINE__);
1259         goto fail1;
1260     }
1261     pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1262     if (pnotBefore == NULL)
1263         goto fail1;
1264     if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1265         Py_DECREF(pnotBefore);
1266         goto fail1;
1267     }
1268     Py_DECREF(pnotBefore);
1269 
1270     (void) BIO_reset(biobuf);
1271     notAfter = X509_get_notAfter(certificate);
1272     ASN1_TIME_print(biobuf, notAfter);
1273     len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1274     if (len < 0) {
1275         _setSSLError(NULL, 0, __FILE__, __LINE__);
1276         goto fail1;
1277     }
1278     pnotAfter = PyString_FromStringAndSize(buf, len);
1279     if (pnotAfter == NULL)
1280         goto fail1;
1281     if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1282         Py_DECREF(pnotAfter);
1283         goto fail1;
1284     }
1285     Py_DECREF(pnotAfter);
1286 
1287     /* Now look for subjectAltName */
1288 
1289     peer_alt_names = _get_peer_alt_names(certificate);
1290     if (peer_alt_names == NULL)
1291         goto fail1;
1292     else if (peer_alt_names != Py_None) {
1293         if (PyDict_SetItemString(retval, "subjectAltName",
1294                                  peer_alt_names) < 0) {
1295             Py_DECREF(peer_alt_names);
1296             goto fail1;
1297         }
1298         Py_DECREF(peer_alt_names);
1299     }
1300 
1301     /* Authority Information Access: OCSP URIs */
1302     obj = _get_aia_uri(certificate, NID_ad_OCSP);
1303     if (obj == NULL) {
1304         goto fail1;
1305     } else if (obj != Py_None) {
1306         result = PyDict_SetItemString(retval, "OCSP", obj);
1307         Py_DECREF(obj);
1308         if (result < 0) {
1309             goto fail1;
1310         }
1311     }
1312 
1313     obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1314     if (obj == NULL) {
1315         goto fail1;
1316     } else if (obj != Py_None) {
1317         result = PyDict_SetItemString(retval, "caIssuers", obj);
1318         Py_DECREF(obj);
1319         if (result < 0) {
1320             goto fail1;
1321         }
1322     }
1323 
1324     /* CDP (CRL distribution points) */
1325     obj = _get_crl_dp(certificate);
1326     if (obj == NULL) {
1327         goto fail1;
1328     } else if (obj != Py_None) {
1329         result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1330         Py_DECREF(obj);
1331         if (result < 0) {
1332             goto fail1;
1333         }
1334     }
1335 
1336     BIO_free(biobuf);
1337     return retval;
1338 
1339   fail1:
1340     if (biobuf != NULL)
1341         BIO_free(biobuf);
1342   fail0:
1343     Py_XDECREF(retval);
1344     return NULL;
1345 }
1346 
1347 static PyObject *
_certificate_to_der(X509 * certificate)1348 _certificate_to_der(X509 *certificate)
1349 {
1350     unsigned char *bytes_buf = NULL;
1351     int len;
1352     PyObject *retval;
1353 
1354     bytes_buf = NULL;
1355     len = i2d_X509(certificate, &bytes_buf);
1356     if (len < 0) {
1357         _setSSLError(NULL, 0, __FILE__, __LINE__);
1358         return NULL;
1359     }
1360     /* this is actually an immutable bytes sequence */
1361     retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1362     OPENSSL_free(bytes_buf);
1363     return retval;
1364 }
1365 
1366 static PyObject *
PySSL_test_decode_certificate(PyObject * mod,PyObject * args)1367 PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1368 
1369     PyObject *retval = NULL;
1370     char *filename = NULL;
1371     X509 *x=NULL;
1372     BIO *cert;
1373 
1374     if (!PyArg_ParseTuple(args, "s:test_decode_certificate", &filename))
1375         return NULL;
1376 
1377     if ((cert=BIO_new(BIO_s_file())) == NULL) {
1378         PyErr_SetString(PySSLErrorObject,
1379                         "Can't malloc memory to read file");
1380         goto fail0;
1381     }
1382 
1383     if (BIO_read_filename(cert,filename) <= 0) {
1384         PyErr_SetString(PySSLErrorObject,
1385                         "Can't open file");
1386         goto fail0;
1387     }
1388 
1389     x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1390     if (x == NULL) {
1391         PyErr_SetString(PySSLErrorObject,
1392                         "Error decoding PEM-encoded file");
1393         goto fail0;
1394     }
1395 
1396     retval = _decode_certificate(x);
1397     X509_free(x);
1398 
1399   fail0:
1400 
1401     if (cert != NULL) BIO_free(cert);
1402     return retval;
1403 }
1404 
1405 
1406 static PyObject *
PySSL_peercert(PySSLSocket * self,PyObject * args)1407 PySSL_peercert(PySSLSocket *self, PyObject *args)
1408 {
1409     int verification;
1410     PyObject *binary_mode = Py_None;
1411     int b;
1412 
1413     if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1414         return NULL;
1415 
1416     if (!self->handshake_done) {
1417         PyErr_SetString(PyExc_ValueError,
1418                         "handshake not done yet");
1419         return NULL;
1420     }
1421     if (!self->peer_cert)
1422         Py_RETURN_NONE;
1423 
1424     b = PyObject_IsTrue(binary_mode);
1425     if (b < 0)
1426         return NULL;
1427     if (b) {
1428         /* return cert in DER-encoded format */
1429         return _certificate_to_der(self->peer_cert);
1430     } else {
1431         verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
1432         if ((verification & SSL_VERIFY_PEER) == 0)
1433             return PyDict_New();
1434         else
1435             return _decode_certificate(self->peer_cert);
1436     }
1437 }
1438 
1439 PyDoc_STRVAR(PySSL_peercert_doc,
1440 "peer_certificate([der=False]) -> certificate\n\
1441 \n\
1442 Returns the certificate for the peer.  If no certificate was provided,\n\
1443 returns None.  If a certificate was provided, but not validated, returns\n\
1444 an empty dictionary.  Otherwise returns a dict containing information\n\
1445 about the peer certificate.\n\
1446 \n\
1447 If the optional argument is True, returns a DER-encoded copy of the\n\
1448 peer certificate, or None if no certificate was provided.  This will\n\
1449 return the certificate even if it wasn't validated.");
1450 
PySSL_cipher(PySSLSocket * self)1451 static PyObject *PySSL_cipher (PySSLSocket *self) {
1452 
1453     PyObject *retval, *v;
1454     const SSL_CIPHER *current;
1455     char *cipher_name;
1456     char *cipher_protocol;
1457 
1458     if (self->ssl == NULL)
1459         Py_RETURN_NONE;
1460     current = SSL_get_current_cipher(self->ssl);
1461     if (current == NULL)
1462         Py_RETURN_NONE;
1463 
1464     retval = PyTuple_New(3);
1465     if (retval == NULL)
1466         return NULL;
1467 
1468     cipher_name = (char *) SSL_CIPHER_get_name(current);
1469     if (cipher_name == NULL) {
1470         Py_INCREF(Py_None);
1471         PyTuple_SET_ITEM(retval, 0, Py_None);
1472     } else {
1473         v = PyString_FromString(cipher_name);
1474         if (v == NULL)
1475             goto fail0;
1476         PyTuple_SET_ITEM(retval, 0, v);
1477     }
1478     cipher_protocol = (char *) SSL_CIPHER_get_version(current);
1479     if (cipher_protocol == NULL) {
1480         Py_INCREF(Py_None);
1481         PyTuple_SET_ITEM(retval, 1, Py_None);
1482     } else {
1483         v = PyString_FromString(cipher_protocol);
1484         if (v == NULL)
1485             goto fail0;
1486         PyTuple_SET_ITEM(retval, 1, v);
1487     }
1488     v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1489     if (v == NULL)
1490         goto fail0;
1491     PyTuple_SET_ITEM(retval, 2, v);
1492     return retval;
1493 
1494   fail0:
1495     Py_DECREF(retval);
1496     return NULL;
1497 }
1498 
PySSL_version(PySSLSocket * self)1499 static PyObject *PySSL_version(PySSLSocket *self)
1500 {
1501     const char *version;
1502 
1503     if (self->ssl == NULL)
1504         Py_RETURN_NONE;
1505     version = SSL_get_version(self->ssl);
1506     if (!strcmp(version, "unknown"))
1507         Py_RETURN_NONE;
1508     return PyUnicode_FromString(version);
1509 }
1510 
1511 #ifdef OPENSSL_NPN_NEGOTIATED
PySSL_selected_npn_protocol(PySSLSocket * self)1512 static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1513     const unsigned char *out;
1514     unsigned int outlen;
1515 
1516     SSL_get0_next_proto_negotiated(self->ssl,
1517                                    &out, &outlen);
1518 
1519     if (out == NULL)
1520         Py_RETURN_NONE;
1521     return PyString_FromStringAndSize((char *)out, outlen);
1522 }
1523 #endif
1524 
1525 #ifdef HAVE_ALPN
PySSL_selected_alpn_protocol(PySSLSocket * self)1526 static PyObject *PySSL_selected_alpn_protocol(PySSLSocket *self) {
1527     const unsigned char *out;
1528     unsigned int outlen;
1529 
1530     SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1531 
1532     if (out == NULL)
1533         Py_RETURN_NONE;
1534     return PyString_FromStringAndSize((char *)out, outlen);
1535 }
1536 #endif
1537 
PySSL_compression(PySSLSocket * self)1538 static PyObject *PySSL_compression(PySSLSocket *self) {
1539 #ifdef OPENSSL_NO_COMP
1540     Py_RETURN_NONE;
1541 #else
1542     const COMP_METHOD *comp_method;
1543     const char *short_name;
1544 
1545     if (self->ssl == NULL)
1546         Py_RETURN_NONE;
1547     comp_method = SSL_get_current_compression(self->ssl);
1548     if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
1549         Py_RETURN_NONE;
1550     short_name = OBJ_nid2sn(COMP_get_type(comp_method));
1551     if (short_name == NULL)
1552         Py_RETURN_NONE;
1553     return PyBytes_FromString(short_name);
1554 #endif
1555 }
1556 
PySSL_get_context(PySSLSocket * self,void * closure)1557 static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1558     Py_INCREF(self->ctx);
1559     return self->ctx;
1560 }
1561 
PySSL_set_context(PySSLSocket * self,PyObject * value,void * closure)1562 static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1563                                    void *closure) {
1564 
1565     if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
1566 #if !HAVE_SNI
1567         PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1568                         "context is not supported by your OpenSSL library");
1569         return -1;
1570 #else
1571         Py_INCREF(value);
1572         Py_SETREF(self->ctx, (PySSLContext *)value);
1573         SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
1574 #endif
1575     } else {
1576         PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1577         return -1;
1578     }
1579 
1580     return 0;
1581 }
1582 
1583 PyDoc_STRVAR(PySSL_set_context_doc,
1584 "_setter_context(ctx)\n\
1585 \
1586 This changes the context associated with the SSLSocket. This is typically\n\
1587 used from within a callback function set by the set_servername_callback\n\
1588 on the SSLContext to change the certificate information associated with the\n\
1589 SSLSocket before the cryptographic exchange handshake messages\n");
1590 
1591 
1592 
PySSL_dealloc(PySSLSocket * self)1593 static void PySSL_dealloc(PySSLSocket *self)
1594 {
1595     if (self->peer_cert)        /* Possible not to have one? */
1596         X509_free (self->peer_cert);
1597     if (self->ssl)
1598         SSL_free(self->ssl);
1599     Py_XDECREF(self->Socket);
1600     Py_XDECREF(self->ssl_sock);
1601     Py_XDECREF(self->ctx);
1602     PyObject_Del(self);
1603 }
1604 
1605 /* If the socket has a timeout, do a select()/poll() on the socket.
1606    The argument writing indicates the direction.
1607    Returns one of the possibilities in the timeout_state enum (above).
1608  */
1609 
1610 static int
check_socket_and_wait_for_timeout(PySocketSockObject * s,int writing)1611 check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
1612 {
1613     fd_set fds;
1614     struct timeval tv;
1615     int rc;
1616 
1617     /* Nothing to do unless we're in timeout mode (not non-blocking) */
1618     if (s->sock_timeout < 0.0)
1619         return SOCKET_IS_BLOCKING;
1620     else if (s->sock_timeout == 0.0)
1621         return SOCKET_IS_NONBLOCKING;
1622 
1623     /* Guard against closed socket */
1624     if (s->sock_fd < 0)
1625         return SOCKET_HAS_BEEN_CLOSED;
1626 
1627     /* Prefer poll, if available, since you can poll() any fd
1628      * which can't be done with select(). */
1629 #ifdef HAVE_POLL
1630     {
1631         struct pollfd pollfd;
1632         int timeout;
1633 
1634         pollfd.fd = s->sock_fd;
1635         pollfd.events = writing ? POLLOUT : POLLIN;
1636 
1637         /* s->sock_timeout is in seconds, timeout in ms */
1638         timeout = (int)(s->sock_timeout * 1000 + 0.5);
1639         PySSL_BEGIN_ALLOW_THREADS
1640         rc = poll(&pollfd, 1, timeout);
1641         PySSL_END_ALLOW_THREADS
1642 
1643         goto normal_return;
1644     }
1645 #endif
1646 
1647     /* Guard against socket too large for select*/
1648     if (!_PyIsSelectable_fd(s->sock_fd))
1649         return SOCKET_TOO_LARGE_FOR_SELECT;
1650 
1651     /* Construct the arguments to select */
1652     tv.tv_sec = (int)s->sock_timeout;
1653     tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1654     FD_ZERO(&fds);
1655     FD_SET(s->sock_fd, &fds);
1656 
1657     /* See if the socket is ready */
1658     PySSL_BEGIN_ALLOW_THREADS
1659     if (writing)
1660         rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1661     else
1662         rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1663     PySSL_END_ALLOW_THREADS
1664 
1665 #ifdef HAVE_POLL
1666 normal_return:
1667 #endif
1668     /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1669        (when we are able to write or when there's something to read) */
1670     return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
1671 }
1672 
PySSL_SSLwrite(PySSLSocket * self,PyObject * args)1673 static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
1674 {
1675     Py_buffer buf;
1676     int len;
1677     int sockstate;
1678     int err;
1679     int nonblocking;
1680     PySocketSockObject *sock = self->Socket;
1681 
1682     Py_INCREF(sock);
1683 
1684     if (!PyArg_ParseTuple(args, "s*:write", &buf)) {
1685         Py_DECREF(sock);
1686         return NULL;
1687     }
1688 
1689     if (buf.len > INT_MAX) {
1690         PyErr_Format(PyExc_OverflowError,
1691                      "string longer than %d bytes", INT_MAX);
1692         goto error;
1693     }
1694 
1695     /* just in case the blocking state of the socket has been changed */
1696     nonblocking = (sock->sock_timeout >= 0.0);
1697     BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1698     BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1699 
1700     sockstate = check_socket_and_wait_for_timeout(sock, 1);
1701     if (sockstate == SOCKET_HAS_TIMED_OUT) {
1702         PyErr_SetString(PySSLErrorObject,
1703                         "The write operation timed out");
1704         goto error;
1705     } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1706         PyErr_SetString(PySSLErrorObject,
1707                         "Underlying socket has been closed.");
1708         goto error;
1709     } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1710         PyErr_SetString(PySSLErrorObject,
1711                         "Underlying socket too large for select().");
1712         goto error;
1713     }
1714     do {
1715         PySSL_BEGIN_ALLOW_THREADS
1716         len = SSL_write(self->ssl, buf.buf, (int)buf.len);
1717         err = SSL_get_error(self->ssl, len);
1718         PySSL_END_ALLOW_THREADS
1719         if (PyErr_CheckSignals()) {
1720             goto error;
1721         }
1722         if (err == SSL_ERROR_WANT_READ) {
1723             sockstate = check_socket_and_wait_for_timeout(sock, 0);
1724         } else if (err == SSL_ERROR_WANT_WRITE) {
1725             sockstate = check_socket_and_wait_for_timeout(sock, 1);
1726         } else {
1727             sockstate = SOCKET_OPERATION_OK;
1728         }
1729         if (sockstate == SOCKET_HAS_TIMED_OUT) {
1730             PyErr_SetString(PySSLErrorObject,
1731                             "The write operation timed out");
1732             goto error;
1733         } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1734             PyErr_SetString(PySSLErrorObject,
1735                             "Underlying socket has been closed.");
1736             goto error;
1737         } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1738             break;
1739         }
1740     } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1741 
1742     Py_DECREF(sock);
1743     PyBuffer_Release(&buf);
1744     if (len > 0)
1745         return PyInt_FromLong(len);
1746     else
1747         return PySSL_SetError(self, len, __FILE__, __LINE__);
1748 
1749 error:
1750     Py_DECREF(sock);
1751     PyBuffer_Release(&buf);
1752     return NULL;
1753 }
1754 
1755 PyDoc_STRVAR(PySSL_SSLwrite_doc,
1756 "write(s) -> len\n\
1757 \n\
1758 Writes the string s into the SSL object.  Returns the number\n\
1759 of bytes written.");
1760 
PySSL_SSLpending(PySSLSocket * self)1761 static PyObject *PySSL_SSLpending(PySSLSocket *self)
1762 {
1763     int count = 0;
1764 
1765     PySSL_BEGIN_ALLOW_THREADS
1766     count = SSL_pending(self->ssl);
1767     PySSL_END_ALLOW_THREADS
1768     if (count < 0)
1769         return PySSL_SetError(self, count, __FILE__, __LINE__);
1770     else
1771         return PyInt_FromLong(count);
1772 }
1773 
1774 PyDoc_STRVAR(PySSL_SSLpending_doc,
1775 "pending() -> count\n\
1776 \n\
1777 Returns the number of already decrypted bytes available for read,\n\
1778 pending on the connection.\n");
1779 
PySSL_SSLread(PySSLSocket * self,PyObject * args)1780 static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
1781 {
1782     PyObject *dest = NULL;
1783     Py_buffer buf;
1784     char *mem;
1785     int len, count;
1786     int buf_passed = 0;
1787     int sockstate;
1788     int err;
1789     int nonblocking;
1790     PySocketSockObject *sock = self->Socket;
1791 
1792     Py_INCREF(sock);
1793 
1794     buf.obj = NULL;
1795     buf.buf = NULL;
1796     if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
1797         goto error;
1798 
1799     if ((buf.buf == NULL) && (buf.obj == NULL)) {
1800         if (len < 0) {
1801             PyErr_SetString(PyExc_ValueError, "size should not be negative");
1802             goto error;
1803         }
1804         dest = PyBytes_FromStringAndSize(NULL, len);
1805         if (dest == NULL)
1806             goto error;
1807         if (len == 0) {
1808             Py_XDECREF(sock);
1809             return dest;
1810         }
1811         mem = PyBytes_AS_STRING(dest);
1812     }
1813     else {
1814         buf_passed = 1;
1815         mem = buf.buf;
1816         if (len <= 0 || len > buf.len) {
1817             len = (int) buf.len;
1818             if (buf.len != len) {
1819                 PyErr_SetString(PyExc_OverflowError,
1820                                 "maximum length can't fit in a C 'int'");
1821                 goto error;
1822             }
1823             if (len == 0) {
1824                 count = 0;
1825                 goto done;
1826             }
1827         }
1828     }
1829 
1830     /* just in case the blocking state of the socket has been changed */
1831     nonblocking = (sock->sock_timeout >= 0.0);
1832     BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1833     BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1834 
1835     do {
1836         PySSL_BEGIN_ALLOW_THREADS
1837         count = SSL_read(self->ssl, mem, len);
1838         err = SSL_get_error(self->ssl, count);
1839         PySSL_END_ALLOW_THREADS
1840         if (PyErr_CheckSignals())
1841             goto error;
1842         if (err == SSL_ERROR_WANT_READ) {
1843             sockstate = check_socket_and_wait_for_timeout(sock, 0);
1844         } else if (err == SSL_ERROR_WANT_WRITE) {
1845             sockstate = check_socket_and_wait_for_timeout(sock, 1);
1846         } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1847                    (SSL_get_shutdown(self->ssl) ==
1848                     SSL_RECEIVED_SHUTDOWN))
1849         {
1850             count = 0;
1851             goto done;
1852         } else {
1853             sockstate = SOCKET_OPERATION_OK;
1854         }
1855         if (sockstate == SOCKET_HAS_TIMED_OUT) {
1856             PyErr_SetString(PySSLErrorObject,
1857                             "The read operation timed out");
1858             goto error;
1859         } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1860             break;
1861         }
1862     } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1863     if (count <= 0) {
1864         PySSL_SetError(self, count, __FILE__, __LINE__);
1865         goto error;
1866     }
1867 
1868 done:
1869     Py_DECREF(sock);
1870     if (!buf_passed) {
1871         _PyBytes_Resize(&dest, count);
1872         return dest;
1873     }
1874     else {
1875         PyBuffer_Release(&buf);
1876         return PyLong_FromLong(count);
1877     }
1878 
1879 error:
1880     Py_DECREF(sock);
1881     if (!buf_passed)
1882         Py_XDECREF(dest);
1883     else
1884         PyBuffer_Release(&buf);
1885     return NULL;
1886 }
1887 
1888 PyDoc_STRVAR(PySSL_SSLread_doc,
1889 "read([len]) -> string\n\
1890 \n\
1891 Read up to len bytes from the SSL socket.");
1892 
PySSL_SSLshutdown(PySSLSocket * self)1893 static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
1894 {
1895     int err, ssl_err, sockstate, nonblocking;
1896     int zeros = 0;
1897     PySocketSockObject *sock = self->Socket;
1898 
1899     /* Guard against closed socket */
1900     if (sock->sock_fd < 0) {
1901         _setSSLError("Underlying socket connection gone",
1902                      PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1903         return NULL;
1904     }
1905     Py_INCREF(sock);
1906 
1907     /* Just in case the blocking state of the socket has been changed */
1908     nonblocking = (sock->sock_timeout >= 0.0);
1909     BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1910     BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1911 
1912     while (1) {
1913         PySSL_BEGIN_ALLOW_THREADS
1914         /* Disable read-ahead so that unwrap can work correctly.
1915          * Otherwise OpenSSL might read in too much data,
1916          * eating clear text data that happens to be
1917          * transmitted after the SSL shutdown.
1918          * Should be safe to call repeatedly every time this
1919          * function is used and the shutdown_seen_zero != 0
1920          * condition is met.
1921          */
1922         if (self->shutdown_seen_zero)
1923             SSL_set_read_ahead(self->ssl, 0);
1924         err = SSL_shutdown(self->ssl);
1925         PySSL_END_ALLOW_THREADS
1926         /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1927         if (err > 0)
1928             break;
1929         if (err == 0) {
1930             /* Don't loop endlessly; instead preserve legacy
1931                behaviour of trying SSL_shutdown() only twice.
1932                This looks necessary for OpenSSL < 0.9.8m */
1933             if (++zeros > 1)
1934                 break;
1935             /* Shutdown was sent, now try receiving */
1936             self->shutdown_seen_zero = 1;
1937             continue;
1938         }
1939 
1940         /* Possibly retry shutdown until timeout or failure */
1941         ssl_err = SSL_get_error(self->ssl, err);
1942         if (ssl_err == SSL_ERROR_WANT_READ)
1943             sockstate = check_socket_and_wait_for_timeout(sock, 0);
1944         else if (ssl_err == SSL_ERROR_WANT_WRITE)
1945             sockstate = check_socket_and_wait_for_timeout(sock, 1);
1946         else
1947             break;
1948         if (sockstate == SOCKET_HAS_TIMED_OUT) {
1949             if (ssl_err == SSL_ERROR_WANT_READ)
1950                 PyErr_SetString(PySSLErrorObject,
1951                                 "The read operation timed out");
1952             else
1953                 PyErr_SetString(PySSLErrorObject,
1954                                 "The write operation timed out");
1955             goto error;
1956         }
1957         else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1958             PyErr_SetString(PySSLErrorObject,
1959                             "Underlying socket too large for select().");
1960             goto error;
1961         }
1962         else if (sockstate != SOCKET_OPERATION_OK)
1963             /* Retain the SSL error code */
1964             break;
1965     }
1966 
1967     if (err < 0) {
1968         Py_DECREF(sock);
1969         return PySSL_SetError(self, err, __FILE__, __LINE__);
1970     }
1971     else
1972         /* It's already INCREF'ed */
1973         return (PyObject *) sock;
1974 
1975 error:
1976     Py_DECREF(sock);
1977     return NULL;
1978 }
1979 
1980 PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1981 "shutdown(s) -> socket\n\
1982 \n\
1983 Does the SSL shutdown handshake with the remote end, and returns\n\
1984 the underlying socket object.");
1985 
1986 #if HAVE_OPENSSL_FINISHED
1987 static PyObject *
PySSL_tls_unique_cb(PySSLSocket * self)1988 PySSL_tls_unique_cb(PySSLSocket *self)
1989 {
1990     PyObject *retval = NULL;
1991     char buf[PySSL_CB_MAXLEN];
1992     size_t len;
1993 
1994     if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1995         /* if session is resumed XOR we are the client */
1996         len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1997     }
1998     else {
1999         /* if a new session XOR we are the server */
2000         len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2001     }
2002 
2003     /* It cannot be negative in current OpenSSL version as of July 2011 */
2004     if (len == 0)
2005         Py_RETURN_NONE;
2006 
2007     retval = PyBytes_FromStringAndSize(buf, len);
2008 
2009     return retval;
2010 }
2011 
2012 PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
2013 "tls_unique_cb() -> bytes\n\
2014 \n\
2015 Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
2016 \n\
2017 If the TLS handshake is not yet complete, None is returned");
2018 
2019 #endif /* HAVE_OPENSSL_FINISHED */
2020 
2021 static PyGetSetDef ssl_getsetlist[] = {
2022     {"context", (getter) PySSL_get_context,
2023                 (setter) PySSL_set_context, PySSL_set_context_doc},
2024     {NULL},            /* sentinel */
2025 };
2026 
2027 static PyMethodDef PySSLMethods[] = {
2028     {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
2029     {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
2030      PySSL_SSLwrite_doc},
2031     {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
2032      PySSL_SSLread_doc},
2033     {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
2034      PySSL_SSLpending_doc},
2035     {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
2036      PySSL_peercert_doc},
2037     {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
2038     {"version", (PyCFunction)PySSL_version, METH_NOARGS},
2039 #ifdef OPENSSL_NPN_NEGOTIATED
2040     {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
2041 #endif
2042 #ifdef HAVE_ALPN
2043     {"selected_alpn_protocol", (PyCFunction)PySSL_selected_alpn_protocol, METH_NOARGS},
2044 #endif
2045     {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
2046     {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
2047      PySSL_SSLshutdown_doc},
2048 #if HAVE_OPENSSL_FINISHED
2049     {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
2050      PySSL_tls_unique_cb_doc},
2051 #endif
2052     {NULL, NULL}
2053 };
2054 
2055 static PyTypeObject PySSLSocket_Type = {
2056     PyVarObject_HEAD_INIT(NULL, 0)
2057     "_ssl._SSLSocket",                  /*tp_name*/
2058     sizeof(PySSLSocket),                /*tp_basicsize*/
2059     0,                                  /*tp_itemsize*/
2060     /* methods */
2061     (destructor)PySSL_dealloc,          /*tp_dealloc*/
2062     0,                                  /*tp_print*/
2063     0,                                  /*tp_getattr*/
2064     0,                                  /*tp_setattr*/
2065     0,                                  /*tp_reserved*/
2066     0,                                  /*tp_repr*/
2067     0,                                  /*tp_as_number*/
2068     0,                                  /*tp_as_sequence*/
2069     0,                                  /*tp_as_mapping*/
2070     0,                                  /*tp_hash*/
2071     0,                                  /*tp_call*/
2072     0,                                  /*tp_str*/
2073     0,                                  /*tp_getattro*/
2074     0,                                  /*tp_setattro*/
2075     0,                                  /*tp_as_buffer*/
2076     Py_TPFLAGS_DEFAULT,                 /*tp_flags*/
2077     0,                                  /*tp_doc*/
2078     0,                                  /*tp_traverse*/
2079     0,                                  /*tp_clear*/
2080     0,                                  /*tp_richcompare*/
2081     0,                                  /*tp_weaklistoffset*/
2082     0,                                  /*tp_iter*/
2083     0,                                  /*tp_iternext*/
2084     PySSLMethods,                       /*tp_methods*/
2085     0,                                  /*tp_members*/
2086     ssl_getsetlist,                     /*tp_getset*/
2087 };
2088 
2089 
2090 /*
2091  * _SSLContext objects
2092  */
2093 
2094 static PyObject *
context_new(PyTypeObject * type,PyObject * args,PyObject * kwds)2095 context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2096 {
2097     char *kwlist[] = {"protocol", NULL};
2098     PySSLContext *self;
2099     int proto_version = PY_SSL_VERSION_TLS;
2100     long options;
2101     SSL_CTX *ctx = NULL;
2102 
2103     if (!PyArg_ParseTupleAndKeywords(
2104         args, kwds, "i:_SSLContext", kwlist,
2105         &proto_version))
2106         return NULL;
2107 
2108     PySSL_BEGIN_ALLOW_THREADS
2109     if (proto_version == PY_SSL_VERSION_TLS1)
2110         ctx = SSL_CTX_new(TLSv1_method());
2111 #if HAVE_TLSv1_2
2112     else if (proto_version == PY_SSL_VERSION_TLS1_1)
2113         ctx = SSL_CTX_new(TLSv1_1_method());
2114     else if (proto_version == PY_SSL_VERSION_TLS1_2)
2115         ctx = SSL_CTX_new(TLSv1_2_method());
2116 #endif
2117 #ifndef OPENSSL_NO_SSL3
2118     else if (proto_version == PY_SSL_VERSION_SSL3)
2119         ctx = SSL_CTX_new(SSLv3_method());
2120 #endif
2121 #ifndef OPENSSL_NO_SSL2
2122     else if (proto_version == PY_SSL_VERSION_SSL2)
2123         ctx = SSL_CTX_new(SSLv2_method());
2124 #endif
2125     else if (proto_version == PY_SSL_VERSION_TLS)
2126         ctx = SSL_CTX_new(TLS_method());
2127     else
2128         proto_version = -1;
2129     PySSL_END_ALLOW_THREADS
2130 
2131     if (proto_version == -1) {
2132         PyErr_SetString(PyExc_ValueError,
2133                         "invalid protocol version");
2134         return NULL;
2135     }
2136     if (ctx == NULL) {
2137         PyErr_SetString(PySSLErrorObject,
2138                         "failed to allocate SSL context");
2139         return NULL;
2140     }
2141 
2142     assert(type != NULL && type->tp_alloc != NULL);
2143     self = (PySSLContext *) type->tp_alloc(type, 0);
2144     if (self == NULL) {
2145         SSL_CTX_free(ctx);
2146         return NULL;
2147     }
2148     self->ctx = ctx;
2149 #ifdef OPENSSL_NPN_NEGOTIATED
2150     self->npn_protocols = NULL;
2151 #endif
2152 #ifdef HAVE_ALPN
2153     self->alpn_protocols = NULL;
2154 #endif
2155 #ifndef OPENSSL_NO_TLSEXT
2156     self->set_hostname = NULL;
2157 #endif
2158     /* Don't check host name by default */
2159     self->check_hostname = 0;
2160     /* Defaults */
2161     SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
2162     options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2163     if (proto_version != PY_SSL_VERSION_SSL2)
2164         options |= SSL_OP_NO_SSLv2;
2165     if (proto_version != PY_SSL_VERSION_SSL3)
2166         options |= SSL_OP_NO_SSLv3;
2167     SSL_CTX_set_options(self->ctx, options);
2168 
2169 #ifndef OPENSSL_NO_ECDH
2170     /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2171        prime256v1 by default.  This is Apache mod_ssl's initialization
2172        policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2173      */
2174 #if defined(SSL_CTX_set_ecdh_auto) && !defined(OPENSSL_VERSION_1_1)
2175     SSL_CTX_set_ecdh_auto(self->ctx, 1);
2176 #else
2177     {
2178         EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2179         SSL_CTX_set_tmp_ecdh(self->ctx, key);
2180         EC_KEY_free(key);
2181     }
2182 #endif
2183 #endif
2184 
2185 #define SID_CTX "Python"
2186     SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2187                                    sizeof(SID_CTX));
2188 #undef SID_CTX
2189 
2190 #ifdef X509_V_FLAG_TRUSTED_FIRST
2191     {
2192         /* Improve trust chain building when cross-signed intermediate
2193            certificates are present. See https://bugs.python.org/issue23476. */
2194         X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2195         X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2196     }
2197 #endif
2198 
2199     return (PyObject *)self;
2200 }
2201 
2202 static int
context_traverse(PySSLContext * self,visitproc visit,void * arg)2203 context_traverse(PySSLContext *self, visitproc visit, void *arg)
2204 {
2205 #ifndef OPENSSL_NO_TLSEXT
2206     Py_VISIT(self->set_hostname);
2207 #endif
2208     return 0;
2209 }
2210 
2211 static int
context_clear(PySSLContext * self)2212 context_clear(PySSLContext *self)
2213 {
2214 #ifndef OPENSSL_NO_TLSEXT
2215     Py_CLEAR(self->set_hostname);
2216 #endif
2217     return 0;
2218 }
2219 
2220 static void
context_dealloc(PySSLContext * self)2221 context_dealloc(PySSLContext *self)
2222 {
2223     context_clear(self);
2224     SSL_CTX_free(self->ctx);
2225 #ifdef OPENSSL_NPN_NEGOTIATED
2226     PyMem_FREE(self->npn_protocols);
2227 #endif
2228 #ifdef HAVE_ALPN
2229     PyMem_FREE(self->alpn_protocols);
2230 #endif
2231     Py_TYPE(self)->tp_free(self);
2232 }
2233 
2234 static PyObject *
set_ciphers(PySSLContext * self,PyObject * args)2235 set_ciphers(PySSLContext *self, PyObject *args)
2236 {
2237     int ret;
2238     const char *cipherlist;
2239 
2240     if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2241         return NULL;
2242     ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2243     if (ret == 0) {
2244         /* Clearing the error queue is necessary on some OpenSSL versions,
2245            otherwise the error will be reported again when another SSL call
2246            is done. */
2247         ERR_clear_error();
2248         PyErr_SetString(PySSLErrorObject,
2249                         "No cipher can be selected.");
2250         return NULL;
2251     }
2252     Py_RETURN_NONE;
2253 }
2254 
2255 #ifdef OPENSSL_NPN_NEGOTIATED
2256 static int
do_protocol_selection(int alpn,unsigned char ** out,unsigned char * outlen,const unsigned char * server_protocols,unsigned int server_protocols_len,const unsigned char * client_protocols,unsigned int client_protocols_len)2257 do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2258                       const unsigned char *server_protocols, unsigned int server_protocols_len,
2259                       const unsigned char *client_protocols, unsigned int client_protocols_len)
2260 {
2261     int ret;
2262     if (client_protocols == NULL) {
2263         client_protocols = (unsigned char *)"";
2264         client_protocols_len = 0;
2265     }
2266     if (server_protocols == NULL) {
2267         server_protocols = (unsigned char *)"";
2268         server_protocols_len = 0;
2269     }
2270 
2271     ret = SSL_select_next_proto(out, outlen,
2272                                 server_protocols, server_protocols_len,
2273                                 client_protocols, client_protocols_len);
2274     if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2275         return SSL_TLSEXT_ERR_NOACK;
2276 
2277     return SSL_TLSEXT_ERR_OK;
2278 }
2279 
2280 /* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2281 static int
_advertiseNPN_cb(SSL * s,const unsigned char ** data,unsigned int * len,void * args)2282 _advertiseNPN_cb(SSL *s,
2283                  const unsigned char **data, unsigned int *len,
2284                  void *args)
2285 {
2286     PySSLContext *ssl_ctx = (PySSLContext *) args;
2287 
2288     if (ssl_ctx->npn_protocols == NULL) {
2289         *data = (unsigned char *)"";
2290         *len = 0;
2291     } else {
2292         *data = ssl_ctx->npn_protocols;
2293         *len = ssl_ctx->npn_protocols_len;
2294     }
2295 
2296     return SSL_TLSEXT_ERR_OK;
2297 }
2298 /* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2299 static int
_selectNPN_cb(SSL * s,unsigned char ** out,unsigned char * outlen,const unsigned char * server,unsigned int server_len,void * args)2300 _selectNPN_cb(SSL *s,
2301               unsigned char **out, unsigned char *outlen,
2302               const unsigned char *server, unsigned int server_len,
2303               void *args)
2304 {
2305     PySSLContext *ctx = (PySSLContext *)args;
2306     return do_protocol_selection(0, out, outlen, server, server_len,
2307                                  ctx->npn_protocols, ctx->npn_protocols_len);
2308 }
2309 #endif
2310 
2311 static PyObject *
_set_npn_protocols(PySSLContext * self,PyObject * args)2312 _set_npn_protocols(PySSLContext *self, PyObject *args)
2313 {
2314 #ifdef OPENSSL_NPN_NEGOTIATED
2315     Py_buffer protos;
2316 
2317     if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2318         return NULL;
2319 
2320     if (self->npn_protocols != NULL) {
2321         PyMem_Free(self->npn_protocols);
2322     }
2323 
2324     self->npn_protocols = PyMem_Malloc(protos.len);
2325     if (self->npn_protocols == NULL) {
2326         PyBuffer_Release(&protos);
2327         return PyErr_NoMemory();
2328     }
2329     memcpy(self->npn_protocols, protos.buf, protos.len);
2330     self->npn_protocols_len = (int) protos.len;
2331 
2332     /* set both server and client callbacks, because the context can
2333      * be used to create both types of sockets */
2334     SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2335                                           _advertiseNPN_cb,
2336                                           self);
2337     SSL_CTX_set_next_proto_select_cb(self->ctx,
2338                                      _selectNPN_cb,
2339                                      self);
2340 
2341     PyBuffer_Release(&protos);
2342     Py_RETURN_NONE;
2343 #else
2344     PyErr_SetString(PyExc_NotImplementedError,
2345                     "The NPN extension requires OpenSSL 1.0.1 or later.");
2346     return NULL;
2347 #endif
2348 }
2349 
2350 #ifdef HAVE_ALPN
2351 static int
_selectALPN_cb(SSL * s,const unsigned char ** out,unsigned char * outlen,const unsigned char * client_protocols,unsigned int client_protocols_len,void * args)2352 _selectALPN_cb(SSL *s,
2353               const unsigned char **out, unsigned char *outlen,
2354               const unsigned char *client_protocols, unsigned int client_protocols_len,
2355               void *args)
2356 {
2357     PySSLContext *ctx = (PySSLContext *)args;
2358     return do_protocol_selection(1, (unsigned char **)out, outlen,
2359                                  ctx->alpn_protocols, ctx->alpn_protocols_len,
2360                                  client_protocols, client_protocols_len);
2361 }
2362 #endif
2363 
2364 static PyObject *
_set_alpn_protocols(PySSLContext * self,PyObject * args)2365 _set_alpn_protocols(PySSLContext *self, PyObject *args)
2366 {
2367 #ifdef HAVE_ALPN
2368     Py_buffer protos;
2369 
2370     if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2371         return NULL;
2372 
2373     PyMem_FREE(self->alpn_protocols);
2374     self->alpn_protocols = PyMem_Malloc(protos.len);
2375     if (!self->alpn_protocols)
2376         return PyErr_NoMemory();
2377     memcpy(self->alpn_protocols, protos.buf, protos.len);
2378     self->alpn_protocols_len = protos.len;
2379     PyBuffer_Release(&protos);
2380 
2381     if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2382         return PyErr_NoMemory();
2383     SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2384 
2385     PyBuffer_Release(&protos);
2386     Py_RETURN_NONE;
2387 #else
2388     PyErr_SetString(PyExc_NotImplementedError,
2389                     "The ALPN extension requires OpenSSL 1.0.2 or later.");
2390     return NULL;
2391 #endif
2392 }
2393 
2394 static PyObject *
get_verify_mode(PySSLContext * self,void * c)2395 get_verify_mode(PySSLContext *self, void *c)
2396 {
2397     switch (SSL_CTX_get_verify_mode(self->ctx)) {
2398     case SSL_VERIFY_NONE:
2399         return PyLong_FromLong(PY_SSL_CERT_NONE);
2400     case SSL_VERIFY_PEER:
2401         return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2402     case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2403         return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2404     }
2405     PyErr_SetString(PySSLErrorObject,
2406                     "invalid return value from SSL_CTX_get_verify_mode");
2407     return NULL;
2408 }
2409 
2410 static int
set_verify_mode(PySSLContext * self,PyObject * arg,void * c)2411 set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2412 {
2413     int n, mode;
2414     if (!PyArg_Parse(arg, "i", &n))
2415         return -1;
2416     if (n == PY_SSL_CERT_NONE)
2417         mode = SSL_VERIFY_NONE;
2418     else if (n == PY_SSL_CERT_OPTIONAL)
2419         mode = SSL_VERIFY_PEER;
2420     else if (n == PY_SSL_CERT_REQUIRED)
2421         mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2422     else {
2423         PyErr_SetString(PyExc_ValueError,
2424                         "invalid value for verify_mode");
2425         return -1;
2426     }
2427     if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2428         PyErr_SetString(PyExc_ValueError,
2429                         "Cannot set verify_mode to CERT_NONE when "
2430                         "check_hostname is enabled.");
2431         return -1;
2432     }
2433     SSL_CTX_set_verify(self->ctx, mode, NULL);
2434     return 0;
2435 }
2436 
2437 #ifdef HAVE_OPENSSL_VERIFY_PARAM
2438 static PyObject *
get_verify_flags(PySSLContext * self,void * c)2439 get_verify_flags(PySSLContext *self, void *c)
2440 {
2441     X509_STORE *store;
2442     X509_VERIFY_PARAM *param;
2443     unsigned long flags;
2444 
2445     store = SSL_CTX_get_cert_store(self->ctx);
2446     param = X509_STORE_get0_param(store);
2447     flags = X509_VERIFY_PARAM_get_flags(param);
2448     return PyLong_FromUnsignedLong(flags);
2449 }
2450 
2451 static int
set_verify_flags(PySSLContext * self,PyObject * arg,void * c)2452 set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2453 {
2454     X509_STORE *store;
2455     X509_VERIFY_PARAM *param;
2456     unsigned long new_flags, flags, set, clear;
2457 
2458     if (!PyArg_Parse(arg, "k", &new_flags))
2459         return -1;
2460     store = SSL_CTX_get_cert_store(self->ctx);
2461     param = X509_STORE_get0_param(store);
2462     flags = X509_VERIFY_PARAM_get_flags(param);
2463     clear = flags & ~new_flags;
2464     set = ~flags & new_flags;
2465     if (clear) {
2466         if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
2467             _setSSLError(NULL, 0, __FILE__, __LINE__);
2468             return -1;
2469         }
2470     }
2471     if (set) {
2472         if (!X509_VERIFY_PARAM_set_flags(param, set)) {
2473             _setSSLError(NULL, 0, __FILE__, __LINE__);
2474             return -1;
2475         }
2476     }
2477     return 0;
2478 }
2479 #endif
2480 
2481 static PyObject *
get_options(PySSLContext * self,void * c)2482 get_options(PySSLContext *self, void *c)
2483 {
2484     return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2485 }
2486 
2487 static int
set_options(PySSLContext * self,PyObject * arg,void * c)2488 set_options(PySSLContext *self, PyObject *arg, void *c)
2489 {
2490     long new_opts, opts, set, clear;
2491     if (!PyArg_Parse(arg, "l", &new_opts))
2492         return -1;
2493     opts = SSL_CTX_get_options(self->ctx);
2494     clear = opts & ~new_opts;
2495     set = ~opts & new_opts;
2496     if (clear) {
2497 #ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2498         SSL_CTX_clear_options(self->ctx, clear);
2499 #else
2500         PyErr_SetString(PyExc_ValueError,
2501                         "can't clear options before OpenSSL 0.9.8m");
2502         return -1;
2503 #endif
2504     }
2505     if (set)
2506         SSL_CTX_set_options(self->ctx, set);
2507     return 0;
2508 }
2509 
2510 static PyObject *
get_check_hostname(PySSLContext * self,void * c)2511 get_check_hostname(PySSLContext *self, void *c)
2512 {
2513     return PyBool_FromLong(self->check_hostname);
2514 }
2515 
2516 static int
set_check_hostname(PySSLContext * self,PyObject * arg,void * c)2517 set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2518 {
2519     PyObject *py_check_hostname;
2520     int check_hostname;
2521     if (!PyArg_Parse(arg, "O", &py_check_hostname))
2522         return -1;
2523 
2524     check_hostname = PyObject_IsTrue(py_check_hostname);
2525     if (check_hostname < 0)
2526         return -1;
2527     if (check_hostname &&
2528             SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2529         PyErr_SetString(PyExc_ValueError,
2530                         "check_hostname needs a SSL context with either "
2531                         "CERT_OPTIONAL or CERT_REQUIRED");
2532         return -1;
2533     }
2534     self->check_hostname = check_hostname;
2535     return 0;
2536 }
2537 
2538 
2539 typedef struct {
2540     PyThreadState *thread_state;
2541     PyObject *callable;
2542     char *password;
2543     int size;
2544     int error;
2545 } _PySSLPasswordInfo;
2546 
2547 static int
_pwinfo_set(_PySSLPasswordInfo * pw_info,PyObject * password,const char * bad_type_error)2548 _pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2549             const char *bad_type_error)
2550 {
2551     /* Set the password and size fields of a _PySSLPasswordInfo struct
2552        from a unicode, bytes, or byte array object.
2553        The password field will be dynamically allocated and must be freed
2554        by the caller */
2555     PyObject *password_bytes = NULL;
2556     const char *data = NULL;
2557     Py_ssize_t size;
2558 
2559     if (PyUnicode_Check(password)) {
2560         password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2561         if (!password_bytes) {
2562             goto error;
2563         }
2564         data = PyBytes_AS_STRING(password_bytes);
2565         size = PyBytes_GET_SIZE(password_bytes);
2566     } else if (PyBytes_Check(password)) {
2567         data = PyBytes_AS_STRING(password);
2568         size = PyBytes_GET_SIZE(password);
2569     } else if (PyByteArray_Check(password)) {
2570         data = PyByteArray_AS_STRING(password);
2571         size = PyByteArray_GET_SIZE(password);
2572     } else {
2573         PyErr_SetString(PyExc_TypeError, bad_type_error);
2574         goto error;
2575     }
2576 
2577     if (size > (Py_ssize_t)INT_MAX) {
2578         PyErr_Format(PyExc_ValueError,
2579                      "password cannot be longer than %d bytes", INT_MAX);
2580         goto error;
2581     }
2582 
2583     PyMem_Free(pw_info->password);
2584     pw_info->password = PyMem_Malloc(size);
2585     if (!pw_info->password) {
2586         PyErr_SetString(PyExc_MemoryError,
2587                         "unable to allocate password buffer");
2588         goto error;
2589     }
2590     memcpy(pw_info->password, data, size);
2591     pw_info->size = (int)size;
2592 
2593     Py_XDECREF(password_bytes);
2594     return 1;
2595 
2596 error:
2597     Py_XDECREF(password_bytes);
2598     return 0;
2599 }
2600 
2601 static int
_password_callback(char * buf,int size,int rwflag,void * userdata)2602 _password_callback(char *buf, int size, int rwflag, void *userdata)
2603 {
2604     _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2605     PyObject *fn_ret = NULL;
2606 
2607     PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2608 
2609     if (pw_info->callable) {
2610         fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2611         if (!fn_ret) {
2612             /* TODO: It would be nice to move _ctypes_add_traceback() into the
2613                core python API, so we could use it to add a frame here */
2614             goto error;
2615         }
2616 
2617         if (!_pwinfo_set(pw_info, fn_ret,
2618                          "password callback must return a string")) {
2619             goto error;
2620         }
2621         Py_CLEAR(fn_ret);
2622     }
2623 
2624     if (pw_info->size > size) {
2625         PyErr_Format(PyExc_ValueError,
2626                      "password cannot be longer than %d bytes", size);
2627         goto error;
2628     }
2629 
2630     PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2631     memcpy(buf, pw_info->password, pw_info->size);
2632     return pw_info->size;
2633 
2634 error:
2635     Py_XDECREF(fn_ret);
2636     PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2637     pw_info->error = 1;
2638     return -1;
2639 }
2640 
2641 static PyObject *
load_cert_chain(PySSLContext * self,PyObject * args,PyObject * kwds)2642 load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2643 {
2644     char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2645     PyObject *keyfile = NULL, *keyfile_bytes = NULL, *password = NULL;
2646     char *certfile_bytes = NULL;
2647     pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
2648     void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
2649     _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
2650     int r;
2651 
2652     errno = 0;
2653     ERR_clear_error();
2654     if (!PyArg_ParseTupleAndKeywords(args, kwds,
2655             "et|OO:load_cert_chain", kwlist,
2656             Py_FileSystemDefaultEncoding, &certfile_bytes,
2657             &keyfile, &password))
2658         return NULL;
2659 
2660     if (keyfile && keyfile != Py_None) {
2661         if (PyString_Check(keyfile)) {
2662             Py_INCREF(keyfile);
2663             keyfile_bytes = keyfile;
2664         } else {
2665             PyObject *u = PyUnicode_FromObject(keyfile);
2666             if (!u)
2667                 goto error;
2668             keyfile_bytes = PyUnicode_AsEncodedString(
2669                 u, Py_FileSystemDefaultEncoding, NULL);
2670             Py_DECREF(u);
2671             if (!keyfile_bytes)
2672                 goto error;
2673         }
2674     }
2675 
2676     if (password && password != Py_None) {
2677         if (PyCallable_Check(password)) {
2678             pw_info.callable = password;
2679         } else if (!_pwinfo_set(&pw_info, password,
2680                                 "password should be a string or callable")) {
2681             goto error;
2682         }
2683         SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2684         SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2685     }
2686     PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2687     r = SSL_CTX_use_certificate_chain_file(self->ctx, certfile_bytes);
2688     PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2689     if (r != 1) {
2690         if (pw_info.error) {
2691             ERR_clear_error();
2692             /* the password callback has already set the error information */
2693         }
2694         else if (errno != 0) {
2695             ERR_clear_error();
2696             PyErr_SetFromErrno(PyExc_IOError);
2697         }
2698         else {
2699             _setSSLError(NULL, 0, __FILE__, __LINE__);
2700         }
2701         goto error;
2702     }
2703     PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2704     r = SSL_CTX_use_PrivateKey_file(self->ctx,
2705         keyfile_bytes ? PyBytes_AS_STRING(keyfile_bytes) : certfile_bytes,
2706         SSL_FILETYPE_PEM);
2707     PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2708     if (r != 1) {
2709         if (pw_info.error) {
2710             ERR_clear_error();
2711             /* the password callback has already set the error information */
2712         }
2713         else if (errno != 0) {
2714             ERR_clear_error();
2715             PyErr_SetFromErrno(PyExc_IOError);
2716         }
2717         else {
2718             _setSSLError(NULL, 0, __FILE__, __LINE__);
2719         }
2720         goto error;
2721     }
2722     PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2723     r = SSL_CTX_check_private_key(self->ctx);
2724     PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2725     if (r != 1) {
2726         _setSSLError(NULL, 0, __FILE__, __LINE__);
2727         goto error;
2728     }
2729     SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2730     SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2731     Py_XDECREF(keyfile_bytes);
2732     PyMem_Free(pw_info.password);
2733     PyMem_Free(certfile_bytes);
2734     Py_RETURN_NONE;
2735 
2736 error:
2737     SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2738     SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2739     Py_XDECREF(keyfile_bytes);
2740     PyMem_Free(pw_info.password);
2741     PyMem_Free(certfile_bytes);
2742     return NULL;
2743 }
2744 
2745 /* internal helper function, returns -1 on error
2746  */
2747 static int
_add_ca_certs(PySSLContext * self,void * data,Py_ssize_t len,int filetype)2748 _add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2749               int filetype)
2750 {
2751     BIO *biobuf = NULL;
2752     X509_STORE *store;
2753     int retval = 0, err, loaded = 0;
2754 
2755     assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2756 
2757     if (len <= 0) {
2758         PyErr_SetString(PyExc_ValueError,
2759                         "Empty certificate data");
2760         return -1;
2761     } else if (len > INT_MAX) {
2762         PyErr_SetString(PyExc_OverflowError,
2763                         "Certificate data is too long.");
2764         return -1;
2765     }
2766 
2767     biobuf = BIO_new_mem_buf(data, (int)len);
2768     if (biobuf == NULL) {
2769         _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2770         return -1;
2771     }
2772 
2773     store = SSL_CTX_get_cert_store(self->ctx);
2774     assert(store != NULL);
2775 
2776     while (1) {
2777         X509 *cert = NULL;
2778         int r;
2779 
2780         if (filetype == SSL_FILETYPE_ASN1) {
2781             cert = d2i_X509_bio(biobuf, NULL);
2782         } else {
2783             cert = PEM_read_bio_X509(biobuf, NULL,
2784                                      SSL_CTX_get_default_passwd_cb(self->ctx),
2785                                      SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
2786                                     );
2787         }
2788         if (cert == NULL) {
2789             break;
2790         }
2791         r = X509_STORE_add_cert(store, cert);
2792         X509_free(cert);
2793         if (!r) {
2794             err = ERR_peek_last_error();
2795             if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2796                 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2797                 /* cert already in hash table, not an error */
2798                 ERR_clear_error();
2799             } else {
2800                 break;
2801             }
2802         }
2803         loaded++;
2804     }
2805 
2806     err = ERR_peek_last_error();
2807     if ((filetype == SSL_FILETYPE_ASN1) &&
2808             (loaded > 0) &&
2809             (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2810             (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2811         /* EOF ASN1 file, not an error */
2812         ERR_clear_error();
2813         retval = 0;
2814     } else if ((filetype == SSL_FILETYPE_PEM) &&
2815                    (loaded > 0) &&
2816                    (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2817                    (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2818         /* EOF PEM file, not an error */
2819         ERR_clear_error();
2820         retval = 0;
2821     } else {
2822         _setSSLError(NULL, 0, __FILE__, __LINE__);
2823         retval = -1;
2824     }
2825 
2826     BIO_free(biobuf);
2827     return retval;
2828 }
2829 
2830 
2831 static PyObject *
load_verify_locations(PySSLContext * self,PyObject * args,PyObject * kwds)2832 load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2833 {
2834     char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2835     PyObject *cadata = NULL, *cafile = NULL, *capath = NULL;
2836     PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2837     const char *cafile_buf = NULL, *capath_buf = NULL;
2838     int r = 0, ok = 1;
2839 
2840     errno = 0;
2841     if (!PyArg_ParseTupleAndKeywords(args, kwds,
2842             "|OOO:load_verify_locations", kwlist,
2843             &cafile, &capath, &cadata))
2844         return NULL;
2845 
2846     if (cafile == Py_None)
2847         cafile = NULL;
2848     if (capath == Py_None)
2849         capath = NULL;
2850     if (cadata == Py_None)
2851         cadata = NULL;
2852 
2853     if (cafile == NULL && capath == NULL && cadata == NULL) {
2854         PyErr_SetString(PyExc_TypeError,
2855                         "cafile, capath and cadata cannot be all omitted");
2856         goto error;
2857     }
2858 
2859     if (cafile) {
2860         if (PyString_Check(cafile)) {
2861             Py_INCREF(cafile);
2862             cafile_bytes = cafile;
2863         } else {
2864             PyObject *u = PyUnicode_FromObject(cafile);
2865             if (!u)
2866                 goto error;
2867             cafile_bytes = PyUnicode_AsEncodedString(
2868                 u, Py_FileSystemDefaultEncoding, NULL);
2869             Py_DECREF(u);
2870             if (!cafile_bytes)
2871                 goto error;
2872         }
2873     }
2874     if (capath) {
2875         if (PyString_Check(capath)) {
2876             Py_INCREF(capath);
2877             capath_bytes = capath;
2878         } else {
2879             PyObject *u = PyUnicode_FromObject(capath);
2880             if (!u)
2881                 goto error;
2882             capath_bytes = PyUnicode_AsEncodedString(
2883                 u, Py_FileSystemDefaultEncoding, NULL);
2884             Py_DECREF(u);
2885             if (!capath_bytes)
2886                 goto error;
2887         }
2888     }
2889 
2890     /* validata cadata type and load cadata */
2891     if (cadata) {
2892         Py_buffer buf;
2893         PyObject *cadata_ascii = NULL;
2894 
2895         if (!PyUnicode_Check(cadata) && PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2896             if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2897                 PyBuffer_Release(&buf);
2898                 PyErr_SetString(PyExc_TypeError,
2899                                 "cadata should be a contiguous buffer with "
2900                                 "a single dimension");
2901                 goto error;
2902             }
2903             r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2904             PyBuffer_Release(&buf);
2905             if (r == -1) {
2906                 goto error;
2907             }
2908         } else {
2909             PyErr_Clear();
2910             cadata_ascii = PyUnicode_AsASCIIString(cadata);
2911             if (cadata_ascii == NULL) {
2912                 PyErr_SetString(PyExc_TypeError,
2913                                 "cadata should be an ASCII string or a "
2914                                 "bytes-like object");
2915                 goto error;
2916             }
2917             r = _add_ca_certs(self,
2918                               PyBytes_AS_STRING(cadata_ascii),
2919                               PyBytes_GET_SIZE(cadata_ascii),
2920                               SSL_FILETYPE_PEM);
2921             Py_DECREF(cadata_ascii);
2922             if (r == -1) {
2923                 goto error;
2924             }
2925         }
2926     }
2927 
2928     /* load cafile or capath */
2929     if (cafile_bytes || capath_bytes) {
2930         if (cafile)
2931             cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2932         if (capath)
2933             capath_buf = PyBytes_AS_STRING(capath_bytes);
2934         PySSL_BEGIN_ALLOW_THREADS
2935         r = SSL_CTX_load_verify_locations(
2936             self->ctx,
2937             cafile_buf,
2938             capath_buf);
2939         PySSL_END_ALLOW_THREADS
2940         if (r != 1) {
2941             ok = 0;
2942             if (errno != 0) {
2943                 ERR_clear_error();
2944                 PyErr_SetFromErrno(PyExc_IOError);
2945             }
2946             else {
2947                 _setSSLError(NULL, 0, __FILE__, __LINE__);
2948             }
2949             goto error;
2950         }
2951     }
2952     goto end;
2953 
2954   error:
2955     ok = 0;
2956   end:
2957     Py_XDECREF(cafile_bytes);
2958     Py_XDECREF(capath_bytes);
2959     if (ok) {
2960         Py_RETURN_NONE;
2961     } else {
2962         return NULL;
2963     }
2964 }
2965 
2966 static PyObject *
load_dh_params(PySSLContext * self,PyObject * filepath)2967 load_dh_params(PySSLContext *self, PyObject *filepath)
2968 {
2969     BIO *bio;
2970     DH *dh;
2971     char *path = PyBytes_AsString(filepath);
2972     if (!path) {
2973         return NULL;
2974     }
2975 
2976     bio = BIO_new_file(path, "r");
2977     if (bio == NULL) {
2978         ERR_clear_error();
2979         PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, filepath);
2980         return NULL;
2981     }
2982     errno = 0;
2983     PySSL_BEGIN_ALLOW_THREADS
2984     dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2985     BIO_free(bio);
2986     PySSL_END_ALLOW_THREADS
2987     if (dh == NULL) {
2988         if (errno != 0) {
2989             ERR_clear_error();
2990             PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2991         }
2992         else {
2993             _setSSLError(NULL, 0, __FILE__, __LINE__);
2994         }
2995         return NULL;
2996     }
2997     if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2998         _setSSLError(NULL, 0, __FILE__, __LINE__);
2999     DH_free(dh);
3000     Py_RETURN_NONE;
3001 }
3002 
3003 static PyObject *
context_wrap_socket(PySSLContext * self,PyObject * args,PyObject * kwds)3004 context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
3005 {
3006     char *kwlist[] = {"sock", "server_side", "server_hostname", "ssl_sock", NULL};
3007     PySocketSockObject *sock;
3008     int server_side = 0;
3009     char *hostname = NULL;
3010     PyObject *hostname_obj, *ssl_sock = Py_None, *res;
3011 
3012     /* server_hostname is either None (or absent), or to be encoded
3013        using the idna encoding. */
3014     if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!O:_wrap_socket", kwlist,
3015                                      PySocketModule.Sock_Type,
3016                                      &sock, &server_side,
3017                                      Py_TYPE(Py_None), &hostname_obj,
3018                                      &ssl_sock)) {
3019         PyErr_Clear();
3020         if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet|O:_wrap_socket", kwlist,
3021             PySocketModule.Sock_Type,
3022             &sock, &server_side,
3023             "idna", &hostname, &ssl_sock))
3024             return NULL;
3025     }
3026 
3027     res = (PyObject *) newPySSLSocket(self, sock, server_side,
3028                                       hostname, ssl_sock);
3029     if (hostname != NULL)
3030         PyMem_Free(hostname);
3031     return res;
3032 }
3033 
3034 static PyObject *
session_stats(PySSLContext * self,PyObject * unused)3035 session_stats(PySSLContext *self, PyObject *unused)
3036 {
3037     int r;
3038     PyObject *value, *stats = PyDict_New();
3039     if (!stats)
3040         return NULL;
3041 
3042 #define ADD_STATS(SSL_NAME, KEY_NAME) \
3043     value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3044     if (value == NULL) \
3045         goto error; \
3046     r = PyDict_SetItemString(stats, KEY_NAME, value); \
3047     Py_DECREF(value); \
3048     if (r < 0) \
3049         goto error;
3050 
3051     ADD_STATS(number, "number");
3052     ADD_STATS(connect, "connect");
3053     ADD_STATS(connect_good, "connect_good");
3054     ADD_STATS(connect_renegotiate, "connect_renegotiate");
3055     ADD_STATS(accept, "accept");
3056     ADD_STATS(accept_good, "accept_good");
3057     ADD_STATS(accept_renegotiate, "accept_renegotiate");
3058     ADD_STATS(accept, "accept");
3059     ADD_STATS(hits, "hits");
3060     ADD_STATS(misses, "misses");
3061     ADD_STATS(timeouts, "timeouts");
3062     ADD_STATS(cache_full, "cache_full");
3063 
3064 #undef ADD_STATS
3065 
3066     return stats;
3067 
3068 error:
3069     Py_DECREF(stats);
3070     return NULL;
3071 }
3072 
3073 static PyObject *
set_default_verify_paths(PySSLContext * self,PyObject * unused)3074 set_default_verify_paths(PySSLContext *self, PyObject *unused)
3075 {
3076     if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3077         _setSSLError(NULL, 0, __FILE__, __LINE__);
3078         return NULL;
3079     }
3080     Py_RETURN_NONE;
3081 }
3082 
3083 #ifndef OPENSSL_NO_ECDH
3084 static PyObject *
set_ecdh_curve(PySSLContext * self,PyObject * name)3085 set_ecdh_curve(PySSLContext *self, PyObject *name)
3086 {
3087     char *name_bytes;
3088     int nid;
3089     EC_KEY *key;
3090 
3091     name_bytes = PyBytes_AsString(name);
3092     if (!name_bytes) {
3093         return NULL;
3094     }
3095     nid = OBJ_sn2nid(name_bytes);
3096     if (nid == 0) {
3097         PyObject *r = PyObject_Repr(name);
3098         if (!r)
3099             return NULL;
3100         PyErr_Format(PyExc_ValueError,
3101                      "unknown elliptic curve name %s", PyString_AS_STRING(r));
3102         Py_DECREF(r);
3103         return NULL;
3104     }
3105     key = EC_KEY_new_by_curve_name(nid);
3106     if (key == NULL) {
3107         _setSSLError(NULL, 0, __FILE__, __LINE__);
3108         return NULL;
3109     }
3110     SSL_CTX_set_tmp_ecdh(self->ctx, key);
3111     EC_KEY_free(key);
3112     Py_RETURN_NONE;
3113 }
3114 #endif
3115 
3116 #if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3117 static int
_servername_callback(SSL * s,int * al,void * args)3118 _servername_callback(SSL *s, int *al, void *args)
3119 {
3120     int ret;
3121     PySSLContext *ssl_ctx = (PySSLContext *) args;
3122     PySSLSocket *ssl;
3123     PyObject *servername_o;
3124     PyObject *servername_idna;
3125     PyObject *result;
3126     /* The high-level ssl.SSLSocket object */
3127     PyObject *ssl_socket;
3128     const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
3129 #ifdef WITH_THREAD
3130     PyGILState_STATE gstate = PyGILState_Ensure();
3131 #endif
3132 
3133     if (ssl_ctx->set_hostname == NULL) {
3134         /* remove race condition in this the call back while if removing the
3135          * callback is in progress */
3136 #ifdef WITH_THREAD
3137         PyGILState_Release(gstate);
3138 #endif
3139         return SSL_TLSEXT_ERR_OK;
3140     }
3141 
3142     ssl = SSL_get_app_data(s);
3143     assert(PySSLSocket_Check(ssl));
3144     if (ssl->ssl_sock == NULL) {
3145         ssl_socket = Py_None;
3146     } else {
3147         ssl_socket = PyWeakref_GetObject(ssl->ssl_sock);
3148         Py_INCREF(ssl_socket);
3149     }
3150     if (ssl_socket == Py_None) {
3151         goto error;
3152     }
3153 
3154     if (servername == NULL) {
3155         result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3156                                               Py_None, ssl_ctx, NULL);
3157     }
3158     else {
3159         servername_o = PyBytes_FromString(servername);
3160         if (servername_o == NULL) {
3161             PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3162             goto error;
3163         }
3164         servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3165         if (servername_idna == NULL) {
3166             PyErr_WriteUnraisable(servername_o);
3167             Py_DECREF(servername_o);
3168             goto error;
3169         }
3170         Py_DECREF(servername_o);
3171         result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3172                                               servername_idna, ssl_ctx, NULL);
3173         Py_DECREF(servername_idna);
3174     }
3175     Py_DECREF(ssl_socket);
3176 
3177     if (result == NULL) {
3178         PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3179         *al = SSL_AD_HANDSHAKE_FAILURE;
3180         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3181     }
3182     else {
3183         if (result != Py_None) {
3184             *al = (int) PyLong_AsLong(result);
3185             if (PyErr_Occurred()) {
3186                 PyErr_WriteUnraisable(result);
3187                 *al = SSL_AD_INTERNAL_ERROR;
3188             }
3189             ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3190         }
3191         else {
3192             ret = SSL_TLSEXT_ERR_OK;
3193         }
3194         Py_DECREF(result);
3195     }
3196 
3197 #ifdef WITH_THREAD
3198     PyGILState_Release(gstate);
3199 #endif
3200     return ret;
3201 
3202 error:
3203     Py_DECREF(ssl_socket);
3204     *al = SSL_AD_INTERNAL_ERROR;
3205     ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3206 #ifdef WITH_THREAD
3207     PyGILState_Release(gstate);
3208 #endif
3209     return ret;
3210 }
3211 #endif
3212 
3213 PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3214 "set_servername_callback(method)\n\
3215 \n\
3216 This sets a callback that will be called when a server name is provided by\n\
3217 the SSL/TLS client in the SNI extension.\n\
3218 \n\
3219 If the argument is None then the callback is disabled. The method is called\n\
3220 with the SSLSocket, the server name as a string, and the SSLContext object.\n\
3221 See RFC 6066 for details of the SNI extension.");
3222 
3223 static PyObject *
set_servername_callback(PySSLContext * self,PyObject * args)3224 set_servername_callback(PySSLContext *self, PyObject *args)
3225 {
3226 #if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3227     PyObject *cb;
3228 
3229     if (!PyArg_ParseTuple(args, "O", &cb))
3230         return NULL;
3231 
3232     Py_CLEAR(self->set_hostname);
3233     if (cb == Py_None) {
3234         SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3235     }
3236     else {
3237         if (!PyCallable_Check(cb)) {
3238             SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3239             PyErr_SetString(PyExc_TypeError,
3240                             "not a callable object");
3241             return NULL;
3242         }
3243         Py_INCREF(cb);
3244         self->set_hostname = cb;
3245         SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3246         SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3247     }
3248     Py_RETURN_NONE;
3249 #else
3250     PyErr_SetString(PyExc_NotImplementedError,
3251                     "The TLS extension servername callback, "
3252                     "SSL_CTX_set_tlsext_servername_callback, "
3253                     "is not in the current OpenSSL library.");
3254     return NULL;
3255 #endif
3256 }
3257 
3258 PyDoc_STRVAR(PySSL_get_stats_doc,
3259 "cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3260 \n\
3261 Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3262 CA extension and certificate revocation lists inside the context's cert\n\
3263 store.\n\
3264 NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3265 been used at least once.");
3266 
3267 static PyObject *
cert_store_stats(PySSLContext * self)3268 cert_store_stats(PySSLContext *self)
3269 {
3270     X509_STORE *store;
3271     STACK_OF(X509_OBJECT) *objs;
3272     X509_OBJECT *obj;
3273     int x509 = 0, crl = 0, ca = 0, i;
3274 
3275     store = SSL_CTX_get_cert_store(self->ctx);
3276     objs = X509_STORE_get0_objects(store);
3277     for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3278         obj = sk_X509_OBJECT_value(objs, i);
3279         switch (X509_OBJECT_get_type(obj)) {
3280             case X509_LU_X509:
3281                 x509++;
3282                 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
3283                     ca++;
3284                 }
3285                 break;
3286             case X509_LU_CRL:
3287                 crl++;
3288                 break;
3289             default:
3290                 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3291                  * As far as I can tell they are internal states and never
3292                  * stored in a cert store */
3293                 break;
3294         }
3295     }
3296     return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3297         "x509_ca", ca);
3298 }
3299 
3300 PyDoc_STRVAR(PySSL_get_ca_certs_doc,
3301 "get_ca_certs(binary_form=False) -> list of loaded certificate\n\
3302 \n\
3303 Returns a list of dicts with information of loaded CA certs. If the\n\
3304 optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3305 NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3306 been used at least once.");
3307 
3308 static PyObject *
get_ca_certs(PySSLContext * self,PyObject * args,PyObject * kwds)3309 get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
3310 {
3311     char *kwlist[] = {"binary_form", NULL};
3312     X509_STORE *store;
3313     PyObject *ci = NULL, *rlist = NULL, *py_binary_mode = Py_False;
3314     STACK_OF(X509_OBJECT) *objs;
3315     int i;
3316     int binary_mode = 0;
3317 
3318     if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:get_ca_certs",
3319                                      kwlist, &py_binary_mode)) {
3320         return NULL;
3321     }
3322     binary_mode = PyObject_IsTrue(py_binary_mode);
3323     if (binary_mode < 0) {
3324         return NULL;
3325     }
3326 
3327     if ((rlist = PyList_New(0)) == NULL) {
3328         return NULL;
3329     }
3330 
3331     store = SSL_CTX_get_cert_store(self->ctx);
3332     objs = X509_STORE_get0_objects(store);
3333     for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3334         X509_OBJECT *obj;
3335         X509 *cert;
3336 
3337         obj = sk_X509_OBJECT_value(objs, i);
3338         if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
3339             /* not a x509 cert */
3340             continue;
3341         }
3342         /* CA for any purpose */
3343         cert = X509_OBJECT_get0_X509(obj);
3344         if (!X509_check_ca(cert)) {
3345             continue;
3346         }
3347         if (binary_mode) {
3348             ci = _certificate_to_der(cert);
3349         } else {
3350             ci = _decode_certificate(cert);
3351         }
3352         if (ci == NULL) {
3353             goto error;
3354         }
3355         if (PyList_Append(rlist, ci) == -1) {
3356             goto error;
3357         }
3358         Py_CLEAR(ci);
3359     }
3360     return rlist;
3361 
3362   error:
3363     Py_XDECREF(ci);
3364     Py_XDECREF(rlist);
3365     return NULL;
3366 }
3367 
3368 
3369 static PyGetSetDef context_getsetlist[] = {
3370     {"check_hostname", (getter) get_check_hostname,
3371                        (setter) set_check_hostname, NULL},
3372     {"options", (getter) get_options,
3373                 (setter) set_options, NULL},
3374 #ifdef HAVE_OPENSSL_VERIFY_PARAM
3375     {"verify_flags", (getter) get_verify_flags,
3376                      (setter) set_verify_flags, NULL},
3377 #endif
3378     {"verify_mode", (getter) get_verify_mode,
3379                     (setter) set_verify_mode, NULL},
3380     {NULL},            /* sentinel */
3381 };
3382 
3383 static struct PyMethodDef context_methods[] = {
3384     {"_wrap_socket", (PyCFunction) context_wrap_socket,
3385                        METH_VARARGS | METH_KEYWORDS, NULL},
3386     {"set_ciphers", (PyCFunction) set_ciphers,
3387                     METH_VARARGS, NULL},
3388     {"_set_alpn_protocols", (PyCFunction) _set_alpn_protocols,
3389                            METH_VARARGS, NULL},
3390     {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3391                            METH_VARARGS, NULL},
3392     {"load_cert_chain", (PyCFunction) load_cert_chain,
3393                         METH_VARARGS | METH_KEYWORDS, NULL},
3394     {"load_dh_params", (PyCFunction) load_dh_params,
3395                        METH_O, NULL},
3396     {"load_verify_locations", (PyCFunction) load_verify_locations,
3397                               METH_VARARGS | METH_KEYWORDS, NULL},
3398     {"session_stats", (PyCFunction) session_stats,
3399                       METH_NOARGS, NULL},
3400     {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3401                                  METH_NOARGS, NULL},
3402 #ifndef OPENSSL_NO_ECDH
3403     {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3404                        METH_O, NULL},
3405 #endif
3406     {"set_servername_callback", (PyCFunction) set_servername_callback,
3407                     METH_VARARGS, PySSL_set_servername_callback_doc},
3408     {"cert_store_stats", (PyCFunction) cert_store_stats,
3409                     METH_NOARGS, PySSL_get_stats_doc},
3410     {"get_ca_certs", (PyCFunction) get_ca_certs,
3411                     METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
3412     {NULL, NULL}        /* sentinel */
3413 };
3414 
3415 static PyTypeObject PySSLContext_Type = {
3416     PyVarObject_HEAD_INIT(NULL, 0)
3417     "_ssl._SSLContext",                        /*tp_name*/
3418     sizeof(PySSLContext),                      /*tp_basicsize*/
3419     0,                                         /*tp_itemsize*/
3420     (destructor)context_dealloc,               /*tp_dealloc*/
3421     0,                                         /*tp_print*/
3422     0,                                         /*tp_getattr*/
3423     0,                                         /*tp_setattr*/
3424     0,                                         /*tp_reserved*/
3425     0,                                         /*tp_repr*/
3426     0,                                         /*tp_as_number*/
3427     0,                                         /*tp_as_sequence*/
3428     0,                                         /*tp_as_mapping*/
3429     0,                                         /*tp_hash*/
3430     0,                                         /*tp_call*/
3431     0,                                         /*tp_str*/
3432     0,                                         /*tp_getattro*/
3433     0,                                         /*tp_setattro*/
3434     0,                                         /*tp_as_buffer*/
3435     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
3436     0,                                         /*tp_doc*/
3437     (traverseproc) context_traverse,           /*tp_traverse*/
3438     (inquiry) context_clear,                   /*tp_clear*/
3439     0,                                         /*tp_richcompare*/
3440     0,                                         /*tp_weaklistoffset*/
3441     0,                                         /*tp_iter*/
3442     0,                                         /*tp_iternext*/
3443     context_methods,                           /*tp_methods*/
3444     0,                                         /*tp_members*/
3445     context_getsetlist,                        /*tp_getset*/
3446     0,                                         /*tp_base*/
3447     0,                                         /*tp_dict*/
3448     0,                                         /*tp_descr_get*/
3449     0,                                         /*tp_descr_set*/
3450     0,                                         /*tp_dictoffset*/
3451     0,                                         /*tp_init*/
3452     0,                                         /*tp_alloc*/
3453     context_new,                               /*tp_new*/
3454 };
3455 
3456 
3457 
3458 #ifdef HAVE_OPENSSL_RAND
3459 
3460 /* helper routines for seeding the SSL PRNG */
3461 static PyObject *
PySSL_RAND_add(PyObject * self,PyObject * args)3462 PySSL_RAND_add(PyObject *self, PyObject *args)
3463 {
3464     char *buf;
3465     Py_ssize_t len, written;
3466     double entropy;
3467 
3468     if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
3469         return NULL;
3470     do {
3471         if (len >= INT_MAX) {
3472             written = INT_MAX;
3473         } else {
3474             written = len;
3475         }
3476         RAND_add(buf, (int)written, entropy);
3477         buf += written;
3478         len -= written;
3479     } while (len);
3480     Py_INCREF(Py_None);
3481     return Py_None;
3482 }
3483 
3484 PyDoc_STRVAR(PySSL_RAND_add_doc,
3485 "RAND_add(string, entropy)\n\
3486 \n\
3487 Mix string into the OpenSSL PRNG state.  entropy (a float) is a lower\n\
3488 bound on the entropy contained in string.  See RFC 1750.");
3489 
3490 static PyObject *
PySSL_RAND_status(PyObject * self)3491 PySSL_RAND_status(PyObject *self)
3492 {
3493     return PyLong_FromLong(RAND_status());
3494 }
3495 
3496 PyDoc_STRVAR(PySSL_RAND_status_doc,
3497 "RAND_status() -> 0 or 1\n\
3498 \n\
3499 Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3500 It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
3501 using the ssl() function.");
3502 
3503 #endif /* HAVE_OPENSSL_RAND */
3504 
3505 
3506 #ifndef OPENSSL_NO_EGD
3507 
3508 static PyObject *
PySSL_RAND_egd(PyObject * self,PyObject * arg)3509 PySSL_RAND_egd(PyObject *self, PyObject *arg)
3510 {
3511     int bytes;
3512 
3513     if (!PyString_Check(arg))
3514         return PyErr_Format(PyExc_TypeError,
3515                             "RAND_egd() expected string, found %s",
3516                             Py_TYPE(arg)->tp_name);
3517     bytes = RAND_egd(PyString_AS_STRING(arg));
3518     if (bytes == -1) {
3519         PyErr_SetString(PySSLErrorObject,
3520                         "EGD connection failed or EGD did not return "
3521                         "enough data to seed the PRNG");
3522         return NULL;
3523     }
3524     return PyInt_FromLong(bytes);
3525 }
3526 
3527 PyDoc_STRVAR(PySSL_RAND_egd_doc,
3528 "RAND_egd(path) -> bytes\n\
3529 \n\
3530 Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3531 Returns number of bytes read.  Raises SSLError if connection to EGD\n\
3532 fails or if it does not provide enough data to seed PRNG.");
3533 
3534 #endif /* !OPENSSL_NO_EGD */
3535 
3536 
3537 PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3538 "get_default_verify_paths() -> tuple\n\
3539 \n\
3540 Return search paths and environment vars that are used by SSLContext's\n\
3541 set_default_verify_paths() to load default CAs. The values are\n\
3542 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3543 
3544 static PyObject *
PySSL_get_default_verify_paths(PyObject * self)3545 PySSL_get_default_verify_paths(PyObject *self)
3546 {
3547     PyObject *ofile_env = NULL;
3548     PyObject *ofile = NULL;
3549     PyObject *odir_env = NULL;
3550     PyObject *odir = NULL;
3551 
3552 #define CONVERT(info, target) { \
3553         const char *tmp = (info); \
3554         target = NULL; \
3555         if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3556         else { target = PyBytes_FromString(tmp); } \
3557         if (!target) goto error; \
3558     }
3559 
3560     CONVERT(X509_get_default_cert_file_env(), ofile_env);
3561     CONVERT(X509_get_default_cert_file(), ofile);
3562     CONVERT(X509_get_default_cert_dir_env(), odir_env);
3563     CONVERT(X509_get_default_cert_dir(), odir);
3564 #undef CONVERT
3565 
3566     return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
3567 
3568   error:
3569     Py_XDECREF(ofile_env);
3570     Py_XDECREF(ofile);
3571     Py_XDECREF(odir_env);
3572     Py_XDECREF(odir);
3573     return NULL;
3574 }
3575 
3576 static PyObject*
asn1obj2py(ASN1_OBJECT * obj)3577 asn1obj2py(ASN1_OBJECT *obj)
3578 {
3579     int nid;
3580     const char *ln, *sn;
3581     char buf[100];
3582     Py_ssize_t buflen;
3583 
3584     nid = OBJ_obj2nid(obj);
3585     if (nid == NID_undef) {
3586         PyErr_Format(PyExc_ValueError, "Unknown object");
3587         return NULL;
3588     }
3589     sn = OBJ_nid2sn(nid);
3590     ln = OBJ_nid2ln(nid);
3591     buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3592     if (buflen < 0) {
3593         _setSSLError(NULL, 0, __FILE__, __LINE__);
3594         return NULL;
3595     }
3596     if (buflen) {
3597         return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3598     } else {
3599         return Py_BuildValue("issO", nid, sn, ln, Py_None);
3600     }
3601 }
3602 
3603 PyDoc_STRVAR(PySSL_txt2obj_doc,
3604 "txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3605 \n\
3606 Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3607 objects are looked up by OID. With name=True short and long name are also\n\
3608 matched.");
3609 
3610 static PyObject*
PySSL_txt2obj(PyObject * self,PyObject * args,PyObject * kwds)3611 PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3612 {
3613     char *kwlist[] = {"txt", "name", NULL};
3614     PyObject *result = NULL;
3615     char *txt;
3616     PyObject *pyname = Py_None;
3617     int name = 0;
3618     ASN1_OBJECT *obj;
3619 
3620     if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:txt2obj",
3621                                      kwlist, &txt, &pyname)) {
3622         return NULL;
3623     }
3624     name = PyObject_IsTrue(pyname);
3625     if (name < 0)
3626         return NULL;
3627     obj = OBJ_txt2obj(txt, name ? 0 : 1);
3628     if (obj == NULL) {
3629         PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
3630         return NULL;
3631     }
3632     result = asn1obj2py(obj);
3633     ASN1_OBJECT_free(obj);
3634     return result;
3635 }
3636 
3637 PyDoc_STRVAR(PySSL_nid2obj_doc,
3638 "nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3639 \n\
3640 Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3641 
3642 static PyObject*
PySSL_nid2obj(PyObject * self,PyObject * args)3643 PySSL_nid2obj(PyObject *self, PyObject *args)
3644 {
3645     PyObject *result = NULL;
3646     int nid;
3647     ASN1_OBJECT *obj;
3648 
3649     if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3650         return NULL;
3651     }
3652     if (nid < NID_undef) {
3653         PyErr_SetString(PyExc_ValueError, "NID must be positive.");
3654         return NULL;
3655     }
3656     obj = OBJ_nid2obj(nid);
3657     if (obj == NULL) {
3658         PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
3659         return NULL;
3660     }
3661     result = asn1obj2py(obj);
3662     ASN1_OBJECT_free(obj);
3663     return result;
3664 }
3665 
3666 #ifdef _MSC_VER
3667 
3668 static PyObject*
certEncodingType(DWORD encodingType)3669 certEncodingType(DWORD encodingType)
3670 {
3671     static PyObject *x509_asn = NULL;
3672     static PyObject *pkcs_7_asn = NULL;
3673 
3674     if (x509_asn == NULL) {
3675         x509_asn = PyString_InternFromString("x509_asn");
3676         if (x509_asn == NULL)
3677             return NULL;
3678     }
3679     if (pkcs_7_asn == NULL) {
3680         pkcs_7_asn = PyString_InternFromString("pkcs_7_asn");
3681         if (pkcs_7_asn == NULL)
3682             return NULL;
3683     }
3684     switch(encodingType) {
3685     case X509_ASN_ENCODING:
3686         Py_INCREF(x509_asn);
3687         return x509_asn;
3688     case PKCS_7_ASN_ENCODING:
3689         Py_INCREF(pkcs_7_asn);
3690         return pkcs_7_asn;
3691     default:
3692         return PyInt_FromLong(encodingType);
3693     }
3694 }
3695 
3696 static PyObject*
parseKeyUsage(PCCERT_CONTEXT pCertCtx,DWORD flags)3697 parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3698 {
3699     CERT_ENHKEY_USAGE *usage;
3700     DWORD size, error, i;
3701     PyObject *retval;
3702 
3703     if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3704         error = GetLastError();
3705         if (error == CRYPT_E_NOT_FOUND) {
3706             Py_RETURN_TRUE;
3707         }
3708         return PyErr_SetFromWindowsErr(error);
3709     }
3710 
3711     usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3712     if (usage == NULL) {
3713         return PyErr_NoMemory();
3714     }
3715 
3716     /* Now get the actual enhanced usage property */
3717     if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3718         PyMem_Free(usage);
3719         error = GetLastError();
3720         if (error == CRYPT_E_NOT_FOUND) {
3721             Py_RETURN_TRUE;
3722         }
3723         return PyErr_SetFromWindowsErr(error);
3724     }
3725     retval = PySet_New(NULL);
3726     if (retval == NULL) {
3727         goto error;
3728     }
3729     for (i = 0; i < usage->cUsageIdentifier; ++i) {
3730         if (usage->rgpszUsageIdentifier[i]) {
3731             PyObject *oid;
3732             int err;
3733             oid = PyString_FromString(usage->rgpszUsageIdentifier[i]);
3734             if (oid == NULL) {
3735                 Py_CLEAR(retval);
3736                 goto error;
3737             }
3738             err = PySet_Add(retval, oid);
3739             Py_DECREF(oid);
3740             if (err == -1) {
3741                 Py_CLEAR(retval);
3742                 goto error;
3743             }
3744         }
3745     }
3746   error:
3747     PyMem_Free(usage);
3748     return retval;
3749 }
3750 
3751 PyDoc_STRVAR(PySSL_enum_certificates_doc,
3752 "enum_certificates(store_name) -> []\n\
3753 \n\
3754 Retrieve certificates from Windows' cert store. store_name may be one of\n\
3755 'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3756 The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
3757 encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3758 PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3759 boolean True.");
3760 
3761 static PyObject *
PySSL_enum_certificates(PyObject * self,PyObject * args,PyObject * kwds)3762 PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
3763 {
3764     char *kwlist[] = {"store_name", NULL};
3765     char *store_name;
3766     HCERTSTORE hStore = NULL;
3767     PCCERT_CONTEXT pCertCtx = NULL;
3768     PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
3769     PyObject *result = NULL;
3770 
3771     if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_certificates",
3772                                      kwlist, &store_name)) {
3773         return NULL;
3774     }
3775     result = PyList_New(0);
3776     if (result == NULL) {
3777         return NULL;
3778     }
3779     hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3780                             CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3781                             store_name);
3782     if (hStore == NULL) {
3783         Py_DECREF(result);
3784         return PyErr_SetFromWindowsErr(GetLastError());
3785     }
3786 
3787     while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3788         cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3789                                             pCertCtx->cbCertEncoded);
3790         if (!cert) {
3791             Py_CLEAR(result);
3792             break;
3793         }
3794         if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3795             Py_CLEAR(result);
3796             break;
3797         }
3798         keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3799         if (keyusage == Py_True) {
3800             Py_DECREF(keyusage);
3801             keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
3802         }
3803         if (keyusage == NULL) {
3804             Py_CLEAR(result);
3805             break;
3806         }
3807         if ((tup = PyTuple_New(3)) == NULL) {
3808             Py_CLEAR(result);
3809             break;
3810         }
3811         PyTuple_SET_ITEM(tup, 0, cert);
3812         cert = NULL;
3813         PyTuple_SET_ITEM(tup, 1, enc);
3814         enc = NULL;
3815         PyTuple_SET_ITEM(tup, 2, keyusage);
3816         keyusage = NULL;
3817         if (PyList_Append(result, tup) < 0) {
3818             Py_CLEAR(result);
3819             break;
3820         }
3821         Py_CLEAR(tup);
3822     }
3823     if (pCertCtx) {
3824         /* loop ended with an error, need to clean up context manually */
3825         CertFreeCertificateContext(pCertCtx);
3826     }
3827 
3828     /* In error cases cert, enc and tup may not be NULL */
3829     Py_XDECREF(cert);
3830     Py_XDECREF(enc);
3831     Py_XDECREF(keyusage);
3832     Py_XDECREF(tup);
3833 
3834     if (!CertCloseStore(hStore, 0)) {
3835         /* This error case might shadow another exception.*/
3836         Py_XDECREF(result);
3837         return PyErr_SetFromWindowsErr(GetLastError());
3838     }
3839     return result;
3840 }
3841 
3842 PyDoc_STRVAR(PySSL_enum_crls_doc,
3843 "enum_crls(store_name) -> []\n\
3844 \n\
3845 Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3846 'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3847 The function returns a list of (bytes, encoding_type) tuples. The\n\
3848 encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3849 PKCS_7_ASN_ENCODING.");
3850 
3851 static PyObject *
PySSL_enum_crls(PyObject * self,PyObject * args,PyObject * kwds)3852 PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3853 {
3854     char *kwlist[] = {"store_name", NULL};
3855     char *store_name;
3856     HCERTSTORE hStore = NULL;
3857     PCCRL_CONTEXT pCrlCtx = NULL;
3858     PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3859     PyObject *result = NULL;
3860 
3861     if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_crls",
3862                                      kwlist, &store_name)) {
3863         return NULL;
3864     }
3865     result = PyList_New(0);
3866     if (result == NULL) {
3867         return NULL;
3868     }
3869     hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3870                             CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3871                             store_name);
3872     if (hStore == NULL) {
3873         Py_DECREF(result);
3874         return PyErr_SetFromWindowsErr(GetLastError());
3875     }
3876 
3877     while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3878         crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3879                                             pCrlCtx->cbCrlEncoded);
3880         if (!crl) {
3881             Py_CLEAR(result);
3882             break;
3883         }
3884         if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3885             Py_CLEAR(result);
3886             break;
3887         }
3888         if ((tup = PyTuple_New(2)) == NULL) {
3889             Py_CLEAR(result);
3890             break;
3891         }
3892         PyTuple_SET_ITEM(tup, 0, crl);
3893         crl = NULL;
3894         PyTuple_SET_ITEM(tup, 1, enc);
3895         enc = NULL;
3896 
3897         if (PyList_Append(result, tup) < 0) {
3898             Py_CLEAR(result);
3899             break;
3900         }
3901         Py_CLEAR(tup);
3902     }
3903     if (pCrlCtx) {
3904         /* loop ended with an error, need to clean up context manually */
3905         CertFreeCRLContext(pCrlCtx);
3906     }
3907 
3908     /* In error cases cert, enc and tup may not be NULL */
3909     Py_XDECREF(crl);
3910     Py_XDECREF(enc);
3911     Py_XDECREF(tup);
3912 
3913     if (!CertCloseStore(hStore, 0)) {
3914         /* This error case might shadow another exception.*/
3915         Py_XDECREF(result);
3916         return PyErr_SetFromWindowsErr(GetLastError());
3917     }
3918     return result;
3919 }
3920 
3921 #endif /* _MSC_VER */
3922 
3923 /* List of functions exported by this module. */
3924 
3925 static PyMethodDef PySSL_methods[] = {
3926     {"_test_decode_cert",       PySSL_test_decode_certificate,
3927      METH_VARARGS},
3928 #ifdef HAVE_OPENSSL_RAND
3929     {"RAND_add",            PySSL_RAND_add, METH_VARARGS,
3930      PySSL_RAND_add_doc},
3931     {"RAND_status",         (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3932      PySSL_RAND_status_doc},
3933 #endif
3934 #ifndef OPENSSL_NO_EGD
3935     {"RAND_egd",            PySSL_RAND_egd, METH_VARARGS,
3936      PySSL_RAND_egd_doc},
3937 #endif
3938     {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
3939      METH_NOARGS, PySSL_get_default_verify_paths_doc},
3940 #ifdef _MSC_VER
3941     {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
3942      METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
3943     {"enum_crls", (PyCFunction)PySSL_enum_crls,
3944      METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
3945 #endif
3946     {"txt2obj", (PyCFunction)PySSL_txt2obj,
3947      METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
3948     {"nid2obj", (PyCFunction)PySSL_nid2obj,
3949      METH_VARARGS, PySSL_nid2obj_doc},
3950     {NULL,                  NULL}            /* Sentinel */
3951 };
3952 
3953 
3954 #ifdef HAVE_OPENSSL_CRYPTO_LOCK
3955 
3956 /* an implementation of OpenSSL threading operations in terms
3957  * of the Python C thread library
3958  * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
3959  */
3960 
3961 static PyThread_type_lock *_ssl_locks = NULL;
3962 
3963 #if OPENSSL_VERSION_NUMBER >= 0x10000000
3964 /* use new CRYPTO_THREADID API. */
3965 static void
_ssl_threadid_callback(CRYPTO_THREADID * id)3966 _ssl_threadid_callback(CRYPTO_THREADID *id)
3967 {
3968     CRYPTO_THREADID_set_numeric(id,
3969                                 (unsigned long)PyThread_get_thread_ident());
3970 }
3971 #else
3972 /* deprecated CRYPTO_set_id_callback() API. */
3973 static unsigned long
_ssl_thread_id_function(void)3974 _ssl_thread_id_function (void) {
3975     return PyThread_get_thread_ident();
3976 }
3977 #endif
3978 
_ssl_thread_locking_function(int mode,int n,const char * file,int line)3979 static void _ssl_thread_locking_function
3980     (int mode, int n, const char *file, int line) {
3981     /* this function is needed to perform locking on shared data
3982        structures. (Note that OpenSSL uses a number of global data
3983        structures that will be implicitly shared whenever multiple
3984        threads use OpenSSL.) Multi-threaded applications will
3985        crash at random if it is not set.
3986 
3987        locking_function() must be able to handle up to
3988        CRYPTO_num_locks() different mutex locks. It sets the n-th
3989        lock if mode & CRYPTO_LOCK, and releases it otherwise.
3990 
3991        file and line are the file number of the function setting the
3992        lock. They can be useful for debugging.
3993     */
3994 
3995     if ((_ssl_locks == NULL) ||
3996         (n < 0) || ((unsigned)n >= _ssl_locks_count))
3997         return;
3998 
3999     if (mode & CRYPTO_LOCK) {
4000         PyThread_acquire_lock(_ssl_locks[n], 1);
4001     } else {
4002         PyThread_release_lock(_ssl_locks[n]);
4003     }
4004 }
4005 
_setup_ssl_threads(void)4006 static int _setup_ssl_threads(void) {
4007 
4008     unsigned int i;
4009 
4010     if (_ssl_locks == NULL) {
4011         _ssl_locks_count = CRYPTO_num_locks();
4012         _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4013         if (_ssl_locks == NULL) {
4014             PyErr_NoMemory();
4015             return 0;
4016         }
4017         memset(_ssl_locks, 0,
4018                sizeof(PyThread_type_lock) * _ssl_locks_count);
4019         for (i = 0;  i < _ssl_locks_count;  i++) {
4020             _ssl_locks[i] = PyThread_allocate_lock();
4021             if (_ssl_locks[i] == NULL) {
4022                 unsigned int j;
4023                 for (j = 0;  j < i;  j++) {
4024                     PyThread_free_lock(_ssl_locks[j]);
4025                 }
4026                 PyMem_Free(_ssl_locks);
4027                 return 0;
4028             }
4029         }
4030         CRYPTO_set_locking_callback(_ssl_thread_locking_function);
4031 #if OPENSSL_VERSION_NUMBER >= 0x10000000
4032         CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4033 #else
4034         CRYPTO_set_id_callback(_ssl_thread_id_function);
4035 #endif
4036     }
4037     return 1;
4038 }
4039 
4040 #endif  /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
4041 
4042 PyDoc_STRVAR(module_doc,
4043 "Implementation module for SSL socket operations.  See the socket module\n\
4044 for documentation.");
4045 
4046 
4047 
4048 
4049 static void
parse_openssl_version(unsigned long libver,unsigned int * major,unsigned int * minor,unsigned int * fix,unsigned int * patch,unsigned int * status)4050 parse_openssl_version(unsigned long libver,
4051                       unsigned int *major, unsigned int *minor,
4052                       unsigned int *fix, unsigned int *patch,
4053                       unsigned int *status)
4054 {
4055     *status = libver & 0xF;
4056     libver >>= 4;
4057     *patch = libver & 0xFF;
4058     libver >>= 8;
4059     *fix = libver & 0xFF;
4060     libver >>= 8;
4061     *minor = libver & 0xFF;
4062     libver >>= 8;
4063     *major = libver & 0xFF;
4064 }
4065 
4066 PyMODINIT_FUNC
init_ssl(void)4067 init_ssl(void)
4068 {
4069     PyObject *m, *d, *r;
4070     unsigned long libver;
4071     unsigned int major, minor, fix, patch, status;
4072     struct py_ssl_error_code *errcode;
4073     struct py_ssl_library_code *libcode;
4074 
4075     if (PyType_Ready(&PySSLContext_Type) < 0)
4076         return;
4077     if (PyType_Ready(&PySSLSocket_Type) < 0)
4078         return;
4079 
4080     m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
4081     if (m == NULL)
4082         return;
4083     d = PyModule_GetDict(m);
4084 
4085     /* Load _socket module and its C API */
4086     if (PySocketModule_ImportModuleAndAPI())
4087         return;
4088 
4089     /* Init OpenSSL */
4090     SSL_load_error_strings();
4091     SSL_library_init();
4092 #ifdef WITH_THREAD
4093 #ifdef HAVE_OPENSSL_CRYPTO_LOCK
4094     /* note that this will start threading if not already started */
4095     if (!_setup_ssl_threads()) {
4096         return;
4097     }
4098 #elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
4099     /* OpenSSL 1.1.0 builtin thread support is enabled */
4100     _ssl_locks_count++;
4101 #endif
4102 #endif  /* WITH_THREAD */
4103     OpenSSL_add_all_algorithms();
4104 
4105     /* Add symbols to module dict */
4106     PySSLErrorObject = PyErr_NewExceptionWithDoc(
4107         "ssl.SSLError", SSLError_doc,
4108         PySocketModule.error, NULL);
4109     if (PySSLErrorObject == NULL)
4110         return;
4111     ((PyTypeObject *)PySSLErrorObject)->tp_str = (reprfunc)SSLError_str;
4112 
4113     PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4114         "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4115         PySSLErrorObject, NULL);
4116     PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4117         "ssl.SSLWantReadError", SSLWantReadError_doc,
4118         PySSLErrorObject, NULL);
4119     PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4120         "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4121         PySSLErrorObject, NULL);
4122     PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4123         "ssl.SSLSyscallError", SSLSyscallError_doc,
4124         PySSLErrorObject, NULL);
4125     PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4126         "ssl.SSLEOFError", SSLEOFError_doc,
4127         PySSLErrorObject, NULL);
4128     if (PySSLZeroReturnErrorObject == NULL
4129         || PySSLWantReadErrorObject == NULL
4130         || PySSLWantWriteErrorObject == NULL
4131         || PySSLSyscallErrorObject == NULL
4132         || PySSLEOFErrorObject == NULL)
4133         return;
4134 
4135     ((PyTypeObject *)PySSLZeroReturnErrorObject)->tp_str = (reprfunc)SSLError_str;
4136     ((PyTypeObject *)PySSLWantReadErrorObject)->tp_str = (reprfunc)SSLError_str;
4137     ((PyTypeObject *)PySSLWantWriteErrorObject)->tp_str = (reprfunc)SSLError_str;
4138     ((PyTypeObject *)PySSLSyscallErrorObject)->tp_str = (reprfunc)SSLError_str;
4139     ((PyTypeObject *)PySSLEOFErrorObject)->tp_str = (reprfunc)SSLError_str;
4140 
4141     if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4142         || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4143         || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4144         || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4145         || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4146         || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
4147         return;
4148     if (PyDict_SetItemString(d, "_SSLContext",
4149                              (PyObject *)&PySSLContext_Type) != 0)
4150         return;
4151     if (PyDict_SetItemString(d, "_SSLSocket",
4152                              (PyObject *)&PySSLSocket_Type) != 0)
4153         return;
4154     PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4155                             PY_SSL_ERROR_ZERO_RETURN);
4156     PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4157                             PY_SSL_ERROR_WANT_READ);
4158     PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4159                             PY_SSL_ERROR_WANT_WRITE);
4160     PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4161                             PY_SSL_ERROR_WANT_X509_LOOKUP);
4162     PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4163                             PY_SSL_ERROR_SYSCALL);
4164     PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4165                             PY_SSL_ERROR_SSL);
4166     PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4167                             PY_SSL_ERROR_WANT_CONNECT);
4168     /* non ssl.h errorcodes */
4169     PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4170                             PY_SSL_ERROR_EOF);
4171     PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4172                             PY_SSL_ERROR_INVALID_ERROR_CODE);
4173     /* cert requirements */
4174     PyModule_AddIntConstant(m, "CERT_NONE",
4175                             PY_SSL_CERT_NONE);
4176     PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4177                             PY_SSL_CERT_OPTIONAL);
4178     PyModule_AddIntConstant(m, "CERT_REQUIRED",
4179                             PY_SSL_CERT_REQUIRED);
4180     /* CRL verification for verification_flags */
4181     PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4182                             0);
4183     PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4184                             X509_V_FLAG_CRL_CHECK);
4185     PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4186                             X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4187     PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4188                             X509_V_FLAG_X509_STRICT);
4189 #ifdef X509_V_FLAG_TRUSTED_FIRST
4190     PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4191                             X509_V_FLAG_TRUSTED_FIRST);
4192 #endif
4193 
4194     /* Alert Descriptions from ssl.h */
4195     /* note RESERVED constants no longer intended for use have been removed */
4196     /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4197 
4198 #define ADD_AD_CONSTANT(s) \
4199     PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4200                             SSL_AD_##s)
4201 
4202     ADD_AD_CONSTANT(CLOSE_NOTIFY);
4203     ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4204     ADD_AD_CONSTANT(BAD_RECORD_MAC);
4205     ADD_AD_CONSTANT(RECORD_OVERFLOW);
4206     ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4207     ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4208     ADD_AD_CONSTANT(BAD_CERTIFICATE);
4209     ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4210     ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4211     ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4212     ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4213     ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4214     ADD_AD_CONSTANT(UNKNOWN_CA);
4215     ADD_AD_CONSTANT(ACCESS_DENIED);
4216     ADD_AD_CONSTANT(DECODE_ERROR);
4217     ADD_AD_CONSTANT(DECRYPT_ERROR);
4218     ADD_AD_CONSTANT(PROTOCOL_VERSION);
4219     ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4220     ADD_AD_CONSTANT(INTERNAL_ERROR);
4221     ADD_AD_CONSTANT(USER_CANCELLED);
4222     ADD_AD_CONSTANT(NO_RENEGOTIATION);
4223     /* Not all constants are in old OpenSSL versions */
4224 #ifdef SSL_AD_UNSUPPORTED_EXTENSION
4225     ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4226 #endif
4227 #ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4228     ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4229 #endif
4230 #ifdef SSL_AD_UNRECOGNIZED_NAME
4231     ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4232 #endif
4233 #ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4234     ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4235 #endif
4236 #ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4237     ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4238 #endif
4239 #ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4240     ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4241 #endif
4242 
4243 #undef ADD_AD_CONSTANT
4244 
4245     /* protocol versions */
4246 #ifndef OPENSSL_NO_SSL2
4247     PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4248                             PY_SSL_VERSION_SSL2);
4249 #endif
4250 #ifndef OPENSSL_NO_SSL3
4251     PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4252                             PY_SSL_VERSION_SSL3);
4253 #endif
4254     PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4255                             PY_SSL_VERSION_TLS);
4256     PyModule_AddIntConstant(m, "PROTOCOL_TLS",
4257                             PY_SSL_VERSION_TLS);
4258     PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4259                             PY_SSL_VERSION_TLS1);
4260 #if HAVE_TLSv1_2
4261     PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4262                             PY_SSL_VERSION_TLS1_1);
4263     PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4264                             PY_SSL_VERSION_TLS1_2);
4265 #endif
4266 
4267     /* protocol options */
4268     PyModule_AddIntConstant(m, "OP_ALL",
4269                             SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
4270     PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4271     PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4272     PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
4273 #if HAVE_TLSv1_2
4274     PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4275     PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4276 #endif
4277     PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4278                             SSL_OP_CIPHER_SERVER_PREFERENCE);
4279     PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
4280 #ifdef SSL_OP_SINGLE_ECDH_USE
4281     PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
4282 #endif
4283 #ifdef SSL_OP_NO_COMPRESSION
4284     PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4285                             SSL_OP_NO_COMPRESSION);
4286 #endif
4287 
4288 #if HAVE_SNI
4289     r = Py_True;
4290 #else
4291     r = Py_False;
4292 #endif
4293     Py_INCREF(r);
4294     PyModule_AddObject(m, "HAS_SNI", r);
4295 
4296 #if HAVE_OPENSSL_FINISHED
4297     r = Py_True;
4298 #else
4299     r = Py_False;
4300 #endif
4301     Py_INCREF(r);
4302     PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4303 
4304 #ifdef OPENSSL_NO_ECDH
4305     r = Py_False;
4306 #else
4307     r = Py_True;
4308 #endif
4309     Py_INCREF(r);
4310     PyModule_AddObject(m, "HAS_ECDH", r);
4311 
4312 #ifdef OPENSSL_NPN_NEGOTIATED
4313     r = Py_True;
4314 #else
4315     r = Py_False;
4316 #endif
4317     Py_INCREF(r);
4318     PyModule_AddObject(m, "HAS_NPN", r);
4319 
4320 #ifdef HAVE_ALPN
4321     r = Py_True;
4322 #else
4323     r = Py_False;
4324 #endif
4325     Py_INCREF(r);
4326     PyModule_AddObject(m, "HAS_ALPN", r);
4327 
4328     /* Mappings for error codes */
4329     err_codes_to_names = PyDict_New();
4330     err_names_to_codes = PyDict_New();
4331     if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4332         return;
4333     errcode = error_codes;
4334     while (errcode->mnemonic != NULL) {
4335         PyObject *mnemo, *key;
4336         mnemo = PyUnicode_FromString(errcode->mnemonic);
4337         key = Py_BuildValue("ii", errcode->library, errcode->reason);
4338         if (mnemo == NULL || key == NULL)
4339             return;
4340         if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4341             return;
4342         if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4343             return;
4344         Py_DECREF(key);
4345         Py_DECREF(mnemo);
4346         errcode++;
4347     }
4348     if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4349         return;
4350     if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4351         return;
4352 
4353     lib_codes_to_names = PyDict_New();
4354     if (lib_codes_to_names == NULL)
4355         return;
4356     libcode = library_codes;
4357     while (libcode->library != NULL) {
4358         PyObject *mnemo, *key;
4359         key = PyLong_FromLong(libcode->code);
4360         mnemo = PyUnicode_FromString(libcode->library);
4361         if (key == NULL || mnemo == NULL)
4362             return;
4363         if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4364             return;
4365         Py_DECREF(key);
4366         Py_DECREF(mnemo);
4367         libcode++;
4368     }
4369     if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4370         return;
4371 
4372     /* OpenSSL version */
4373     /* SSLeay() gives us the version of the library linked against,
4374        which could be different from the headers version.
4375     */
4376     libver = SSLeay();
4377     r = PyLong_FromUnsignedLong(libver);
4378     if (r == NULL)
4379         return;
4380     if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4381         return;
4382     parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4383     r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4384     if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4385         return;
4386     r = PyString_FromString(SSLeay_version(SSLEAY_VERSION));
4387     if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4388         return;
4389 
4390     libver = OPENSSL_VERSION_NUMBER;
4391     parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4392     r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4393     if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4394         return;
4395 }
4396