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