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 
19 #include "Python.h"
20 
21 #include "pythread.h"
22 
23 /* Redefined below for Windows debug builds after important #includes */
24 #define _PySSL_FIX_ERRNO
25 
26 #define PySSL_BEGIN_ALLOW_THREADS_S(save) \
27     do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
28 #define PySSL_END_ALLOW_THREADS_S(save) \
29     do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } _PySSL_FIX_ERRNO; } while (0)
30 #define PySSL_BEGIN_ALLOW_THREADS { \
31             PyThreadState *_save = NULL;  \
32             PySSL_BEGIN_ALLOW_THREADS_S(_save);
33 #define PySSL_BLOCK_THREADS     PySSL_END_ALLOW_THREADS_S(_save);
34 #define PySSL_UNBLOCK_THREADS   PySSL_BEGIN_ALLOW_THREADS_S(_save);
35 #define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
36 
37 /* Include symbols from _socket module */
38 #include "socketmodule.h"
39 
40 static PySocketModule_APIObject PySocketModule;
41 
42 #if defined(HAVE_POLL_H)
43 #include <poll.h>
44 #elif defined(HAVE_SYS_POLL_H)
45 #include <sys/poll.h>
46 #endif
47 
48 /* Don't warn about deprecated functions */
49 #ifdef __GNUC__
50 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
51 #endif
52 #ifdef __clang__
53 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
54 #endif
55 
56 /* Include OpenSSL header files */
57 #include "openssl/rsa.h"
58 #include "openssl/crypto.h"
59 #include "openssl/x509.h"
60 #include "openssl/x509v3.h"
61 #include "openssl/pem.h"
62 #include "openssl/ssl.h"
63 #include "openssl/err.h"
64 #include "openssl/rand.h"
65 #include "openssl/bio.h"
66 #include "openssl/dh.h"
67 
68 #ifndef HAVE_X509_VERIFY_PARAM_SET1_HOST
69 #  ifdef LIBRESSL_VERSION_NUMBER
70 #    error "LibreSSL is missing X509_VERIFY_PARAM_set1_host(), see https://github.com/libressl-portable/portable/issues/381"
71 #  elif OPENSSL_VERSION_NUMBER > 0x1000200fL
72 #    define HAVE_X509_VERIFY_PARAM_SET1_HOST
73 #  else
74 #    error "libssl is too old and does not support X509_VERIFY_PARAM_set1_host()"
75 #  endif
76 #endif
77 
78 #ifndef OPENSSL_THREADS
79 #  error "OPENSSL_THREADS is not defined, Python requires thread-safe OpenSSL"
80 #endif
81 
82 /* SSL error object */
83 static PyObject *PySSLErrorObject;
84 static PyObject *PySSLCertVerificationErrorObject;
85 static PyObject *PySSLZeroReturnErrorObject;
86 static PyObject *PySSLWantReadErrorObject;
87 static PyObject *PySSLWantWriteErrorObject;
88 static PyObject *PySSLSyscallErrorObject;
89 static PyObject *PySSLEOFErrorObject;
90 
91 /* Error mappings */
92 static PyObject *err_codes_to_names;
93 static PyObject *err_names_to_codes;
94 static PyObject *lib_codes_to_names;
95 
96 struct py_ssl_error_code {
97     const char *mnemonic;
98     int library, reason;
99 };
100 struct py_ssl_library_code {
101     const char *library;
102     int code;
103 };
104 
105 #if defined(MS_WINDOWS) && defined(Py_DEBUG)
106 /* Debug builds on Windows rely on getting errno directly from OpenSSL.
107  * However, because it uses a different CRT, we need to transfer the
108  * value of errno from OpenSSL into our debug CRT.
109  *
110  * Don't be fooled - this is horribly ugly code. The only reasonable
111  * alternative is to do both debug and release builds of OpenSSL, which
112  * requires much uglier code to transform their automatically generated
113  * makefile. This is the lesser of all the evils.
114  */
115 
_PySSLFixErrno(void)116 static void _PySSLFixErrno(void) {
117     HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
118     if (!ucrtbase) {
119         /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
120          * have a catastrophic failure, but this function is not the
121          * place to raise it. */
122         return;
123     }
124 
125     typedef int *(__stdcall *errno_func)(void);
126     errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
127     if (ssl_errno) {
128         errno = *ssl_errno();
129         *ssl_errno() = 0;
130     } else {
131         errno = ENOTRECOVERABLE;
132     }
133 }
134 
135 #undef _PySSL_FIX_ERRNO
136 #define _PySSL_FIX_ERRNO _PySSLFixErrno()
137 #endif
138 
139 /* Include generated data (error codes) */
140 #include "_ssl_data.h"
141 
142 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
143 #  define OPENSSL_VERSION_1_1 1
144 #  define PY_OPENSSL_1_1_API 1
145 #endif
146 
147 /* OpenSSL API compat */
148 #ifdef OPENSSL_API_COMPAT
149 #if OPENSSL_API_COMPAT >= 0x10100000L
150 
151 /* OpenSSL API 1.1.0+ does not include version methods */
152 #ifndef OPENSSL_NO_TLS1_METHOD
153 #define OPENSSL_NO_TLS1_METHOD 1
154 #endif
155 #ifndef OPENSSL_NO_TLS1_1_METHOD
156 #define OPENSSL_NO_TLS1_1_METHOD 1
157 #endif
158 #ifndef OPENSSL_NO_TLS1_2_METHOD
159 #define OPENSSL_NO_TLS1_2_METHOD 1
160 #endif
161 
162 #endif /* >= 1.1.0 compcat */
163 #endif /* OPENSSL_API_COMPAT */
164 
165 /* LibreSSL 2.7.0 provides necessary OpenSSL 1.1.0 APIs */
166 #if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x2070000fL
167 #  define PY_OPENSSL_1_1_API 1
168 #endif
169 
170 /* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
171  * This includes the SSL_set_SSL_CTX() function.
172  */
173 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
174 # define HAVE_SNI 1
175 #else
176 # define HAVE_SNI 0
177 #endif
178 
179 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
180 # define HAVE_ALPN 1
181 #else
182 # define HAVE_ALPN 0
183 #endif
184 
185 /* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
186  * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
187  * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
188  * OpenSSL 1.0.1+ and LibreSSL.
189  * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
190  */
191 #ifdef OPENSSL_NO_NEXTPROTONEG
192 # define HAVE_NPN 0
193 #elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
194 # define HAVE_NPN 0
195 #elif defined(TLSEXT_TYPE_next_proto_neg)
196 # define HAVE_NPN 1
197 #else
198 # define HAVE_NPN 0
199 #endif
200 
201 #ifndef INVALID_SOCKET /* MS defines this */
202 #define INVALID_SOCKET (-1)
203 #endif
204 
205 /* OpenSSL 1.0.2 and LibreSSL needs extra code for locking */
206 #ifndef OPENSSL_VERSION_1_1
207 #define HAVE_OPENSSL_CRYPTO_LOCK
208 #endif
209 
210 #if defined(OPENSSL_VERSION_1_1) && !defined(OPENSSL_NO_SSL2)
211 #define OPENSSL_NO_SSL2
212 #endif
213 
214 #ifndef PY_OPENSSL_1_1_API
215 /* OpenSSL 1.1 API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 */
216 
217 #define TLS_method SSLv23_method
218 #define TLS_client_method SSLv23_client_method
219 #define TLS_server_method SSLv23_server_method
220 #define ASN1_STRING_get0_data ASN1_STRING_data
221 #define X509_get0_notBefore X509_get_notBefore
222 #define X509_get0_notAfter X509_get_notAfter
223 #define OpenSSL_version_num SSLeay
224 #define OpenSSL_version SSLeay_version
225 #define OPENSSL_VERSION SSLEAY_VERSION
226 
X509_NAME_ENTRY_set(const X509_NAME_ENTRY * ne)227 static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
228 {
229     return ne->set;
230 }
231 
232 #ifndef OPENSSL_NO_COMP
233 /* LCOV_EXCL_START */
COMP_get_type(const COMP_METHOD * meth)234 static int COMP_get_type(const COMP_METHOD *meth)
235 {
236     return meth->type;
237 }
238 /* LCOV_EXCL_STOP */
239 #endif
240 
SSL_CTX_get_default_passwd_cb(SSL_CTX * ctx)241 static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
242 {
243     return ctx->default_passwd_callback;
244 }
245 
SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX * ctx)246 static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
247 {
248     return ctx->default_passwd_callback_userdata;
249 }
250 
X509_OBJECT_get_type(X509_OBJECT * x)251 static int X509_OBJECT_get_type(X509_OBJECT *x)
252 {
253     return x->type;
254 }
255 
X509_OBJECT_get0_X509(X509_OBJECT * x)256 static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
257 {
258     return x->data.x509;
259 }
260 
BIO_up_ref(BIO * b)261 static int BIO_up_ref(BIO *b)
262 {
263     CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
264     return 1;
265 }
266 
STACK_OF(X509_OBJECT)267 static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
268     return store->objs;
269 }
270 
271 static int
SSL_SESSION_has_ticket(const SSL_SESSION * s)272 SSL_SESSION_has_ticket(const SSL_SESSION *s)
273 {
274     return (s->tlsext_ticklen > 0) ? 1 : 0;
275 }
276 
277 static unsigned long
SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION * s)278 SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
279 {
280     return s->tlsext_tick_lifetime_hint;
281 }
282 
283 #endif /* OpenSSL < 1.1.0 or LibreSSL < 2.7.0 */
284 
285 /* Default cipher suites */
286 #ifndef PY_SSL_DEFAULT_CIPHERS
287 #define PY_SSL_DEFAULT_CIPHERS 1
288 #endif
289 
290 #if PY_SSL_DEFAULT_CIPHERS == 0
291   #ifndef PY_SSL_DEFAULT_CIPHER_STRING
292      #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
293   #endif
294 #elif PY_SSL_DEFAULT_CIPHERS == 1
295 /* Python custom selection of sensible cipher suites
296  * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
297  * !aNULL:!eNULL: really no NULL ciphers
298  * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
299  * !aDSS: no authentication with discrete logarithm DSA algorithm
300  * !SRP:!PSK: no secure remote password or pre-shared key authentication
301  */
302   #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
303 #elif PY_SSL_DEFAULT_CIPHERS == 2
304 /* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
305   #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
306 #else
307   #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
308 #endif
309 
310 
311 enum py_ssl_error {
312     /* these mirror ssl.h */
313     PY_SSL_ERROR_NONE,
314     PY_SSL_ERROR_SSL,
315     PY_SSL_ERROR_WANT_READ,
316     PY_SSL_ERROR_WANT_WRITE,
317     PY_SSL_ERROR_WANT_X509_LOOKUP,
318     PY_SSL_ERROR_SYSCALL,     /* look at error stack/return value/errno */
319     PY_SSL_ERROR_ZERO_RETURN,
320     PY_SSL_ERROR_WANT_CONNECT,
321     /* start of non ssl.h errorcodes */
322     PY_SSL_ERROR_EOF,         /* special case of SSL_ERROR_SYSCALL */
323     PY_SSL_ERROR_NO_SOCKET,   /* socket has been GC'd */
324     PY_SSL_ERROR_INVALID_ERROR_CODE
325 };
326 
327 enum py_ssl_server_or_client {
328     PY_SSL_CLIENT,
329     PY_SSL_SERVER
330 };
331 
332 enum py_ssl_cert_requirements {
333     PY_SSL_CERT_NONE,
334     PY_SSL_CERT_OPTIONAL,
335     PY_SSL_CERT_REQUIRED
336 };
337 
338 enum py_ssl_version {
339     PY_SSL_VERSION_SSL2,
340     PY_SSL_VERSION_SSL3=1,
341     PY_SSL_VERSION_TLS, /* SSLv23 */
342     PY_SSL_VERSION_TLS1,
343     PY_SSL_VERSION_TLS1_1,
344     PY_SSL_VERSION_TLS1_2,
345     PY_SSL_VERSION_TLS_CLIENT=0x10,
346     PY_SSL_VERSION_TLS_SERVER,
347 };
348 
349 enum py_proto_version {
350     PY_PROTO_MINIMUM_SUPPORTED = -2,
351     PY_PROTO_SSLv3 = SSL3_VERSION,
352     PY_PROTO_TLSv1 = TLS1_VERSION,
353     PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
354     PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
355 #ifdef TLS1_3_VERSION
356     PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
357 #else
358     PY_PROTO_TLSv1_3 = 0x304,
359 #endif
360     PY_PROTO_MAXIMUM_SUPPORTED = -1,
361 
362 /* OpenSSL has no dedicated API to set the minimum version to the maximum
363  * available version, and the other way around. We have to figure out the
364  * minimum and maximum available version on our own and hope for the best.
365  */
366 #if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
367     PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
368 #elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
369     PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
370 #elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
371     PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
372 #elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
373     PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
374 #elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
375     PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
376 #else
377     #error "PY_PROTO_MINIMUM_AVAILABLE not found"
378 #endif
379 
380 #if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
381     PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
382 #elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
383     PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
384 #elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
385     PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
386 #elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
387     PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
388 #elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
389     PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
390 #else
391     #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
392 #endif
393 };
394 
395 
396 /* serves as a flag to see whether we've initialized the SSL thread support. */
397 /* 0 means no, greater than 0 means yes */
398 
399 static unsigned int _ssl_locks_count = 0;
400 
401 /* SSL socket object */
402 
403 #define X509_NAME_MAXLEN 256
404 
405 /* SSL_CTX_clear_options() and SSL_clear_options() were first added in
406  * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
407  * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
408 #if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
409 # define HAVE_SSL_CTX_CLEAR_OPTIONS
410 #else
411 # undef HAVE_SSL_CTX_CLEAR_OPTIONS
412 #endif
413 
414 /* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
415  * older SSL, but let's be safe */
416 #define PySSL_CB_MAXLEN 128
417 
418 
419 typedef struct {
420     PyObject_HEAD
421     SSL_CTX *ctx;
422 #if HAVE_NPN
423     unsigned char *npn_protocols;
424     int npn_protocols_len;
425 #endif
426 #if HAVE_ALPN
427     unsigned char *alpn_protocols;
428     unsigned int alpn_protocols_len;
429 #endif
430 #ifndef OPENSSL_NO_TLSEXT
431     PyObject *set_sni_cb;
432 #endif
433     int check_hostname;
434     /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
435      * We have to maintain our own copy. OpenSSL's hostflags default to 0.
436      */
437     unsigned int hostflags;
438     int protocol;
439 #ifdef TLS1_3_VERSION
440     int post_handshake_auth;
441 #endif
442 } PySSLContext;
443 
444 typedef struct {
445     int ssl; /* last seen error from SSL */
446     int c; /* last seen error from libc */
447 #ifdef MS_WINDOWS
448     int ws; /* last seen error from winsock */
449 #endif
450 } _PySSLError;
451 
452 typedef struct {
453     PyObject_HEAD
454     PyObject *Socket; /* weakref to socket on which we're layered */
455     SSL *ssl;
456     PySSLContext *ctx; /* weakref to SSL context */
457     char shutdown_seen_zero;
458     enum py_ssl_server_or_client socket_type;
459     PyObject *owner; /* Python level "owner" passed to servername callback */
460     PyObject *server_hostname;
461     _PySSLError err; /* last seen error from various sources */
462 } PySSLSocket;
463 
464 typedef struct {
465     PyObject_HEAD
466     BIO *bio;
467     int eof_written;
468 } PySSLMemoryBIO;
469 
470 typedef struct {
471     PyObject_HEAD
472     SSL_SESSION *session;
473     PySSLContext *ctx;
474 } PySSLSession;
475 
476 static PyTypeObject PySSLContext_Type;
477 static PyTypeObject PySSLSocket_Type;
478 static PyTypeObject PySSLMemoryBIO_Type;
479 static PyTypeObject PySSLSession_Type;
480 
_PySSL_errno(int failed,const SSL * ssl,int retcode)481 static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
482 {
483     _PySSLError err = { 0 };
484     if (failed) {
485 #ifdef MS_WINDOWS
486         err.ws = WSAGetLastError();
487         _PySSL_FIX_ERRNO;
488 #endif
489         err.c = errno;
490         err.ssl = SSL_get_error(ssl, retcode);
491     }
492     return err;
493 }
494 
495 /*[clinic input]
496 module _ssl
497 class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
498 class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
499 class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
500 class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
501 [clinic start generated code]*/
502 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
503 
504 #include "clinic/_ssl.c.h"
505 
506 static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
507 
508 static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
509 static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
510 #define PySSLSocket_Check(v)    (Py_TYPE(v) == &PySSLSocket_Type)
511 #define PySSLMemoryBIO_Check(v)    (Py_TYPE(v) == &PySSLMemoryBIO_Type)
512 #define PySSLSession_Check(v)   (Py_TYPE(v) == &PySSLSession_Type)
513 
514 typedef enum {
515     SOCKET_IS_NONBLOCKING,
516     SOCKET_IS_BLOCKING,
517     SOCKET_HAS_TIMED_OUT,
518     SOCKET_HAS_BEEN_CLOSED,
519     SOCKET_TOO_LARGE_FOR_SELECT,
520     SOCKET_OPERATION_OK
521 } timeout_state;
522 
523 /* Wrap error strings with filename and line # */
524 #define ERRSTR1(x,y,z) (x ":" y ": " z)
525 #define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
526 
527 /* Get the socket from a PySSLSocket, if it has one */
528 #define GET_SOCKET(obj) ((obj)->Socket ? \
529     (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
530 
531 /* If sock is NULL, use a timeout of 0 second */
532 #define GET_SOCKET_TIMEOUT(sock) \
533     ((sock != NULL) ? (sock)->sock_timeout : 0)
534 
535 /*
536  * SSL errors.
537  */
538 
539 PyDoc_STRVAR(SSLError_doc,
540 "An error occurred in the SSL implementation.");
541 
542 PyDoc_STRVAR(SSLCertVerificationError_doc,
543 "A certificate could not be verified.");
544 
545 PyDoc_STRVAR(SSLZeroReturnError_doc,
546 "SSL/TLS session closed cleanly.");
547 
548 PyDoc_STRVAR(SSLWantReadError_doc,
549 "Non-blocking SSL socket needs to read more data\n"
550 "before the requested operation can be completed.");
551 
552 PyDoc_STRVAR(SSLWantWriteError_doc,
553 "Non-blocking SSL socket needs to write more data\n"
554 "before the requested operation can be completed.");
555 
556 PyDoc_STRVAR(SSLSyscallError_doc,
557 "System error when attempting SSL operation.");
558 
559 PyDoc_STRVAR(SSLEOFError_doc,
560 "SSL/TLS connection terminated abruptly.");
561 
562 static PyObject *
SSLError_str(PyOSErrorObject * self)563 SSLError_str(PyOSErrorObject *self)
564 {
565     if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
566         Py_INCREF(self->strerror);
567         return self->strerror;
568     }
569     else
570         return PyObject_Str(self->args);
571 }
572 
573 static PyType_Slot sslerror_type_slots[] = {
574     {Py_tp_base, NULL},  /* Filled out in module init as it's not a constant */
575     {Py_tp_doc, SSLError_doc},
576     {Py_tp_str, SSLError_str},
577     {0, 0},
578 };
579 
580 static PyType_Spec sslerror_type_spec = {
581     "ssl.SSLError",
582     sizeof(PyOSErrorObject),
583     0,
584     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
585     sslerror_type_slots
586 };
587 
588 static void
fill_and_set_sslerror(PySSLSocket * sslsock,PyObject * type,int ssl_errno,const char * errstr,int lineno,unsigned long errcode)589 fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
590                       const char *errstr, int lineno, unsigned long errcode)
591 {
592     PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
593     PyObject *verify_obj = NULL, *verify_code_obj = NULL;
594     PyObject *init_value, *msg, *key;
595     _Py_IDENTIFIER(reason);
596     _Py_IDENTIFIER(library);
597     _Py_IDENTIFIER(verify_message);
598     _Py_IDENTIFIER(verify_code);
599 
600     if (errcode != 0) {
601         int lib, reason;
602 
603         lib = ERR_GET_LIB(errcode);
604         reason = ERR_GET_REASON(errcode);
605         key = Py_BuildValue("ii", lib, reason);
606         if (key == NULL)
607             goto fail;
608         reason_obj = PyDict_GetItem(err_codes_to_names, key);
609         Py_DECREF(key);
610         if (reason_obj == NULL) {
611             /* XXX if reason < 100, it might reflect a library number (!!) */
612             PyErr_Clear();
613         }
614         key = PyLong_FromLong(lib);
615         if (key == NULL)
616             goto fail;
617         lib_obj = PyDict_GetItem(lib_codes_to_names, key);
618         Py_DECREF(key);
619         if (lib_obj == NULL) {
620             PyErr_Clear();
621         }
622         if (errstr == NULL)
623             errstr = ERR_reason_error_string(errcode);
624     }
625     if (errstr == NULL)
626         errstr = "unknown error";
627 
628     /* verify code for cert validation error */
629     if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
630         const char *verify_str = NULL;
631         long verify_code;
632 
633         verify_code = SSL_get_verify_result(sslsock->ssl);
634         verify_code_obj = PyLong_FromLong(verify_code);
635         if (verify_code_obj == NULL) {
636             goto fail;
637         }
638 
639         switch (verify_code) {
640 #ifdef X509_V_ERR_HOSTNAME_MISMATCH
641         /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
642         case X509_V_ERR_HOSTNAME_MISMATCH:
643             verify_obj = PyUnicode_FromFormat(
644                 "Hostname mismatch, certificate is not valid for '%S'.",
645                 sslsock->server_hostname
646             );
647             break;
648 #endif
649 #ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
650         case X509_V_ERR_IP_ADDRESS_MISMATCH:
651             verify_obj = PyUnicode_FromFormat(
652                 "IP address mismatch, certificate is not valid for '%S'.",
653                 sslsock->server_hostname
654             );
655             break;
656 #endif
657         default:
658             verify_str = X509_verify_cert_error_string(verify_code);
659             if (verify_str != NULL) {
660                 verify_obj = PyUnicode_FromString(verify_str);
661             } else {
662                 verify_obj = Py_None;
663                 Py_INCREF(verify_obj);
664             }
665             break;
666         }
667         if (verify_obj == NULL) {
668             goto fail;
669         }
670     }
671 
672     if (verify_obj && reason_obj && lib_obj)
673         msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
674                                    lib_obj, reason_obj, errstr, verify_obj,
675                                    lineno);
676     else if (reason_obj && lib_obj)
677         msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
678                                    lib_obj, reason_obj, errstr, lineno);
679     else if (lib_obj)
680         msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
681                                    lib_obj, errstr, lineno);
682     else
683         msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
684     if (msg == NULL)
685         goto fail;
686 
687     init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
688     if (init_value == NULL)
689         goto fail;
690 
691     err_value = PyObject_CallObject(type, init_value);
692     Py_DECREF(init_value);
693     if (err_value == NULL)
694         goto fail;
695 
696     if (reason_obj == NULL)
697         reason_obj = Py_None;
698     if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
699         goto fail;
700 
701     if (lib_obj == NULL)
702         lib_obj = Py_None;
703     if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
704         goto fail;
705 
706     if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
707         /* Only set verify code / message for SSLCertVerificationError */
708         if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
709                                 verify_code_obj))
710             goto fail;
711         if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
712             goto fail;
713     }
714 
715     PyErr_SetObject(type, err_value);
716 fail:
717     Py_XDECREF(err_value);
718     Py_XDECREF(verify_code_obj);
719     Py_XDECREF(verify_obj);
720 }
721 
722 static PyObject *
PySSL_SetError(PySSLSocket * sslsock,int ret,const char * filename,int lineno)723 PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
724 {
725     PyObject *type = PySSLErrorObject;
726     char *errstr = NULL;
727     _PySSLError err;
728     enum py_ssl_error p = PY_SSL_ERROR_NONE;
729     unsigned long e = 0;
730 
731     assert(ret <= 0);
732     e = ERR_peek_last_error();
733 
734     if (sslsock->ssl != NULL) {
735         err = sslsock->err;
736 
737         switch (err.ssl) {
738         case SSL_ERROR_ZERO_RETURN:
739             errstr = "TLS/SSL connection has been closed (EOF)";
740             type = PySSLZeroReturnErrorObject;
741             p = PY_SSL_ERROR_ZERO_RETURN;
742             break;
743         case SSL_ERROR_WANT_READ:
744             errstr = "The operation did not complete (read)";
745             type = PySSLWantReadErrorObject;
746             p = PY_SSL_ERROR_WANT_READ;
747             break;
748         case SSL_ERROR_WANT_WRITE:
749             p = PY_SSL_ERROR_WANT_WRITE;
750             type = PySSLWantWriteErrorObject;
751             errstr = "The operation did not complete (write)";
752             break;
753         case SSL_ERROR_WANT_X509_LOOKUP:
754             p = PY_SSL_ERROR_WANT_X509_LOOKUP;
755             errstr = "The operation did not complete (X509 lookup)";
756             break;
757         case SSL_ERROR_WANT_CONNECT:
758             p = PY_SSL_ERROR_WANT_CONNECT;
759             errstr = "The operation did not complete (connect)";
760             break;
761         case SSL_ERROR_SYSCALL:
762         {
763             if (e == 0) {
764                 PySocketSockObject *s = GET_SOCKET(sslsock);
765                 if (ret == 0 || (((PyObject *)s) == Py_None)) {
766                     p = PY_SSL_ERROR_EOF;
767                     type = PySSLEOFErrorObject;
768                     errstr = "EOF occurred in violation of protocol";
769                 } else if (s && ret == -1) {
770                     /* underlying BIO reported an I/O error */
771                     ERR_clear_error();
772 #ifdef MS_WINDOWS
773                     if (err.ws) {
774                         return PyErr_SetFromWindowsErr(err.ws);
775                     }
776 #endif
777                     if (err.c) {
778                         errno = err.c;
779                         return PyErr_SetFromErrno(PyExc_OSError);
780                     }
781                     Py_INCREF(s);
782                     s->errorhandler();
783                     Py_DECREF(s);
784                     return NULL;
785                 } else { /* possible? */
786                     p = PY_SSL_ERROR_SYSCALL;
787                     type = PySSLSyscallErrorObject;
788                     errstr = "Some I/O error occurred";
789                 }
790             } else {
791                 p = PY_SSL_ERROR_SYSCALL;
792             }
793             break;
794         }
795         case SSL_ERROR_SSL:
796         {
797             p = PY_SSL_ERROR_SSL;
798             if (e == 0) {
799                 /* possible? */
800                 errstr = "A failure in the SSL library occurred";
801             }
802             if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
803                     ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
804                 type = PySSLCertVerificationErrorObject;
805             }
806             break;
807         }
808         default:
809             p = PY_SSL_ERROR_INVALID_ERROR_CODE;
810             errstr = "Invalid error code";
811         }
812     }
813     fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
814     ERR_clear_error();
815     return NULL;
816 }
817 
818 static PyObject *
_setSSLError(const char * errstr,int errcode,const char * filename,int lineno)819 _setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
820 
821     if (errstr == NULL)
822         errcode = ERR_peek_last_error();
823     else
824         errcode = 0;
825     fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
826     ERR_clear_error();
827     return NULL;
828 }
829 
830 /*
831  * SSL objects
832  */
833 
834 static int
_ssl_configure_hostname(PySSLSocket * self,const char * server_hostname)835 _ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
836 {
837     int retval = -1;
838     ASN1_OCTET_STRING *ip;
839     PyObject *hostname;
840     size_t len;
841 
842     assert(server_hostname);
843 
844     /* Disable OpenSSL's special mode with leading dot in hostname:
845      * When name starts with a dot (e.g ".example.com"), it will be
846      * matched by a certificate valid for any sub-domain of name.
847      */
848     len = strlen(server_hostname);
849     if (len == 0 || *server_hostname == '.') {
850         PyErr_SetString(
851             PyExc_ValueError,
852             "server_hostname cannot be an empty string or start with a "
853             "leading dot.");
854         return retval;
855     }
856 
857     /* inet_pton is not available on all platforms. */
858     ip = a2i_IPADDRESS(server_hostname);
859     if (ip == NULL) {
860         ERR_clear_error();
861     }
862 
863     hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
864     if (hostname == NULL) {
865         goto error;
866     }
867     self->server_hostname = hostname;
868 
869     /* Only send SNI extension for non-IP hostnames */
870     if (ip == NULL) {
871         if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
872             _setSSLError(NULL, 0, __FILE__, __LINE__);
873         }
874     }
875     if (self->ctx->check_hostname) {
876         X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
877         if (ip == NULL) {
878             if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
879                                              strlen(server_hostname))) {
880                 _setSSLError(NULL, 0, __FILE__, __LINE__);
881                 goto error;
882             }
883         } else {
884             if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_get0_data(ip),
885                                            ASN1_STRING_length(ip))) {
886                 _setSSLError(NULL, 0, __FILE__, __LINE__);
887                 goto error;
888             }
889         }
890     }
891     retval = 0;
892   error:
893     if (ip != NULL) {
894         ASN1_OCTET_STRING_free(ip);
895     }
896     return retval;
897 }
898 
899 static PySSLSocket *
newPySSLSocket(PySSLContext * sslctx,PySocketSockObject * sock,enum py_ssl_server_or_client socket_type,char * server_hostname,PyObject * owner,PyObject * session,PySSLMemoryBIO * inbio,PySSLMemoryBIO * outbio)900 newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
901                enum py_ssl_server_or_client socket_type,
902                char *server_hostname,
903                PyObject *owner, PyObject *session,
904                PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
905 {
906     PySSLSocket *self;
907     SSL_CTX *ctx = sslctx->ctx;
908     _PySSLError err = { 0 };
909 
910     self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
911     if (self == NULL)
912         return NULL;
913 
914     self->ssl = NULL;
915     self->Socket = NULL;
916     self->ctx = sslctx;
917     Py_INCREF(sslctx);
918     self->shutdown_seen_zero = 0;
919     self->owner = NULL;
920     self->server_hostname = NULL;
921     self->err = err;
922 
923     /* Make sure the SSL error state is initialized */
924     (void) ERR_get_state();
925     ERR_clear_error();
926 
927     PySSL_BEGIN_ALLOW_THREADS
928     self->ssl = SSL_new(ctx);
929     PySSL_END_ALLOW_THREADS
930     if (self->ssl == NULL) {
931         Py_DECREF(self);
932         _setSSLError(NULL, 0, __FILE__, __LINE__);
933         return NULL;
934     }
935     SSL_set_app_data(self->ssl, self);
936     if (sock) {
937         SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
938     } else {
939         /* BIOs are reference counted and SSL_set_bio borrows our reference.
940          * To prevent a double free in memory_bio_dealloc() we need to take an
941          * extra reference here. */
942         BIO_up_ref(inbio->bio);
943         BIO_up_ref(outbio->bio);
944         SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
945     }
946     SSL_set_mode(self->ssl,
947                  SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
948 
949 #ifdef TLS1_3_VERSION
950     if (sslctx->post_handshake_auth == 1) {
951         if (socket_type == PY_SSL_SERVER) {
952             /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
953              * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
954              * only in combination with SSL_VERIFY_PEER flag. */
955             int mode = SSL_get_verify_mode(self->ssl);
956             if (mode & SSL_VERIFY_PEER) {
957                 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
958                 verify_cb = SSL_get_verify_callback(self->ssl);
959                 mode |= SSL_VERIFY_POST_HANDSHAKE;
960                 SSL_set_verify(self->ssl, mode, verify_cb);
961             }
962         } else {
963             /* client socket */
964             SSL_set_post_handshake_auth(self->ssl, 1);
965         }
966     }
967 #endif
968 
969     if (server_hostname != NULL) {
970         if (_ssl_configure_hostname(self, server_hostname) < 0) {
971             Py_DECREF(self);
972             return NULL;
973         }
974     }
975     /* If the socket is in non-blocking mode or timeout mode, set the BIO
976      * to non-blocking mode (blocking is the default)
977      */
978     if (sock && sock->sock_timeout >= 0) {
979         BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
980         BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
981     }
982 
983     PySSL_BEGIN_ALLOW_THREADS
984     if (socket_type == PY_SSL_CLIENT)
985         SSL_set_connect_state(self->ssl);
986     else
987         SSL_set_accept_state(self->ssl);
988     PySSL_END_ALLOW_THREADS
989 
990     self->socket_type = socket_type;
991     if (sock != NULL) {
992         self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
993         if (self->Socket == NULL) {
994             Py_DECREF(self);
995             return NULL;
996         }
997     }
998     if (owner && owner != Py_None) {
999         if (PySSL_set_owner(self, owner, NULL) == -1) {
1000             Py_DECREF(self);
1001             return NULL;
1002         }
1003     }
1004     if (session && session != Py_None) {
1005         if (PySSL_set_session(self, session, NULL) == -1) {
1006             Py_DECREF(self);
1007             return NULL;
1008         }
1009     }
1010     return self;
1011 }
1012 
1013 /* SSL object methods */
1014 
1015 /*[clinic input]
1016 _ssl._SSLSocket.do_handshake
1017 [clinic start generated code]*/
1018 
1019 static PyObject *
_ssl__SSLSocket_do_handshake_impl(PySSLSocket * self)1020 _ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
1021 /*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
1022 {
1023     int ret;
1024     _PySSLError err;
1025     int sockstate, nonblocking;
1026     PySocketSockObject *sock = GET_SOCKET(self);
1027     _PyTime_t timeout, deadline = 0;
1028     int has_timeout;
1029 
1030     if (sock) {
1031         if (((PyObject*)sock) == Py_None) {
1032             _setSSLError("Underlying socket connection gone",
1033                          PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1034             return NULL;
1035         }
1036         Py_INCREF(sock);
1037 
1038         /* just in case the blocking state of the socket has been changed */
1039         nonblocking = (sock->sock_timeout >= 0);
1040         BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1041         BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1042     }
1043 
1044     timeout = GET_SOCKET_TIMEOUT(sock);
1045     has_timeout = (timeout > 0);
1046     if (has_timeout)
1047         deadline = _PyTime_GetMonotonicClock() + timeout;
1048 
1049     /* Actually negotiate SSL connection */
1050     /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
1051     do {
1052         PySSL_BEGIN_ALLOW_THREADS
1053         ret = SSL_do_handshake(self->ssl);
1054         err = _PySSL_errno(ret < 1, self->ssl, ret);
1055         PySSL_END_ALLOW_THREADS
1056         self->err = err;
1057 
1058         if (PyErr_CheckSignals())
1059             goto error;
1060 
1061         if (has_timeout)
1062             timeout = deadline - _PyTime_GetMonotonicClock();
1063 
1064         if (err.ssl == SSL_ERROR_WANT_READ) {
1065             sockstate = PySSL_select(sock, 0, timeout);
1066         } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
1067             sockstate = PySSL_select(sock, 1, timeout);
1068         } else {
1069             sockstate = SOCKET_OPERATION_OK;
1070         }
1071 
1072         if (sockstate == SOCKET_HAS_TIMED_OUT) {
1073             PyErr_SetString(PySocketModule.timeout_error,
1074                             ERRSTR("The handshake operation timed out"));
1075             goto error;
1076         } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1077             PyErr_SetString(PySSLErrorObject,
1078                             ERRSTR("Underlying socket has been closed."));
1079             goto error;
1080         } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1081             PyErr_SetString(PySSLErrorObject,
1082                             ERRSTR("Underlying socket too large for select()."));
1083             goto error;
1084         } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1085             break;
1086         }
1087     } while (err.ssl == SSL_ERROR_WANT_READ ||
1088              err.ssl == SSL_ERROR_WANT_WRITE);
1089     Py_XDECREF(sock);
1090     if (ret < 1)
1091         return PySSL_SetError(self, ret, __FILE__, __LINE__);
1092 
1093     Py_RETURN_NONE;
1094 
1095 error:
1096     Py_XDECREF(sock);
1097     return NULL;
1098 }
1099 
1100 static PyObject *
_asn1obj2py(const ASN1_OBJECT * name,int no_name)1101 _asn1obj2py(const ASN1_OBJECT *name, int no_name)
1102 {
1103     char buf[X509_NAME_MAXLEN];
1104     char *namebuf = buf;
1105     int buflen;
1106     PyObject *name_obj = NULL;
1107 
1108     buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
1109     if (buflen < 0) {
1110         _setSSLError(NULL, 0, __FILE__, __LINE__);
1111         return NULL;
1112     }
1113     /* initial buffer is too small for oid + terminating null byte */
1114     if (buflen > X509_NAME_MAXLEN - 1) {
1115         /* make OBJ_obj2txt() calculate the required buflen */
1116         buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1117         /* allocate len + 1 for terminating NULL byte */
1118         namebuf = PyMem_Malloc(buflen + 1);
1119         if (namebuf == NULL) {
1120             PyErr_NoMemory();
1121             return NULL;
1122         }
1123         buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1124         if (buflen < 0) {
1125             _setSSLError(NULL, 0, __FILE__, __LINE__);
1126             goto done;
1127         }
1128     }
1129     if (!buflen && no_name) {
1130         Py_INCREF(Py_None);
1131         name_obj = Py_None;
1132     }
1133     else {
1134         name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1135     }
1136 
1137   done:
1138     if (buf != namebuf) {
1139         PyMem_Free(namebuf);
1140     }
1141     return name_obj;
1142 }
1143 
1144 static PyObject *
_create_tuple_for_attribute(ASN1_OBJECT * name,ASN1_STRING * value)1145 _create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1146 {
1147     Py_ssize_t buflen;
1148     unsigned char *valuebuf = NULL;
1149     PyObject *attr;
1150 
1151     buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1152     if (buflen < 0) {
1153         _setSSLError(NULL, 0, __FILE__, __LINE__);
1154         return NULL;
1155     }
1156     attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
1157     OPENSSL_free(valuebuf);
1158     return attr;
1159 }
1160 
1161 static PyObject *
_create_tuple_for_X509_NAME(X509_NAME * xname)1162 _create_tuple_for_X509_NAME (X509_NAME *xname)
1163 {
1164     PyObject *dn = NULL;    /* tuple which represents the "distinguished name" */
1165     PyObject *rdn = NULL;   /* tuple to hold a "relative distinguished name" */
1166     PyObject *rdnt;
1167     PyObject *attr = NULL;   /* tuple to hold an attribute */
1168     int entry_count = X509_NAME_entry_count(xname);
1169     X509_NAME_ENTRY *entry;
1170     ASN1_OBJECT *name;
1171     ASN1_STRING *value;
1172     int index_counter;
1173     int rdn_level = -1;
1174     int retcode;
1175 
1176     dn = PyList_New(0);
1177     if (dn == NULL)
1178         return NULL;
1179     /* now create another tuple to hold the top-level RDN */
1180     rdn = PyList_New(0);
1181     if (rdn == NULL)
1182         goto fail0;
1183 
1184     for (index_counter = 0;
1185          index_counter < entry_count;
1186          index_counter++)
1187     {
1188         entry = X509_NAME_get_entry(xname, index_counter);
1189 
1190         /* check to see if we've gotten to a new RDN */
1191         if (rdn_level >= 0) {
1192             if (rdn_level != X509_NAME_ENTRY_set(entry)) {
1193                 /* yes, new RDN */
1194                 /* add old RDN to DN */
1195                 rdnt = PyList_AsTuple(rdn);
1196                 Py_DECREF(rdn);
1197                 if (rdnt == NULL)
1198                     goto fail0;
1199                 retcode = PyList_Append(dn, rdnt);
1200                 Py_DECREF(rdnt);
1201                 if (retcode < 0)
1202                     goto fail0;
1203                 /* create new RDN */
1204                 rdn = PyList_New(0);
1205                 if (rdn == NULL)
1206                     goto fail0;
1207             }
1208         }
1209         rdn_level = X509_NAME_ENTRY_set(entry);
1210 
1211         /* now add this attribute to the current RDN */
1212         name = X509_NAME_ENTRY_get_object(entry);
1213         value = X509_NAME_ENTRY_get_data(entry);
1214         attr = _create_tuple_for_attribute(name, value);
1215         /*
1216         fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1217             entry->set,
1218             PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1219             PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1220         */
1221         if (attr == NULL)
1222             goto fail1;
1223         retcode = PyList_Append(rdn, attr);
1224         Py_DECREF(attr);
1225         if (retcode < 0)
1226             goto fail1;
1227     }
1228     /* now, there's typically a dangling RDN */
1229     if (rdn != NULL) {
1230         if (PyList_GET_SIZE(rdn) > 0) {
1231             rdnt = PyList_AsTuple(rdn);
1232             Py_DECREF(rdn);
1233             if (rdnt == NULL)
1234                 goto fail0;
1235             retcode = PyList_Append(dn, rdnt);
1236             Py_DECREF(rdnt);
1237             if (retcode < 0)
1238                 goto fail0;
1239         }
1240         else {
1241             Py_DECREF(rdn);
1242         }
1243     }
1244 
1245     /* convert list to tuple */
1246     rdnt = PyList_AsTuple(dn);
1247     Py_DECREF(dn);
1248     if (rdnt == NULL)
1249         return NULL;
1250     return rdnt;
1251 
1252   fail1:
1253     Py_XDECREF(rdn);
1254 
1255   fail0:
1256     Py_XDECREF(dn);
1257     return NULL;
1258 }
1259 
1260 static PyObject *
_get_peer_alt_names(X509 * certificate)1261 _get_peer_alt_names (X509 *certificate) {
1262 
1263     /* this code follows the procedure outlined in
1264        OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1265        function to extract the STACK_OF(GENERAL_NAME),
1266        then iterates through the stack to add the
1267        names. */
1268 
1269     int j;
1270     PyObject *peer_alt_names = Py_None;
1271     PyObject *v = NULL, *t;
1272     GENERAL_NAMES *names = NULL;
1273     GENERAL_NAME *name;
1274     BIO *biobuf = NULL;
1275     char buf[2048];
1276     char *vptr;
1277     int len;
1278 
1279     if (certificate == NULL)
1280         return peer_alt_names;
1281 
1282     /* get a memory buffer */
1283     biobuf = BIO_new(BIO_s_mem());
1284     if (biobuf == NULL) {
1285         PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1286         return NULL;
1287     }
1288 
1289     names = (GENERAL_NAMES *)X509_get_ext_d2i(
1290         certificate, NID_subject_alt_name, NULL, NULL);
1291     if (names != NULL) {
1292         if (peer_alt_names == Py_None) {
1293             peer_alt_names = PyList_New(0);
1294             if (peer_alt_names == NULL)
1295                 goto fail;
1296         }
1297 
1298         for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
1299             /* get a rendering of each name in the set of names */
1300             int gntype;
1301             ASN1_STRING *as = NULL;
1302 
1303             name = sk_GENERAL_NAME_value(names, j);
1304             gntype = name->type;
1305             switch (gntype) {
1306             case GEN_DIRNAME:
1307                 /* we special-case DirName as a tuple of
1308                    tuples of attributes */
1309 
1310                 t = PyTuple_New(2);
1311                 if (t == NULL) {
1312                     goto fail;
1313                 }
1314 
1315                 v = PyUnicode_FromString("DirName");
1316                 if (v == NULL) {
1317                     Py_DECREF(t);
1318                     goto fail;
1319                 }
1320                 PyTuple_SET_ITEM(t, 0, v);
1321 
1322                 v = _create_tuple_for_X509_NAME (name->d.dirn);
1323                 if (v == NULL) {
1324                     Py_DECREF(t);
1325                     goto fail;
1326                 }
1327                 PyTuple_SET_ITEM(t, 1, v);
1328                 break;
1329 
1330             case GEN_EMAIL:
1331             case GEN_DNS:
1332             case GEN_URI:
1333                 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1334                    correctly, CVE-2013-4238 */
1335                 t = PyTuple_New(2);
1336                 if (t == NULL)
1337                     goto fail;
1338                 switch (gntype) {
1339                 case GEN_EMAIL:
1340                     v = PyUnicode_FromString("email");
1341                     as = name->d.rfc822Name;
1342                     break;
1343                 case GEN_DNS:
1344                     v = PyUnicode_FromString("DNS");
1345                     as = name->d.dNSName;
1346                     break;
1347                 case GEN_URI:
1348                     v = PyUnicode_FromString("URI");
1349                     as = name->d.uniformResourceIdentifier;
1350                     break;
1351                 }
1352                 if (v == NULL) {
1353                     Py_DECREF(t);
1354                     goto fail;
1355                 }
1356                 PyTuple_SET_ITEM(t, 0, v);
1357                 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_get0_data(as),
1358                                                 ASN1_STRING_length(as));
1359                 if (v == NULL) {
1360                     Py_DECREF(t);
1361                     goto fail;
1362                 }
1363                 PyTuple_SET_ITEM(t, 1, v);
1364                 break;
1365 
1366             case GEN_RID:
1367                 t = PyTuple_New(2);
1368                 if (t == NULL)
1369                     goto fail;
1370 
1371                 v = PyUnicode_FromString("Registered ID");
1372                 if (v == NULL) {
1373                     Py_DECREF(t);
1374                     goto fail;
1375                 }
1376                 PyTuple_SET_ITEM(t, 0, v);
1377 
1378                 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1379                 if (len < 0) {
1380                     Py_DECREF(t);
1381                     _setSSLError(NULL, 0, __FILE__, __LINE__);
1382                     goto fail;
1383                 } else if (len >= (int)sizeof(buf)) {
1384                     v = PyUnicode_FromString("<INVALID>");
1385                 } else {
1386                     v = PyUnicode_FromStringAndSize(buf, len);
1387                 }
1388                 if (v == NULL) {
1389                     Py_DECREF(t);
1390                     goto fail;
1391                 }
1392                 PyTuple_SET_ITEM(t, 1, v);
1393                 break;
1394 
1395             case GEN_IPADD:
1396                 /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1397                  * the trailing newline. Remove it in all versions
1398                  */
1399                 t = PyTuple_New(2);
1400                 if (t == NULL)
1401                     goto fail;
1402 
1403                 v = PyUnicode_FromString("IP Address");
1404                 if (v == NULL) {
1405                     Py_DECREF(t);
1406                     goto fail;
1407                 }
1408                 PyTuple_SET_ITEM(t, 0, v);
1409 
1410                 if (name->d.ip->length == 4) {
1411                     unsigned char *p = name->d.ip->data;
1412                     v = PyUnicode_FromFormat(
1413                         "%d.%d.%d.%d",
1414                         p[0], p[1], p[2], p[3]
1415                     );
1416                 } else if (name->d.ip->length == 16) {
1417                     /* PyUnicode_FromFormat() does not support %X */
1418                     unsigned char *p = name->d.ip->data;
1419                     len = sprintf(
1420                         buf,
1421                         "%X:%X:%X:%X:%X:%X:%X:%X",
1422                         p[0] << 8 | p[1],
1423                         p[2] << 8 | p[3],
1424                         p[4] << 8 | p[5],
1425                         p[6] << 8 | p[7],
1426                         p[8] << 8 | p[9],
1427                         p[10] << 8 | p[11],
1428                         p[12] << 8 | p[13],
1429                         p[14] << 8 | p[15]
1430                     );
1431                     v = PyUnicode_FromStringAndSize(buf, len);
1432                 } else {
1433                     v = PyUnicode_FromString("<invalid>");
1434                 }
1435 
1436                 if (v == NULL) {
1437                     Py_DECREF(t);
1438                     goto fail;
1439                 }
1440                 PyTuple_SET_ITEM(t, 1, v);
1441                 break;
1442 
1443             default:
1444                 /* for everything else, we use the OpenSSL print form */
1445                 switch (gntype) {
1446                     /* check for new general name type */
1447                     case GEN_OTHERNAME:
1448                     case GEN_X400:
1449                     case GEN_EDIPARTY:
1450                     case GEN_RID:
1451                         break;
1452                     default:
1453                         if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1454                                              "Unknown general name type %d",
1455                                              gntype) == -1) {
1456                             goto fail;
1457                         }
1458                         break;
1459                 }
1460                 (void) BIO_reset(biobuf);
1461                 GENERAL_NAME_print(biobuf, name);
1462                 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1463                 if (len < 0) {
1464                     _setSSLError(NULL, 0, __FILE__, __LINE__);
1465                     goto fail;
1466                 }
1467                 vptr = strchr(buf, ':');
1468                 if (vptr == NULL) {
1469                     PyErr_Format(PyExc_ValueError,
1470                                  "Invalid value %.200s",
1471                                  buf);
1472                     goto fail;
1473                 }
1474                 t = PyTuple_New(2);
1475                 if (t == NULL)
1476                     goto fail;
1477                 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1478                 if (v == NULL) {
1479                     Py_DECREF(t);
1480                     goto fail;
1481                 }
1482                 PyTuple_SET_ITEM(t, 0, v);
1483                 v = PyUnicode_FromStringAndSize((vptr + 1),
1484                                                 (len - (vptr - buf + 1)));
1485                 if (v == NULL) {
1486                     Py_DECREF(t);
1487                     goto fail;
1488                 }
1489                 PyTuple_SET_ITEM(t, 1, v);
1490                 break;
1491             }
1492 
1493             /* and add that rendering to the list */
1494 
1495             if (PyList_Append(peer_alt_names, t) < 0) {
1496                 Py_DECREF(t);
1497                 goto fail;
1498             }
1499             Py_DECREF(t);
1500         }
1501         sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
1502     }
1503     BIO_free(biobuf);
1504     if (peer_alt_names != Py_None) {
1505         v = PyList_AsTuple(peer_alt_names);
1506         Py_DECREF(peer_alt_names);
1507         return v;
1508     } else {
1509         return peer_alt_names;
1510     }
1511 
1512 
1513   fail:
1514     if (biobuf != NULL)
1515         BIO_free(biobuf);
1516 
1517     if (peer_alt_names != Py_None) {
1518         Py_XDECREF(peer_alt_names);
1519     }
1520 
1521     return NULL;
1522 }
1523 
1524 static PyObject *
_get_aia_uri(X509 * certificate,int nid)1525 _get_aia_uri(X509 *certificate, int nid) {
1526     PyObject *lst = NULL, *ostr = NULL;
1527     int i, result;
1528     AUTHORITY_INFO_ACCESS *info;
1529 
1530     info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
1531     if (info == NULL)
1532         return Py_None;
1533     if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1534         AUTHORITY_INFO_ACCESS_free(info);
1535         return Py_None;
1536     }
1537 
1538     if ((lst = PyList_New(0)) == NULL) {
1539         goto fail;
1540     }
1541 
1542     for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1543         ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1544         ASN1_IA5STRING *uri;
1545 
1546         if ((OBJ_obj2nid(ad->method) != nid) ||
1547                 (ad->location->type != GEN_URI)) {
1548             continue;
1549         }
1550         uri = ad->location->d.uniformResourceIdentifier;
1551         ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1552                                            uri->length);
1553         if (ostr == NULL) {
1554             goto fail;
1555         }
1556         result = PyList_Append(lst, ostr);
1557         Py_DECREF(ostr);
1558         if (result < 0) {
1559             goto fail;
1560         }
1561     }
1562     AUTHORITY_INFO_ACCESS_free(info);
1563 
1564     /* convert to tuple or None */
1565     if (PyList_Size(lst) == 0) {
1566         Py_DECREF(lst);
1567         return Py_None;
1568     } else {
1569         PyObject *tup;
1570         tup = PyList_AsTuple(lst);
1571         Py_DECREF(lst);
1572         return tup;
1573     }
1574 
1575   fail:
1576     AUTHORITY_INFO_ACCESS_free(info);
1577     Py_XDECREF(lst);
1578     return NULL;
1579 }
1580 
1581 static PyObject *
_get_crl_dp(X509 * certificate)1582 _get_crl_dp(X509 *certificate) {
1583     STACK_OF(DIST_POINT) *dps;
1584     int i, j;
1585     PyObject *lst, *res = NULL;
1586 
1587     dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
1588 
1589     if (dps == NULL)
1590         return Py_None;
1591 
1592     lst = PyList_New(0);
1593     if (lst == NULL)
1594         goto done;
1595 
1596     for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1597         DIST_POINT *dp;
1598         STACK_OF(GENERAL_NAME) *gns;
1599 
1600         dp = sk_DIST_POINT_value(dps, i);
1601         if (dp->distpoint == NULL) {
1602             /* Ignore empty DP value, CVE-2019-5010 */
1603             continue;
1604         }
1605         gns = dp->distpoint->name.fullname;
1606 
1607         for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1608             GENERAL_NAME *gn;
1609             ASN1_IA5STRING *uri;
1610             PyObject *ouri;
1611             int err;
1612 
1613             gn = sk_GENERAL_NAME_value(gns, j);
1614             if (gn->type != GEN_URI) {
1615                 continue;
1616             }
1617             uri = gn->d.uniformResourceIdentifier;
1618             ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1619                                                uri->length);
1620             if (ouri == NULL)
1621                 goto done;
1622 
1623             err = PyList_Append(lst, ouri);
1624             Py_DECREF(ouri);
1625             if (err < 0)
1626                 goto done;
1627         }
1628     }
1629 
1630     /* Convert to tuple. */
1631     res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1632 
1633   done:
1634     Py_XDECREF(lst);
1635     CRL_DIST_POINTS_free(dps);
1636     return res;
1637 }
1638 
1639 static PyObject *
_decode_certificate(X509 * certificate)1640 _decode_certificate(X509 *certificate) {
1641 
1642     PyObject *retval = NULL;
1643     BIO *biobuf = NULL;
1644     PyObject *peer;
1645     PyObject *peer_alt_names = NULL;
1646     PyObject *issuer;
1647     PyObject *version;
1648     PyObject *sn_obj;
1649     PyObject *obj;
1650     ASN1_INTEGER *serialNumber;
1651     char buf[2048];
1652     int len, result;
1653     const ASN1_TIME *notBefore, *notAfter;
1654     PyObject *pnotBefore, *pnotAfter;
1655 
1656     retval = PyDict_New();
1657     if (retval == NULL)
1658         return NULL;
1659 
1660     peer = _create_tuple_for_X509_NAME(
1661         X509_get_subject_name(certificate));
1662     if (peer == NULL)
1663         goto fail0;
1664     if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1665         Py_DECREF(peer);
1666         goto fail0;
1667     }
1668     Py_DECREF(peer);
1669 
1670     issuer = _create_tuple_for_X509_NAME(
1671         X509_get_issuer_name(certificate));
1672     if (issuer == NULL)
1673         goto fail0;
1674     if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
1675         Py_DECREF(issuer);
1676         goto fail0;
1677     }
1678     Py_DECREF(issuer);
1679 
1680     version = PyLong_FromLong(X509_get_version(certificate) + 1);
1681     if (version == NULL)
1682         goto fail0;
1683     if (PyDict_SetItemString(retval, "version", version) < 0) {
1684         Py_DECREF(version);
1685         goto fail0;
1686     }
1687     Py_DECREF(version);
1688 
1689     /* get a memory buffer */
1690     biobuf = BIO_new(BIO_s_mem());
1691     if (biobuf == NULL) {
1692         PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1693         goto fail0;
1694     }
1695 
1696     (void) BIO_reset(biobuf);
1697     serialNumber = X509_get_serialNumber(certificate);
1698     /* should not exceed 20 octets, 160 bits, so buf is big enough */
1699     i2a_ASN1_INTEGER(biobuf, serialNumber);
1700     len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1701     if (len < 0) {
1702         _setSSLError(NULL, 0, __FILE__, __LINE__);
1703         goto fail1;
1704     }
1705     sn_obj = PyUnicode_FromStringAndSize(buf, len);
1706     if (sn_obj == NULL)
1707         goto fail1;
1708     if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1709         Py_DECREF(sn_obj);
1710         goto fail1;
1711     }
1712     Py_DECREF(sn_obj);
1713 
1714     (void) BIO_reset(biobuf);
1715     notBefore = X509_get0_notBefore(certificate);
1716     ASN1_TIME_print(biobuf, notBefore);
1717     len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1718     if (len < 0) {
1719         _setSSLError(NULL, 0, __FILE__, __LINE__);
1720         goto fail1;
1721     }
1722     pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1723     if (pnotBefore == NULL)
1724         goto fail1;
1725     if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1726         Py_DECREF(pnotBefore);
1727         goto fail1;
1728     }
1729     Py_DECREF(pnotBefore);
1730 
1731     (void) BIO_reset(biobuf);
1732     notAfter = X509_get0_notAfter(certificate);
1733     ASN1_TIME_print(biobuf, notAfter);
1734     len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1735     if (len < 0) {
1736         _setSSLError(NULL, 0, __FILE__, __LINE__);
1737         goto fail1;
1738     }
1739     pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1740     if (pnotAfter == NULL)
1741         goto fail1;
1742     if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1743         Py_DECREF(pnotAfter);
1744         goto fail1;
1745     }
1746     Py_DECREF(pnotAfter);
1747 
1748     /* Now look for subjectAltName */
1749 
1750     peer_alt_names = _get_peer_alt_names(certificate);
1751     if (peer_alt_names == NULL)
1752         goto fail1;
1753     else if (peer_alt_names != Py_None) {
1754         if (PyDict_SetItemString(retval, "subjectAltName",
1755                                  peer_alt_names) < 0) {
1756             Py_DECREF(peer_alt_names);
1757             goto fail1;
1758         }
1759         Py_DECREF(peer_alt_names);
1760     }
1761 
1762     /* Authority Information Access: OCSP URIs */
1763     obj = _get_aia_uri(certificate, NID_ad_OCSP);
1764     if (obj == NULL) {
1765         goto fail1;
1766     } else if (obj != Py_None) {
1767         result = PyDict_SetItemString(retval, "OCSP", obj);
1768         Py_DECREF(obj);
1769         if (result < 0) {
1770             goto fail1;
1771         }
1772     }
1773 
1774     obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1775     if (obj == NULL) {
1776         goto fail1;
1777     } else if (obj != Py_None) {
1778         result = PyDict_SetItemString(retval, "caIssuers", obj);
1779         Py_DECREF(obj);
1780         if (result < 0) {
1781             goto fail1;
1782         }
1783     }
1784 
1785     /* CDP (CRL distribution points) */
1786     obj = _get_crl_dp(certificate);
1787     if (obj == NULL) {
1788         goto fail1;
1789     } else if (obj != Py_None) {
1790         result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1791         Py_DECREF(obj);
1792         if (result < 0) {
1793             goto fail1;
1794         }
1795     }
1796 
1797     BIO_free(biobuf);
1798     return retval;
1799 
1800   fail1:
1801     if (biobuf != NULL)
1802         BIO_free(biobuf);
1803   fail0:
1804     Py_XDECREF(retval);
1805     return NULL;
1806 }
1807 
1808 static PyObject *
_certificate_to_der(X509 * certificate)1809 _certificate_to_der(X509 *certificate)
1810 {
1811     unsigned char *bytes_buf = NULL;
1812     int len;
1813     PyObject *retval;
1814 
1815     bytes_buf = NULL;
1816     len = i2d_X509(certificate, &bytes_buf);
1817     if (len < 0) {
1818         _setSSLError(NULL, 0, __FILE__, __LINE__);
1819         return NULL;
1820     }
1821     /* this is actually an immutable bytes sequence */
1822     retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1823     OPENSSL_free(bytes_buf);
1824     return retval;
1825 }
1826 
1827 /*[clinic input]
1828 _ssl._test_decode_cert
1829     path: object(converter="PyUnicode_FSConverter")
1830     /
1831 
1832 [clinic start generated code]*/
1833 
1834 static PyObject *
_ssl__test_decode_cert_impl(PyObject * module,PyObject * path)1835 _ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1836 /*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
1837 {
1838     PyObject *retval = NULL;
1839     X509 *x=NULL;
1840     BIO *cert;
1841 
1842     if ((cert=BIO_new(BIO_s_file())) == NULL) {
1843         PyErr_SetString(PySSLErrorObject,
1844                         "Can't malloc memory to read file");
1845         goto fail0;
1846     }
1847 
1848     if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
1849         PyErr_SetString(PySSLErrorObject,
1850                         "Can't open file");
1851         goto fail0;
1852     }
1853 
1854     x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
1855     if (x == NULL) {
1856         PyErr_SetString(PySSLErrorObject,
1857                         "Error decoding PEM-encoded file");
1858         goto fail0;
1859     }
1860 
1861     retval = _decode_certificate(x);
1862     X509_free(x);
1863 
1864   fail0:
1865     Py_DECREF(path);
1866     if (cert != NULL) BIO_free(cert);
1867     return retval;
1868 }
1869 
1870 
1871 /*[clinic input]
1872 _ssl._SSLSocket.getpeercert
1873     der as binary_mode: bool = False
1874     /
1875 
1876 Returns the certificate for the peer.
1877 
1878 If no certificate was provided, returns None.  If a certificate was
1879 provided, but not validated, returns an empty dictionary.  Otherwise
1880 returns a dict containing information about the peer certificate.
1881 
1882 If the optional argument is True, returns a DER-encoded copy of the
1883 peer certificate, or None if no certificate was provided.  This will
1884 return the certificate even if it wasn't validated.
1885 [clinic start generated code]*/
1886 
1887 static PyObject *
_ssl__SSLSocket_getpeercert_impl(PySSLSocket * self,int binary_mode)1888 _ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1889 /*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
1890 {
1891     int verification;
1892     X509 *peer_cert;
1893     PyObject *result;
1894 
1895     if (!SSL_is_init_finished(self->ssl)) {
1896         PyErr_SetString(PyExc_ValueError,
1897                         "handshake not done yet");
1898         return NULL;
1899     }
1900     peer_cert = SSL_get_peer_certificate(self->ssl);
1901     if (peer_cert == NULL)
1902         Py_RETURN_NONE;
1903 
1904     if (binary_mode) {
1905         /* return cert in DER-encoded format */
1906         result = _certificate_to_der(peer_cert);
1907     } else {
1908         verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
1909         if ((verification & SSL_VERIFY_PEER) == 0)
1910             result = PyDict_New();
1911         else
1912             result = _decode_certificate(peer_cert);
1913     }
1914     X509_free(peer_cert);
1915     return result;
1916 }
1917 
1918 static PyObject *
cipher_to_tuple(const SSL_CIPHER * cipher)1919 cipher_to_tuple(const SSL_CIPHER *cipher)
1920 {
1921     const char *cipher_name, *cipher_protocol;
1922     PyObject *v, *retval = PyTuple_New(3);
1923     if (retval == NULL)
1924         return NULL;
1925 
1926     cipher_name = SSL_CIPHER_get_name(cipher);
1927     if (cipher_name == NULL) {
1928         Py_INCREF(Py_None);
1929         PyTuple_SET_ITEM(retval, 0, Py_None);
1930     } else {
1931         v = PyUnicode_FromString(cipher_name);
1932         if (v == NULL)
1933             goto fail;
1934         PyTuple_SET_ITEM(retval, 0, v);
1935     }
1936 
1937     cipher_protocol = SSL_CIPHER_get_version(cipher);
1938     if (cipher_protocol == NULL) {
1939         Py_INCREF(Py_None);
1940         PyTuple_SET_ITEM(retval, 1, Py_None);
1941     } else {
1942         v = PyUnicode_FromString(cipher_protocol);
1943         if (v == NULL)
1944             goto fail;
1945         PyTuple_SET_ITEM(retval, 1, v);
1946     }
1947 
1948     v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
1949     if (v == NULL)
1950         goto fail;
1951     PyTuple_SET_ITEM(retval, 2, v);
1952 
1953     return retval;
1954 
1955   fail:
1956     Py_DECREF(retval);
1957     return NULL;
1958 }
1959 
1960 #if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1961 static PyObject *
cipher_to_dict(const SSL_CIPHER * cipher)1962 cipher_to_dict(const SSL_CIPHER *cipher)
1963 {
1964     const char *cipher_name, *cipher_protocol;
1965 
1966     unsigned long cipher_id;
1967     int alg_bits, strength_bits, len;
1968     char buf[512] = {0};
1969 #if OPENSSL_VERSION_1_1
1970     int aead, nid;
1971     const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1972 #endif
1973 
1974     /* can be NULL */
1975     cipher_name = SSL_CIPHER_get_name(cipher);
1976     cipher_protocol = SSL_CIPHER_get_version(cipher);
1977     cipher_id = SSL_CIPHER_get_id(cipher);
1978     SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
1979     /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1980     len = (int)strlen(buf);
1981     if (len > 1 && buf[len-1] == '\n')
1982         buf[len-1] = '\0';
1983     strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1984 
1985 #if OPENSSL_VERSION_1_1
1986     aead = SSL_CIPHER_is_aead(cipher);
1987     nid = SSL_CIPHER_get_cipher_nid(cipher);
1988     skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1989     nid = SSL_CIPHER_get_digest_nid(cipher);
1990     digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1991     nid = SSL_CIPHER_get_kx_nid(cipher);
1992     kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1993     nid = SSL_CIPHER_get_auth_nid(cipher);
1994     auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1995 #endif
1996 
1997     return Py_BuildValue(
1998         "{sksssssssisi"
1999 #if OPENSSL_VERSION_1_1
2000         "sOssssssss"
2001 #endif
2002         "}",
2003         "id", cipher_id,
2004         "name", cipher_name,
2005         "protocol", cipher_protocol,
2006         "description", buf,
2007         "strength_bits", strength_bits,
2008         "alg_bits", alg_bits
2009 #if OPENSSL_VERSION_1_1
2010         ,"aead", aead ? Py_True : Py_False,
2011         "symmetric", skcipher,
2012         "digest", digest,
2013         "kea", kx,
2014         "auth", auth
2015 #endif
2016        );
2017 }
2018 #endif
2019 
2020 /*[clinic input]
2021 _ssl._SSLSocket.shared_ciphers
2022 [clinic start generated code]*/
2023 
2024 static PyObject *
_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket * self)2025 _ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
2026 /*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
2027 {
2028     STACK_OF(SSL_CIPHER) *ciphers;
2029     int i;
2030     PyObject *res;
2031 
2032     ciphers = SSL_get_ciphers(self->ssl);
2033     if (!ciphers)
2034         Py_RETURN_NONE;
2035     res = PyList_New(sk_SSL_CIPHER_num(ciphers));
2036     if (!res)
2037         return NULL;
2038     for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
2039         PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
2040         if (!tup) {
2041             Py_DECREF(res);
2042             return NULL;
2043         }
2044         PyList_SET_ITEM(res, i, tup);
2045     }
2046     return res;
2047 }
2048 
2049 /*[clinic input]
2050 _ssl._SSLSocket.cipher
2051 [clinic start generated code]*/
2052 
2053 static PyObject *
_ssl__SSLSocket_cipher_impl(PySSLSocket * self)2054 _ssl__SSLSocket_cipher_impl(PySSLSocket *self)
2055 /*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
2056 {
2057     const SSL_CIPHER *current;
2058 
2059     if (self->ssl == NULL)
2060         Py_RETURN_NONE;
2061     current = SSL_get_current_cipher(self->ssl);
2062     if (current == NULL)
2063         Py_RETURN_NONE;
2064     return cipher_to_tuple(current);
2065 }
2066 
2067 /*[clinic input]
2068 _ssl._SSLSocket.version
2069 [clinic start generated code]*/
2070 
2071 static PyObject *
_ssl__SSLSocket_version_impl(PySSLSocket * self)2072 _ssl__SSLSocket_version_impl(PySSLSocket *self)
2073 /*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
2074 {
2075     const char *version;
2076 
2077     if (self->ssl == NULL)
2078         Py_RETURN_NONE;
2079     if (!SSL_is_init_finished(self->ssl)) {
2080         /* handshake not finished */
2081         Py_RETURN_NONE;
2082     }
2083     version = SSL_get_version(self->ssl);
2084     if (!strcmp(version, "unknown"))
2085         Py_RETURN_NONE;
2086     return PyUnicode_FromString(version);
2087 }
2088 
2089 #if HAVE_NPN
2090 /*[clinic input]
2091 _ssl._SSLSocket.selected_npn_protocol
2092 [clinic start generated code]*/
2093 
2094 static PyObject *
_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket * self)2095 _ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
2096 /*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
2097 {
2098     const unsigned char *out;
2099     unsigned int outlen;
2100 
2101     SSL_get0_next_proto_negotiated(self->ssl,
2102                                    &out, &outlen);
2103 
2104     if (out == NULL)
2105         Py_RETURN_NONE;
2106     return PyUnicode_FromStringAndSize((char *)out, outlen);
2107 }
2108 #endif
2109 
2110 #if HAVE_ALPN
2111 /*[clinic input]
2112 _ssl._SSLSocket.selected_alpn_protocol
2113 [clinic start generated code]*/
2114 
2115 static PyObject *
_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket * self)2116 _ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2117 /*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2118 {
2119     const unsigned char *out;
2120     unsigned int outlen;
2121 
2122     SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2123 
2124     if (out == NULL)
2125         Py_RETURN_NONE;
2126     return PyUnicode_FromStringAndSize((char *)out, outlen);
2127 }
2128 #endif
2129 
2130 /*[clinic input]
2131 _ssl._SSLSocket.compression
2132 [clinic start generated code]*/
2133 
2134 static PyObject *
_ssl__SSLSocket_compression_impl(PySSLSocket * self)2135 _ssl__SSLSocket_compression_impl(PySSLSocket *self)
2136 /*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2137 {
2138 #ifdef OPENSSL_NO_COMP
2139     Py_RETURN_NONE;
2140 #else
2141     const COMP_METHOD *comp_method;
2142     const char *short_name;
2143 
2144     if (self->ssl == NULL)
2145         Py_RETURN_NONE;
2146     comp_method = SSL_get_current_compression(self->ssl);
2147     if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
2148         Py_RETURN_NONE;
2149     short_name = OBJ_nid2sn(COMP_get_type(comp_method));
2150     if (short_name == NULL)
2151         Py_RETURN_NONE;
2152     return PyUnicode_DecodeFSDefault(short_name);
2153 #endif
2154 }
2155 
PySSL_get_context(PySSLSocket * self,void * closure)2156 static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2157     Py_INCREF(self->ctx);
2158     return self->ctx;
2159 }
2160 
PySSL_set_context(PySSLSocket * self,PyObject * value,void * closure)2161 static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2162                                    void *closure) {
2163 
2164     if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
2165 #if !HAVE_SNI
2166         PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2167                         "context is not supported by your OpenSSL library");
2168         return -1;
2169 #else
2170         Py_INCREF(value);
2171         Py_SETREF(self->ctx, (PySSLContext *)value);
2172         SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
2173 #endif
2174     } else {
2175         PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
2176         return -1;
2177     }
2178 
2179     return 0;
2180 }
2181 
2182 PyDoc_STRVAR(PySSL_set_context_doc,
2183 "_setter_context(ctx)\n\
2184 \
2185 This changes the context associated with the SSLSocket. This is typically\n\
2186 used from within a callback function set by the sni_callback\n\
2187 on the SSLContext to change the certificate information associated with the\n\
2188 SSLSocket before the cryptographic exchange handshake messages\n");
2189 
2190 
2191 static PyObject *
PySSL_get_server_side(PySSLSocket * self,void * c)2192 PySSL_get_server_side(PySSLSocket *self, void *c)
2193 {
2194     return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2195 }
2196 
2197 PyDoc_STRVAR(PySSL_get_server_side_doc,
2198 "Whether this is a server-side socket.");
2199 
2200 static PyObject *
PySSL_get_server_hostname(PySSLSocket * self,void * c)2201 PySSL_get_server_hostname(PySSLSocket *self, void *c)
2202 {
2203     if (self->server_hostname == NULL)
2204         Py_RETURN_NONE;
2205     Py_INCREF(self->server_hostname);
2206     return self->server_hostname;
2207 }
2208 
2209 PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2210 "The currently set server hostname (for SNI).");
2211 
2212 static PyObject *
PySSL_get_owner(PySSLSocket * self,void * c)2213 PySSL_get_owner(PySSLSocket *self, void *c)
2214 {
2215     PyObject *owner;
2216 
2217     if (self->owner == NULL)
2218         Py_RETURN_NONE;
2219 
2220     owner = PyWeakref_GetObject(self->owner);
2221     Py_INCREF(owner);
2222     return owner;
2223 }
2224 
2225 static int
PySSL_set_owner(PySSLSocket * self,PyObject * value,void * c)2226 PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2227 {
2228     Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
2229     if (self->owner == NULL)
2230         return -1;
2231     return 0;
2232 }
2233 
2234 PyDoc_STRVAR(PySSL_get_owner_doc,
2235 "The Python-level owner of this object.\
2236 Passed as \"self\" in servername callback.");
2237 
2238 
PySSL_dealloc(PySSLSocket * self)2239 static void PySSL_dealloc(PySSLSocket *self)
2240 {
2241     if (self->ssl)
2242         SSL_free(self->ssl);
2243     Py_XDECREF(self->Socket);
2244     Py_XDECREF(self->ctx);
2245     Py_XDECREF(self->server_hostname);
2246     Py_XDECREF(self->owner);
2247     PyObject_Del(self);
2248 }
2249 
2250 /* If the socket has a timeout, do a select()/poll() on the socket.
2251    The argument writing indicates the direction.
2252    Returns one of the possibilities in the timeout_state enum (above).
2253  */
2254 
2255 static int
PySSL_select(PySocketSockObject * s,int writing,_PyTime_t timeout)2256 PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
2257 {
2258     int rc;
2259 #ifdef HAVE_POLL
2260     struct pollfd pollfd;
2261     _PyTime_t ms;
2262 #else
2263     int nfds;
2264     fd_set fds;
2265     struct timeval tv;
2266 #endif
2267 
2268     /* Nothing to do unless we're in timeout mode (not non-blocking) */
2269     if ((s == NULL) || (timeout == 0))
2270         return SOCKET_IS_NONBLOCKING;
2271     else if (timeout < 0) {
2272         if (s->sock_timeout > 0)
2273             return SOCKET_HAS_TIMED_OUT;
2274         else
2275             return SOCKET_IS_BLOCKING;
2276     }
2277 
2278     /* Guard against closed socket */
2279     if (s->sock_fd == INVALID_SOCKET)
2280         return SOCKET_HAS_BEEN_CLOSED;
2281 
2282     /* Prefer poll, if available, since you can poll() any fd
2283      * which can't be done with select(). */
2284 #ifdef HAVE_POLL
2285     pollfd.fd = s->sock_fd;
2286     pollfd.events = writing ? POLLOUT : POLLIN;
2287 
2288     /* timeout is in seconds, poll() uses milliseconds */
2289     ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
2290     assert(ms <= INT_MAX);
2291 
2292     PySSL_BEGIN_ALLOW_THREADS
2293     rc = poll(&pollfd, 1, (int)ms);
2294     PySSL_END_ALLOW_THREADS
2295 #else
2296     /* Guard against socket too large for select*/
2297     if (!_PyIsSelectable_fd(s->sock_fd))
2298         return SOCKET_TOO_LARGE_FOR_SELECT;
2299 
2300     _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
2301 
2302     FD_ZERO(&fds);
2303     FD_SET(s->sock_fd, &fds);
2304 
2305     /* Wait until the socket becomes ready */
2306     PySSL_BEGIN_ALLOW_THREADS
2307     nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
2308     if (writing)
2309         rc = select(nfds, NULL, &fds, NULL, &tv);
2310     else
2311         rc = select(nfds, &fds, NULL, NULL, &tv);
2312     PySSL_END_ALLOW_THREADS
2313 #endif
2314 
2315     /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2316        (when we are able to write or when there's something to read) */
2317     return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
2318 }
2319 
2320 /*[clinic input]
2321 _ssl._SSLSocket.write
2322     b: Py_buffer
2323     /
2324 
2325 Writes the bytes-like object b into the SSL object.
2326 
2327 Returns the number of bytes written.
2328 [clinic start generated code]*/
2329 
2330 static PyObject *
_ssl__SSLSocket_write_impl(PySSLSocket * self,Py_buffer * b)2331 _ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2332 /*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
2333 {
2334     int len;
2335     int sockstate;
2336     _PySSLError err;
2337     int nonblocking;
2338     PySocketSockObject *sock = GET_SOCKET(self);
2339     _PyTime_t timeout, deadline = 0;
2340     int has_timeout;
2341 
2342     if (sock != NULL) {
2343         if (((PyObject*)sock) == Py_None) {
2344             _setSSLError("Underlying socket connection gone",
2345                          PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2346             return NULL;
2347         }
2348         Py_INCREF(sock);
2349     }
2350 
2351     if (b->len > INT_MAX) {
2352         PyErr_Format(PyExc_OverflowError,
2353                      "string longer than %d bytes", INT_MAX);
2354         goto error;
2355     }
2356 
2357     if (sock != NULL) {
2358         /* just in case the blocking state of the socket has been changed */
2359         nonblocking = (sock->sock_timeout >= 0);
2360         BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2361         BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2362     }
2363 
2364     timeout = GET_SOCKET_TIMEOUT(sock);
2365     has_timeout = (timeout > 0);
2366     if (has_timeout)
2367         deadline = _PyTime_GetMonotonicClock() + timeout;
2368 
2369     sockstate = PySSL_select(sock, 1, timeout);
2370     if (sockstate == SOCKET_HAS_TIMED_OUT) {
2371         PyErr_SetString(PySocketModule.timeout_error,
2372                         "The write operation timed out");
2373         goto error;
2374     } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2375         PyErr_SetString(PySSLErrorObject,
2376                         "Underlying socket has been closed.");
2377         goto error;
2378     } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2379         PyErr_SetString(PySSLErrorObject,
2380                         "Underlying socket too large for select().");
2381         goto error;
2382     }
2383 
2384     do {
2385         PySSL_BEGIN_ALLOW_THREADS
2386         len = SSL_write(self->ssl, b->buf, (int)b->len);
2387         err = _PySSL_errno(len <= 0, self->ssl, len);
2388         PySSL_END_ALLOW_THREADS
2389         self->err = err;
2390 
2391         if (PyErr_CheckSignals())
2392             goto error;
2393 
2394         if (has_timeout)
2395             timeout = deadline - _PyTime_GetMonotonicClock();
2396 
2397         if (err.ssl == SSL_ERROR_WANT_READ) {
2398             sockstate = PySSL_select(sock, 0, timeout);
2399         } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
2400             sockstate = PySSL_select(sock, 1, timeout);
2401         } else {
2402             sockstate = SOCKET_OPERATION_OK;
2403         }
2404 
2405         if (sockstate == SOCKET_HAS_TIMED_OUT) {
2406             PyErr_SetString(PySocketModule.timeout_error,
2407                             "The write operation timed out");
2408             goto error;
2409         } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2410             PyErr_SetString(PySSLErrorObject,
2411                             "Underlying socket has been closed.");
2412             goto error;
2413         } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2414             break;
2415         }
2416     } while (err.ssl == SSL_ERROR_WANT_READ ||
2417              err.ssl == SSL_ERROR_WANT_WRITE);
2418 
2419     Py_XDECREF(sock);
2420     if (len > 0)
2421         return PyLong_FromLong(len);
2422     else
2423         return PySSL_SetError(self, len, __FILE__, __LINE__);
2424 
2425 error:
2426     Py_XDECREF(sock);
2427     return NULL;
2428 }
2429 
2430 /*[clinic input]
2431 _ssl._SSLSocket.pending
2432 
2433 Returns the number of already decrypted bytes available for read, pending on the connection.
2434 [clinic start generated code]*/
2435 
2436 static PyObject *
_ssl__SSLSocket_pending_impl(PySSLSocket * self)2437 _ssl__SSLSocket_pending_impl(PySSLSocket *self)
2438 /*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
2439 {
2440     int count = 0;
2441     _PySSLError err;
2442 
2443     PySSL_BEGIN_ALLOW_THREADS
2444     count = SSL_pending(self->ssl);
2445     err = _PySSL_errno(count < 0, self->ssl, count);
2446     PySSL_END_ALLOW_THREADS
2447     self->err = err;
2448 
2449     if (count < 0)
2450         return PySSL_SetError(self, count, __FILE__, __LINE__);
2451     else
2452         return PyLong_FromLong(count);
2453 }
2454 
2455 /*[clinic input]
2456 _ssl._SSLSocket.read
2457     size as len: int
2458     [
2459     buffer: Py_buffer(accept={rwbuffer})
2460     ]
2461     /
2462 
2463 Read up to size bytes from the SSL socket.
2464 [clinic start generated code]*/
2465 
2466 static PyObject *
_ssl__SSLSocket_read_impl(PySSLSocket * self,int len,int group_right_1,Py_buffer * buffer)2467 _ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2468                           Py_buffer *buffer)
2469 /*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
2470 {
2471     PyObject *dest = NULL;
2472     char *mem;
2473     int count;
2474     int sockstate;
2475     _PySSLError err;
2476     int nonblocking;
2477     PySocketSockObject *sock = GET_SOCKET(self);
2478     _PyTime_t timeout, deadline = 0;
2479     int has_timeout;
2480 
2481     if (!group_right_1 && len < 0) {
2482         PyErr_SetString(PyExc_ValueError, "size should not be negative");
2483         return NULL;
2484     }
2485 
2486     if (sock != NULL) {
2487         if (((PyObject*)sock) == Py_None) {
2488             _setSSLError("Underlying socket connection gone",
2489                          PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2490             return NULL;
2491         }
2492         Py_INCREF(sock);
2493     }
2494 
2495     if (!group_right_1) {
2496         dest = PyBytes_FromStringAndSize(NULL, len);
2497         if (dest == NULL)
2498             goto error;
2499         if (len == 0) {
2500             Py_XDECREF(sock);
2501             return dest;
2502         }
2503         mem = PyBytes_AS_STRING(dest);
2504     }
2505     else {
2506         mem = buffer->buf;
2507         if (len <= 0 || len > buffer->len) {
2508             len = (int) buffer->len;
2509             if (buffer->len != len) {
2510                 PyErr_SetString(PyExc_OverflowError,
2511                                 "maximum length can't fit in a C 'int'");
2512                 goto error;
2513             }
2514             if (len == 0) {
2515                 count = 0;
2516                 goto done;
2517             }
2518         }
2519     }
2520 
2521     if (sock != NULL) {
2522         /* just in case the blocking state of the socket has been changed */
2523         nonblocking = (sock->sock_timeout >= 0);
2524         BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2525         BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2526     }
2527 
2528     timeout = GET_SOCKET_TIMEOUT(sock);
2529     has_timeout = (timeout > 0);
2530     if (has_timeout)
2531         deadline = _PyTime_GetMonotonicClock() + timeout;
2532 
2533     do {
2534         PySSL_BEGIN_ALLOW_THREADS
2535         count = SSL_read(self->ssl, mem, len);
2536         err = _PySSL_errno(count <= 0, self->ssl, count);
2537         PySSL_END_ALLOW_THREADS
2538         self->err = err;
2539 
2540         if (PyErr_CheckSignals())
2541             goto error;
2542 
2543         if (has_timeout)
2544             timeout = deadline - _PyTime_GetMonotonicClock();
2545 
2546         if (err.ssl == SSL_ERROR_WANT_READ) {
2547             sockstate = PySSL_select(sock, 0, timeout);
2548         } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
2549             sockstate = PySSL_select(sock, 1, timeout);
2550         } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
2551                    SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
2552         {
2553             count = 0;
2554             goto done;
2555         }
2556         else
2557             sockstate = SOCKET_OPERATION_OK;
2558 
2559         if (sockstate == SOCKET_HAS_TIMED_OUT) {
2560             PyErr_SetString(PySocketModule.timeout_error,
2561                             "The read operation timed out");
2562             goto error;
2563         } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2564             break;
2565         }
2566     } while (err.ssl == SSL_ERROR_WANT_READ ||
2567              err.ssl == SSL_ERROR_WANT_WRITE);
2568 
2569     if (count <= 0) {
2570         PySSL_SetError(self, count, __FILE__, __LINE__);
2571         goto error;
2572     }
2573 
2574 done:
2575     Py_XDECREF(sock);
2576     if (!group_right_1) {
2577         _PyBytes_Resize(&dest, count);
2578         return dest;
2579     }
2580     else {
2581         return PyLong_FromLong(count);
2582     }
2583 
2584 error:
2585     Py_XDECREF(sock);
2586     if (!group_right_1)
2587         Py_XDECREF(dest);
2588     return NULL;
2589 }
2590 
2591 /*[clinic input]
2592 _ssl._SSLSocket.shutdown
2593 
2594 Does the SSL shutdown handshake with the remote end.
2595 [clinic start generated code]*/
2596 
2597 static PyObject *
_ssl__SSLSocket_shutdown_impl(PySSLSocket * self)2598 _ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2599 /*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
2600 {
2601     _PySSLError err;
2602     int sockstate, nonblocking, ret;
2603     int zeros = 0;
2604     PySocketSockObject *sock = GET_SOCKET(self);
2605     _PyTime_t timeout, deadline = 0;
2606     int has_timeout;
2607 
2608     if (sock != NULL) {
2609         /* Guard against closed socket */
2610         if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
2611             _setSSLError("Underlying socket connection gone",
2612                          PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2613             return NULL;
2614         }
2615         Py_INCREF(sock);
2616 
2617         /* Just in case the blocking state of the socket has been changed */
2618         nonblocking = (sock->sock_timeout >= 0);
2619         BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2620         BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2621     }
2622 
2623     timeout = GET_SOCKET_TIMEOUT(sock);
2624     has_timeout = (timeout > 0);
2625     if (has_timeout)
2626         deadline = _PyTime_GetMonotonicClock() + timeout;
2627 
2628     while (1) {
2629         PySSL_BEGIN_ALLOW_THREADS
2630         /* Disable read-ahead so that unwrap can work correctly.
2631          * Otherwise OpenSSL might read in too much data,
2632          * eating clear text data that happens to be
2633          * transmitted after the SSL shutdown.
2634          * Should be safe to call repeatedly every time this
2635          * function is used and the shutdown_seen_zero != 0
2636          * condition is met.
2637          */
2638         if (self->shutdown_seen_zero)
2639             SSL_set_read_ahead(self->ssl, 0);
2640         ret = SSL_shutdown(self->ssl);
2641         err = _PySSL_errno(ret < 0, self->ssl, ret);
2642         PySSL_END_ALLOW_THREADS
2643         self->err = err;
2644 
2645         /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2646         if (ret > 0)
2647             break;
2648         if (ret == 0) {
2649             /* Don't loop endlessly; instead preserve legacy
2650                behaviour of trying SSL_shutdown() only twice.
2651                This looks necessary for OpenSSL < 0.9.8m */
2652             if (++zeros > 1)
2653                 break;
2654             /* Shutdown was sent, now try receiving */
2655             self->shutdown_seen_zero = 1;
2656             continue;
2657         }
2658 
2659         if (has_timeout)
2660             timeout = deadline - _PyTime_GetMonotonicClock();
2661 
2662         /* Possibly retry shutdown until timeout or failure */
2663         if (err.ssl == SSL_ERROR_WANT_READ)
2664             sockstate = PySSL_select(sock, 0, timeout);
2665         else if (err.ssl == SSL_ERROR_WANT_WRITE)
2666             sockstate = PySSL_select(sock, 1, timeout);
2667         else
2668             break;
2669 
2670         if (sockstate == SOCKET_HAS_TIMED_OUT) {
2671             if (err.ssl == SSL_ERROR_WANT_READ)
2672                 PyErr_SetString(PySocketModule.timeout_error,
2673                                 "The read operation timed out");
2674             else
2675                 PyErr_SetString(PySocketModule.timeout_error,
2676                                 "The write operation timed out");
2677             goto error;
2678         }
2679         else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2680             PyErr_SetString(PySSLErrorObject,
2681                             "Underlying socket too large for select().");
2682             goto error;
2683         }
2684         else if (sockstate != SOCKET_OPERATION_OK)
2685             /* Retain the SSL error code */
2686             break;
2687     }
2688 
2689     if (ret < 0) {
2690         Py_XDECREF(sock);
2691         return PySSL_SetError(self, ret, __FILE__, __LINE__);
2692     }
2693     if (sock)
2694         /* It's already INCREF'ed */
2695         return (PyObject *) sock;
2696     else
2697         Py_RETURN_NONE;
2698 
2699 error:
2700     Py_XDECREF(sock);
2701     return NULL;
2702 }
2703 
2704 /*[clinic input]
2705 _ssl._SSLSocket.get_channel_binding
2706    cb_type: str = "tls-unique"
2707 
2708 Get channel binding data for current connection.
2709 
2710 Raise ValueError if the requested `cb_type` is not supported.  Return bytes
2711 of the data or None if the data is not available (e.g. before the handshake).
2712 Only 'tls-unique' channel binding data from RFC 5929 is supported.
2713 [clinic start generated code]*/
2714 
2715 static PyObject *
_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket * self,const char * cb_type)2716 _ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2717                                          const char *cb_type)
2718 /*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
2719 {
2720     char buf[PySSL_CB_MAXLEN];
2721     size_t len;
2722 
2723     if (strcmp(cb_type, "tls-unique") == 0) {
2724         if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2725             /* if session is resumed XOR we are the client */
2726             len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2727         }
2728         else {
2729             /* if a new session XOR we are the server */
2730             len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2731         }
2732     }
2733     else {
2734         PyErr_Format(
2735             PyExc_ValueError,
2736             "'%s' channel binding type not implemented",
2737             cb_type
2738         );
2739         return NULL;
2740     }
2741 
2742     /* It cannot be negative in current OpenSSL version as of July 2011 */
2743     if (len == 0)
2744         Py_RETURN_NONE;
2745 
2746     return PyBytes_FromStringAndSize(buf, len);
2747 }
2748 
2749 /*[clinic input]
2750 _ssl._SSLSocket.verify_client_post_handshake
2751 
2752 Initiate TLS 1.3 post-handshake authentication
2753 [clinic start generated code]*/
2754 
2755 static PyObject *
_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket * self)2756 _ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2757 /*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2758 {
2759 #ifdef TLS1_3_VERSION
2760     int err = SSL_verify_client_post_handshake(self->ssl);
2761     if (err == 0)
2762         return _setSSLError(NULL, 0, __FILE__, __LINE__);
2763     else
2764         Py_RETURN_NONE;
2765 #else
2766     PyErr_SetString(PyExc_NotImplementedError,
2767                     "Post-handshake auth is not supported by your "
2768                     "OpenSSL version.");
2769     return NULL;
2770 #endif
2771 }
2772 
2773 #ifdef OPENSSL_VERSION_1_1
2774 
2775 static SSL_SESSION*
_ssl_session_dup(SSL_SESSION * session)2776 _ssl_session_dup(SSL_SESSION *session) {
2777     SSL_SESSION *newsession = NULL;
2778     int slen;
2779     unsigned char *senc = NULL, *p;
2780     const unsigned char *const_p;
2781 
2782     if (session == NULL) {
2783         PyErr_SetString(PyExc_ValueError, "Invalid session");
2784         goto error;
2785     }
2786 
2787     /* get length */
2788     slen = i2d_SSL_SESSION(session, NULL);
2789     if (slen == 0 || slen > 0xFF00) {
2790         PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2791         goto error;
2792     }
2793     if ((senc = PyMem_Malloc(slen)) == NULL) {
2794         PyErr_NoMemory();
2795         goto error;
2796     }
2797     p = senc;
2798     if (!i2d_SSL_SESSION(session, &p)) {
2799         PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2800         goto error;
2801     }
2802     const_p = senc;
2803     newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2804     if (session == NULL) {
2805         goto error;
2806     }
2807     PyMem_Free(senc);
2808     return newsession;
2809   error:
2810     if (senc != NULL) {
2811         PyMem_Free(senc);
2812     }
2813     return NULL;
2814 }
2815 #endif
2816 
2817 static PyObject *
PySSL_get_session(PySSLSocket * self,void * closure)2818 PySSL_get_session(PySSLSocket *self, void *closure) {
2819     /* get_session can return sessions from a server-side connection,
2820      * it does not check for handshake done or client socket. */
2821     PySSLSession *pysess;
2822     SSL_SESSION *session;
2823 
2824 #ifdef OPENSSL_VERSION_1_1
2825     /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2826      * https://github.com/openssl/openssl/issues/1550 */
2827     session = SSL_get0_session(self->ssl);  /* borrowed reference */
2828     if (session == NULL) {
2829         Py_RETURN_NONE;
2830     }
2831     if ((session = _ssl_session_dup(session)) == NULL) {
2832         return NULL;
2833     }
2834 #else
2835     session = SSL_get1_session(self->ssl);
2836     if (session == NULL) {
2837         Py_RETURN_NONE;
2838     }
2839 #endif
2840     pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
2841     if (pysess == NULL) {
2842         SSL_SESSION_free(session);
2843         return NULL;
2844     }
2845 
2846     assert(self->ctx);
2847     pysess->ctx = self->ctx;
2848     Py_INCREF(pysess->ctx);
2849     pysess->session = session;
2850     PyObject_GC_Track(pysess);
2851     return (PyObject *)pysess;
2852 }
2853 
PySSL_set_session(PySSLSocket * self,PyObject * value,void * closure)2854 static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2855                              void *closure)
2856                               {
2857     PySSLSession *pysess;
2858 #ifdef OPENSSL_VERSION_1_1
2859     SSL_SESSION *session;
2860 #endif
2861     int result;
2862 
2863     if (!PySSLSession_Check(value)) {
2864         PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2865         return -1;
2866     }
2867     pysess = (PySSLSession *)value;
2868 
2869     if (self->ctx->ctx != pysess->ctx->ctx) {
2870         PyErr_SetString(PyExc_ValueError,
2871                         "Session refers to a different SSLContext.");
2872         return -1;
2873     }
2874     if (self->socket_type != PY_SSL_CLIENT) {
2875         PyErr_SetString(PyExc_ValueError,
2876                         "Cannot set session for server-side SSLSocket.");
2877         return -1;
2878     }
2879     if (SSL_is_init_finished(self->ssl)) {
2880         PyErr_SetString(PyExc_ValueError,
2881                         "Cannot set session after handshake.");
2882         return -1;
2883     }
2884 #ifdef OPENSSL_VERSION_1_1
2885     /* duplicate session */
2886     if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2887         return -1;
2888     }
2889     result = SSL_set_session(self->ssl, session);
2890     /* free duplicate, SSL_set_session() bumps ref count */
2891     SSL_SESSION_free(session);
2892 #else
2893     result = SSL_set_session(self->ssl, pysess->session);
2894 #endif
2895     if (result == 0) {
2896         _setSSLError(NULL, 0, __FILE__, __LINE__);
2897         return -1;
2898     }
2899     return 0;
2900 }
2901 
2902 PyDoc_STRVAR(PySSL_set_session_doc,
2903 "_setter_session(session)\n\
2904 \
2905 Get / set SSLSession.");
2906 
2907 static PyObject *
PySSL_get_session_reused(PySSLSocket * self,void * closure)2908 PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2909     if (SSL_session_reused(self->ssl)) {
2910         Py_RETURN_TRUE;
2911     } else {
2912         Py_RETURN_FALSE;
2913     }
2914 }
2915 
2916 PyDoc_STRVAR(PySSL_get_session_reused_doc,
2917 "Was the client session reused during handshake?");
2918 
2919 static PyGetSetDef ssl_getsetlist[] = {
2920     {"context", (getter) PySSL_get_context,
2921                 (setter) PySSL_set_context, PySSL_set_context_doc},
2922     {"server_side", (getter) PySSL_get_server_side, NULL,
2923                     PySSL_get_server_side_doc},
2924     {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2925                         PySSL_get_server_hostname_doc},
2926     {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2927               PySSL_get_owner_doc},
2928     {"session", (getter) PySSL_get_session,
2929                 (setter) PySSL_set_session, PySSL_set_session_doc},
2930     {"session_reused", (getter) PySSL_get_session_reused, NULL,
2931               PySSL_get_session_reused_doc},
2932     {NULL},            /* sentinel */
2933 };
2934 
2935 static PyMethodDef PySSLMethods[] = {
2936     _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2937     _SSL__SSLSOCKET_WRITE_METHODDEF
2938     _SSL__SSLSOCKET_READ_METHODDEF
2939     _SSL__SSLSOCKET_PENDING_METHODDEF
2940     _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2941     _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
2942     _SSL__SSLSOCKET_CIPHER_METHODDEF
2943     _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2944     _SSL__SSLSOCKET_VERSION_METHODDEF
2945     _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2946     _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2947     _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2948     _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2949     _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
2950     {NULL, NULL}
2951 };
2952 
2953 static PyTypeObject PySSLSocket_Type = {
2954     PyVarObject_HEAD_INIT(NULL, 0)
2955     "_ssl._SSLSocket",                  /*tp_name*/
2956     sizeof(PySSLSocket),                /*tp_basicsize*/
2957     0,                                  /*tp_itemsize*/
2958     /* methods */
2959     (destructor)PySSL_dealloc,          /*tp_dealloc*/
2960     0,                                  /*tp_print*/
2961     0,                                  /*tp_getattr*/
2962     0,                                  /*tp_setattr*/
2963     0,                                  /*tp_reserved*/
2964     0,                                  /*tp_repr*/
2965     0,                                  /*tp_as_number*/
2966     0,                                  /*tp_as_sequence*/
2967     0,                                  /*tp_as_mapping*/
2968     0,                                  /*tp_hash*/
2969     0,                                  /*tp_call*/
2970     0,                                  /*tp_str*/
2971     0,                                  /*tp_getattro*/
2972     0,                                  /*tp_setattro*/
2973     0,                                  /*tp_as_buffer*/
2974     Py_TPFLAGS_DEFAULT,                 /*tp_flags*/
2975     0,                                  /*tp_doc*/
2976     0,                                  /*tp_traverse*/
2977     0,                                  /*tp_clear*/
2978     0,                                  /*tp_richcompare*/
2979     0,                                  /*tp_weaklistoffset*/
2980     0,                                  /*tp_iter*/
2981     0,                                  /*tp_iternext*/
2982     PySSLMethods,                       /*tp_methods*/
2983     0,                                  /*tp_members*/
2984     ssl_getsetlist,                     /*tp_getset*/
2985 };
2986 
2987 
2988 /*
2989  * _SSLContext objects
2990  */
2991 
2992 static int
_set_verify_mode(PySSLContext * self,enum py_ssl_cert_requirements n)2993 _set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
2994 {
2995     int mode;
2996     int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2997 
2998     switch(n) {
2999     case PY_SSL_CERT_NONE:
3000         mode = SSL_VERIFY_NONE;
3001         break;
3002     case PY_SSL_CERT_OPTIONAL:
3003         mode = SSL_VERIFY_PEER;
3004         break;
3005     case PY_SSL_CERT_REQUIRED:
3006         mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
3007         break;
3008     default:
3009          PyErr_SetString(PyExc_ValueError,
3010                         "invalid value for verify_mode");
3011         return -1;
3012     }
3013 
3014     /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3015      * server sockets and SSL_set_post_handshake_auth() for client. */
3016 
3017     /* keep current verify cb */
3018     verify_cb = SSL_CTX_get_verify_callback(self->ctx);
3019     SSL_CTX_set_verify(self->ctx, mode, verify_cb);
3020     return 0;
3021 }
3022 
3023 /*[clinic input]
3024 @classmethod
3025 _ssl._SSLContext.__new__
3026     protocol as proto_version: int
3027     /
3028 [clinic start generated code]*/
3029 
3030 static PyObject *
_ssl__SSLContext_impl(PyTypeObject * type,int proto_version)3031 _ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
3032 /*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
3033 {
3034     PySSLContext *self;
3035     long options;
3036     SSL_CTX *ctx = NULL;
3037     X509_VERIFY_PARAM *params;
3038     int result;
3039 #if defined(SSL_MODE_RELEASE_BUFFERS)
3040     unsigned long libver;
3041 #endif
3042 
3043     PySSL_BEGIN_ALLOW_THREADS
3044     switch(proto_version) {
3045 #if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
3046     case PY_SSL_VERSION_SSL3:
3047         ctx = SSL_CTX_new(SSLv3_method());
3048         break;
3049 #endif
3050 #if (defined(TLS1_VERSION) && \
3051         !defined(OPENSSL_NO_TLS1) && \
3052         !defined(OPENSSL_NO_TLS1_METHOD))
3053     case PY_SSL_VERSION_TLS1:
3054         ctx = SSL_CTX_new(TLSv1_method());
3055         break;
3056 #endif
3057 #if (defined(TLS1_1_VERSION) && \
3058         !defined(OPENSSL_NO_TLS1_1) && \
3059         !defined(OPENSSL_NO_TLS1_1_METHOD))
3060     case PY_SSL_VERSION_TLS1_1:
3061         ctx = SSL_CTX_new(TLSv1_1_method());
3062         break;
3063 #endif
3064 #if (defined(TLS1_2_VERSION) && \
3065         !defined(OPENSSL_NO_TLS1_2) && \
3066         !defined(OPENSSL_NO_TLS1_2_METHOD))
3067     case PY_SSL_VERSION_TLS1_2:
3068         ctx = SSL_CTX_new(TLSv1_2_method());
3069         break;
3070 #endif
3071     case PY_SSL_VERSION_TLS:
3072         /* SSLv23 */
3073         ctx = SSL_CTX_new(TLS_method());
3074         break;
3075     case PY_SSL_VERSION_TLS_CLIENT:
3076         ctx = SSL_CTX_new(TLS_client_method());
3077         break;
3078     case PY_SSL_VERSION_TLS_SERVER:
3079         ctx = SSL_CTX_new(TLS_server_method());
3080         break;
3081     default:
3082         proto_version = -1;
3083     }
3084     PySSL_END_ALLOW_THREADS
3085 
3086     if (proto_version == -1) {
3087         PyErr_SetString(PyExc_ValueError,
3088                         "invalid or unsupported protocol version");
3089         return NULL;
3090     }
3091     if (ctx == NULL) {
3092         _setSSLError(NULL, 0, __FILE__, __LINE__);
3093         return NULL;
3094     }
3095 
3096     assert(type != NULL && type->tp_alloc != NULL);
3097     self = (PySSLContext *) type->tp_alloc(type, 0);
3098     if (self == NULL) {
3099         SSL_CTX_free(ctx);
3100         return NULL;
3101     }
3102     self->ctx = ctx;
3103     self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
3104     self->protocol = proto_version;
3105 #if HAVE_NPN
3106     self->npn_protocols = NULL;
3107 #endif
3108 #if HAVE_ALPN
3109     self->alpn_protocols = NULL;
3110 #endif
3111 #ifndef OPENSSL_NO_TLSEXT
3112     self->set_sni_cb = NULL;
3113 #endif
3114     /* Don't check host name by default */
3115     if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3116         self->check_hostname = 1;
3117         if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
3118             Py_DECREF(self);
3119             return NULL;
3120         }
3121     } else {
3122         self->check_hostname = 0;
3123         if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
3124             Py_DECREF(self);
3125             return NULL;
3126         }
3127     }
3128     /* Defaults */
3129     options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3130     if (proto_version != PY_SSL_VERSION_SSL2)
3131         options |= SSL_OP_NO_SSLv2;
3132     if (proto_version != PY_SSL_VERSION_SSL3)
3133         options |= SSL_OP_NO_SSLv3;
3134     /* Minimal security flags for server and client side context.
3135      * Client sockets ignore server-side parameters. */
3136 #ifdef SSL_OP_NO_COMPRESSION
3137     options |= SSL_OP_NO_COMPRESSION;
3138 #endif
3139 #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3140     options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3141 #endif
3142 #ifdef SSL_OP_SINGLE_DH_USE
3143     options |= SSL_OP_SINGLE_DH_USE;
3144 #endif
3145 #ifdef SSL_OP_SINGLE_ECDH_USE
3146     options |= SSL_OP_SINGLE_ECDH_USE;
3147 #endif
3148     SSL_CTX_set_options(self->ctx, options);
3149 
3150     /* A bare minimum cipher list without completely broken cipher suites.
3151      * It's far from perfect but gives users a better head start. */
3152     if (proto_version != PY_SSL_VERSION_SSL2) {
3153 #if PY_SSL_DEFAULT_CIPHERS == 2
3154         /* stick to OpenSSL's default settings */
3155         result = 1;
3156 #else
3157         result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3158 #endif
3159     } else {
3160         /* SSLv2 needs MD5 */
3161         result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3162     }
3163     if (result == 0) {
3164         Py_DECREF(self);
3165         ERR_clear_error();
3166         PyErr_SetString(PySSLErrorObject,
3167                         "No cipher can be selected.");
3168         return NULL;
3169     }
3170 
3171 #if defined(SSL_MODE_RELEASE_BUFFERS)
3172     /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3173        usage for no cost at all. However, don't do this for OpenSSL versions
3174        between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3175        2014-0198. I can't find exactly which beta fixed this CVE, so be
3176        conservative and assume it wasn't fixed until release. We do this check
3177        at runtime to avoid problems from the dynamic linker.
3178        See #25672 for more on this. */
3179     libver = OpenSSL_version_num();
3180     if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3181         !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3182         SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3183     }
3184 #endif
3185 
3186 
3187 #if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
3188     /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3189        prime256v1 by default.  This is Apache mod_ssl's initialization
3190        policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3191      */
3192 #if defined(SSL_CTX_set_ecdh_auto)
3193     SSL_CTX_set_ecdh_auto(self->ctx, 1);
3194 #else
3195     {
3196         EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3197         SSL_CTX_set_tmp_ecdh(self->ctx, key);
3198         EC_KEY_free(key);
3199     }
3200 #endif
3201 #endif
3202 
3203 #define SID_CTX "Python"
3204     SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3205                                    sizeof(SID_CTX));
3206 #undef SID_CTX
3207 
3208     params = SSL_CTX_get0_param(self->ctx);
3209 #ifdef X509_V_FLAG_TRUSTED_FIRST
3210     /* Improve trust chain building when cross-signed intermediate
3211        certificates are present. See https://bugs.python.org/issue23476. */
3212     X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
3213 #endif
3214     X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
3215 
3216 #ifdef TLS1_3_VERSION
3217     self->post_handshake_auth = 0;
3218     SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3219 #endif
3220 
3221     return (PyObject *)self;
3222 }
3223 
3224 static int
context_traverse(PySSLContext * self,visitproc visit,void * arg)3225 context_traverse(PySSLContext *self, visitproc visit, void *arg)
3226 {
3227 #ifndef OPENSSL_NO_TLSEXT
3228     Py_VISIT(self->set_sni_cb);
3229 #endif
3230     return 0;
3231 }
3232 
3233 static int
context_clear(PySSLContext * self)3234 context_clear(PySSLContext *self)
3235 {
3236 #ifndef OPENSSL_NO_TLSEXT
3237     Py_CLEAR(self->set_sni_cb);
3238 #endif
3239     return 0;
3240 }
3241 
3242 static void
context_dealloc(PySSLContext * self)3243 context_dealloc(PySSLContext *self)
3244 {
3245     /* bpo-31095: UnTrack is needed before calling any callbacks */
3246     PyObject_GC_UnTrack(self);
3247     context_clear(self);
3248     SSL_CTX_free(self->ctx);
3249 #if HAVE_NPN
3250     PyMem_FREE(self->npn_protocols);
3251 #endif
3252 #if HAVE_ALPN
3253     PyMem_FREE(self->alpn_protocols);
3254 #endif
3255     Py_TYPE(self)->tp_free(self);
3256 }
3257 
3258 /*[clinic input]
3259 _ssl._SSLContext.set_ciphers
3260     cipherlist: str
3261     /
3262 [clinic start generated code]*/
3263 
3264 static PyObject *
_ssl__SSLContext_set_ciphers_impl(PySSLContext * self,const char * cipherlist)3265 _ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3266 /*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3267 {
3268     int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
3269     if (ret == 0) {
3270         /* Clearing the error queue is necessary on some OpenSSL versions,
3271            otherwise the error will be reported again when another SSL call
3272            is done. */
3273         ERR_clear_error();
3274         PyErr_SetString(PySSLErrorObject,
3275                         "No cipher can be selected.");
3276         return NULL;
3277     }
3278     Py_RETURN_NONE;
3279 }
3280 
3281 #if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3282 /*[clinic input]
3283 _ssl._SSLContext.get_ciphers
3284 [clinic start generated code]*/
3285 
3286 static PyObject *
_ssl__SSLContext_get_ciphers_impl(PySSLContext * self)3287 _ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3288 /*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3289 {
3290     SSL *ssl = NULL;
3291     STACK_OF(SSL_CIPHER) *sk = NULL;
3292     const SSL_CIPHER *cipher;
3293     int i=0;
3294     PyObject *result = NULL, *dct;
3295 
3296     ssl = SSL_new(self->ctx);
3297     if (ssl == NULL) {
3298         _setSSLError(NULL, 0, __FILE__, __LINE__);
3299         goto exit;
3300     }
3301     sk = SSL_get_ciphers(ssl);
3302 
3303     result = PyList_New(sk_SSL_CIPHER_num(sk));
3304     if (result == NULL) {
3305         goto exit;
3306     }
3307 
3308     for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3309         cipher = sk_SSL_CIPHER_value(sk, i);
3310         dct = cipher_to_dict(cipher);
3311         if (dct == NULL) {
3312             Py_CLEAR(result);
3313             goto exit;
3314         }
3315         PyList_SET_ITEM(result, i, dct);
3316     }
3317 
3318   exit:
3319     if (ssl != NULL)
3320         SSL_free(ssl);
3321     return result;
3322 
3323 }
3324 #endif
3325 
3326 
3327 #if HAVE_NPN || HAVE_ALPN
3328 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)3329 do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3330                       const unsigned char *server_protocols, unsigned int server_protocols_len,
3331                       const unsigned char *client_protocols, unsigned int client_protocols_len)
3332 {
3333     int ret;
3334     if (client_protocols == NULL) {
3335         client_protocols = (unsigned char *)"";
3336         client_protocols_len = 0;
3337     }
3338     if (server_protocols == NULL) {
3339         server_protocols = (unsigned char *)"";
3340         server_protocols_len = 0;
3341     }
3342 
3343     ret = SSL_select_next_proto(out, outlen,
3344                                 server_protocols, server_protocols_len,
3345                                 client_protocols, client_protocols_len);
3346     if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3347         return SSL_TLSEXT_ERR_NOACK;
3348 
3349     return SSL_TLSEXT_ERR_OK;
3350 }
3351 #endif
3352 
3353 #if HAVE_NPN
3354 /* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3355 static int
_advertiseNPN_cb(SSL * s,const unsigned char ** data,unsigned int * len,void * args)3356 _advertiseNPN_cb(SSL *s,
3357                  const unsigned char **data, unsigned int *len,
3358                  void *args)
3359 {
3360     PySSLContext *ssl_ctx = (PySSLContext *) args;
3361 
3362     if (ssl_ctx->npn_protocols == NULL) {
3363         *data = (unsigned char *)"";
3364         *len = 0;
3365     } else {
3366         *data = ssl_ctx->npn_protocols;
3367         *len = ssl_ctx->npn_protocols_len;
3368     }
3369 
3370     return SSL_TLSEXT_ERR_OK;
3371 }
3372 /* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3373 static int
_selectNPN_cb(SSL * s,unsigned char ** out,unsigned char * outlen,const unsigned char * server,unsigned int server_len,void * args)3374 _selectNPN_cb(SSL *s,
3375               unsigned char **out, unsigned char *outlen,
3376               const unsigned char *server, unsigned int server_len,
3377               void *args)
3378 {
3379     PySSLContext *ctx = (PySSLContext *)args;
3380     return do_protocol_selection(0, out, outlen, server, server_len,
3381                                  ctx->npn_protocols, ctx->npn_protocols_len);
3382 }
3383 #endif
3384 
3385 /*[clinic input]
3386 _ssl._SSLContext._set_npn_protocols
3387     protos: Py_buffer
3388     /
3389 [clinic start generated code]*/
3390 
3391 static PyObject *
_ssl__SSLContext__set_npn_protocols_impl(PySSLContext * self,Py_buffer * protos)3392 _ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3393                                          Py_buffer *protos)
3394 /*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
3395 {
3396 #if HAVE_NPN
3397     PyMem_Free(self->npn_protocols);
3398     self->npn_protocols = PyMem_Malloc(protos->len);
3399     if (self->npn_protocols == NULL)
3400         return PyErr_NoMemory();
3401     memcpy(self->npn_protocols, protos->buf, protos->len);
3402     self->npn_protocols_len = (int) protos->len;
3403 
3404     /* set both server and client callbacks, because the context can
3405      * be used to create both types of sockets */
3406     SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3407                                           _advertiseNPN_cb,
3408                                           self);
3409     SSL_CTX_set_next_proto_select_cb(self->ctx,
3410                                      _selectNPN_cb,
3411                                      self);
3412 
3413     Py_RETURN_NONE;
3414 #else
3415     PyErr_SetString(PyExc_NotImplementedError,
3416                     "The NPN extension requires OpenSSL 1.0.1 or later.");
3417     return NULL;
3418 #endif
3419 }
3420 
3421 #if HAVE_ALPN
3422 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)3423 _selectALPN_cb(SSL *s,
3424               const unsigned char **out, unsigned char *outlen,
3425               const unsigned char *client_protocols, unsigned int client_protocols_len,
3426               void *args)
3427 {
3428     PySSLContext *ctx = (PySSLContext *)args;
3429     return do_protocol_selection(1, (unsigned char **)out, outlen,
3430                                  ctx->alpn_protocols, ctx->alpn_protocols_len,
3431                                  client_protocols, client_protocols_len);
3432 }
3433 #endif
3434 
3435 /*[clinic input]
3436 _ssl._SSLContext._set_alpn_protocols
3437     protos: Py_buffer
3438     /
3439 [clinic start generated code]*/
3440 
3441 static PyObject *
_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext * self,Py_buffer * protos)3442 _ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3443                                           Py_buffer *protos)
3444 /*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
3445 {
3446 #if HAVE_ALPN
3447     if ((size_t)protos->len > UINT_MAX) {
3448         PyErr_Format(PyExc_OverflowError,
3449             "protocols longer than %u bytes", UINT_MAX);
3450         return NULL;
3451     }
3452 
3453     PyMem_FREE(self->alpn_protocols);
3454     self->alpn_protocols = PyMem_Malloc(protos->len);
3455     if (!self->alpn_protocols)
3456         return PyErr_NoMemory();
3457     memcpy(self->alpn_protocols, protos->buf, protos->len);
3458     self->alpn_protocols_len = (unsigned int)protos->len;
3459 
3460     if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3461         return PyErr_NoMemory();
3462     SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3463 
3464     Py_RETURN_NONE;
3465 #else
3466     PyErr_SetString(PyExc_NotImplementedError,
3467                     "The ALPN extension requires OpenSSL 1.0.2 or later.");
3468     return NULL;
3469 #endif
3470 }
3471 
3472 static PyObject *
get_verify_mode(PySSLContext * self,void * c)3473 get_verify_mode(PySSLContext *self, void *c)
3474 {
3475     /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3476     int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3477                 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3478     switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
3479     case SSL_VERIFY_NONE:
3480         return PyLong_FromLong(PY_SSL_CERT_NONE);
3481     case SSL_VERIFY_PEER:
3482         return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3483     case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3484         return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3485     }
3486     PyErr_SetString(PySSLErrorObject,
3487                     "invalid return value from SSL_CTX_get_verify_mode");
3488     return NULL;
3489 }
3490 
3491 static int
set_verify_mode(PySSLContext * self,PyObject * arg,void * c)3492 set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3493 {
3494     int n;
3495     if (!PyArg_Parse(arg, "i", &n))
3496         return -1;
3497     if (n == PY_SSL_CERT_NONE && self->check_hostname) {
3498         PyErr_SetString(PyExc_ValueError,
3499                         "Cannot set verify_mode to CERT_NONE when "
3500                         "check_hostname is enabled.");
3501         return -1;
3502     }
3503     return _set_verify_mode(self, n);
3504 }
3505 
3506 static PyObject *
get_verify_flags(PySSLContext * self,void * c)3507 get_verify_flags(PySSLContext *self, void *c)
3508 {
3509     X509_VERIFY_PARAM *param;
3510     unsigned long flags;
3511 
3512     param = SSL_CTX_get0_param(self->ctx);
3513     flags = X509_VERIFY_PARAM_get_flags(param);
3514     return PyLong_FromUnsignedLong(flags);
3515 }
3516 
3517 static int
set_verify_flags(PySSLContext * self,PyObject * arg,void * c)3518 set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3519 {
3520     X509_VERIFY_PARAM *param;
3521     unsigned long new_flags, flags, set, clear;
3522 
3523     if (!PyArg_Parse(arg, "k", &new_flags))
3524         return -1;
3525     param = SSL_CTX_get0_param(self->ctx);
3526     flags = X509_VERIFY_PARAM_get_flags(param);
3527     clear = flags & ~new_flags;
3528     set = ~flags & new_flags;
3529     if (clear) {
3530         if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
3531             _setSSLError(NULL, 0, __FILE__, __LINE__);
3532             return -1;
3533         }
3534     }
3535     if (set) {
3536         if (!X509_VERIFY_PARAM_set_flags(param, set)) {
3537             _setSSLError(NULL, 0, __FILE__, __LINE__);
3538             return -1;
3539         }
3540     }
3541     return 0;
3542 }
3543 
3544 /* Getter and setter for protocol version */
3545 #if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3546 
3547 
3548 static int
set_min_max_proto_version(PySSLContext * self,PyObject * arg,int what)3549 set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3550 {
3551     long v;
3552     int result;
3553 
3554     if (!PyArg_Parse(arg, "l", &v))
3555         return -1;
3556     if (v > INT_MAX) {
3557         PyErr_SetString(PyExc_OverflowError, "Option is too long");
3558         return -1;
3559     }
3560 
3561     switch(self->protocol) {
3562     case PY_SSL_VERSION_TLS_CLIENT:  /* fall through */
3563     case PY_SSL_VERSION_TLS_SERVER:  /* fall through */
3564     case PY_SSL_VERSION_TLS:
3565         break;
3566     default:
3567         PyErr_SetString(
3568             PyExc_ValueError,
3569             "The context's protocol doesn't support modification of "
3570             "highest and lowest version."
3571         );
3572         return -1;
3573     }
3574 
3575     if (what == 0) {
3576         switch(v) {
3577         case PY_PROTO_MINIMUM_SUPPORTED:
3578             v = 0;
3579             break;
3580         case PY_PROTO_MAXIMUM_SUPPORTED:
3581             /* Emulate max for set_min_proto_version */
3582             v = PY_PROTO_MAXIMUM_AVAILABLE;
3583             break;
3584         default:
3585             break;
3586         }
3587         result = SSL_CTX_set_min_proto_version(self->ctx, v);
3588     }
3589     else {
3590         switch(v) {
3591         case PY_PROTO_MAXIMUM_SUPPORTED:
3592             v = 0;
3593             break;
3594         case PY_PROTO_MINIMUM_SUPPORTED:
3595             /* Emulate max for set_min_proto_version */
3596             v = PY_PROTO_MINIMUM_AVAILABLE;
3597             break;
3598         default:
3599             break;
3600         }
3601         result = SSL_CTX_set_max_proto_version(self->ctx, v);
3602     }
3603     if (result == 0) {
3604         PyErr_Format(PyExc_ValueError,
3605                      "Unsupported protocol version 0x%x", v);
3606         return -1;
3607     }
3608     return 0;
3609 }
3610 
3611 static PyObject *
get_minimum_version(PySSLContext * self,void * c)3612 get_minimum_version(PySSLContext *self, void *c)
3613 {
3614     int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3615     if (v == 0) {
3616         v = PY_PROTO_MINIMUM_SUPPORTED;
3617     }
3618     return PyLong_FromLong(v);
3619 }
3620 
3621 static int
set_minimum_version(PySSLContext * self,PyObject * arg,void * c)3622 set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3623 {
3624     return set_min_max_proto_version(self, arg, 0);
3625 }
3626 
3627 static PyObject *
get_maximum_version(PySSLContext * self,void * c)3628 get_maximum_version(PySSLContext *self, void *c)
3629 {
3630     int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3631     if (v == 0) {
3632         v = PY_PROTO_MAXIMUM_SUPPORTED;
3633     }
3634     return PyLong_FromLong(v);
3635 }
3636 
3637 static int
set_maximum_version(PySSLContext * self,PyObject * arg,void * c)3638 set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3639 {
3640     return set_min_max_proto_version(self, arg, 1);
3641 }
3642 #endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3643 
3644 static PyObject *
get_options(PySSLContext * self,void * c)3645 get_options(PySSLContext *self, void *c)
3646 {
3647     return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3648 }
3649 
3650 static int
set_options(PySSLContext * self,PyObject * arg,void * c)3651 set_options(PySSLContext *self, PyObject *arg, void *c)
3652 {
3653     long new_opts, opts, set, clear;
3654     if (!PyArg_Parse(arg, "l", &new_opts))
3655         return -1;
3656     opts = SSL_CTX_get_options(self->ctx);
3657     clear = opts & ~new_opts;
3658     set = ~opts & new_opts;
3659     if (clear) {
3660 #ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3661         SSL_CTX_clear_options(self->ctx, clear);
3662 #else
3663         PyErr_SetString(PyExc_ValueError,
3664                         "can't clear options before OpenSSL 0.9.8m");
3665         return -1;
3666 #endif
3667     }
3668     if (set)
3669         SSL_CTX_set_options(self->ctx, set);
3670     return 0;
3671 }
3672 
3673 static PyObject *
get_host_flags(PySSLContext * self,void * c)3674 get_host_flags(PySSLContext *self, void *c)
3675 {
3676     return PyLong_FromUnsignedLong(self->hostflags);
3677 }
3678 
3679 static int
set_host_flags(PySSLContext * self,PyObject * arg,void * c)3680 set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3681 {
3682     X509_VERIFY_PARAM *param;
3683     unsigned int new_flags = 0;
3684 
3685     if (!PyArg_Parse(arg, "I", &new_flags))
3686         return -1;
3687 
3688     param = SSL_CTX_get0_param(self->ctx);
3689     self->hostflags = new_flags;
3690     X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3691     return 0;
3692 }
3693 
3694 static PyObject *
get_check_hostname(PySSLContext * self,void * c)3695 get_check_hostname(PySSLContext *self, void *c)
3696 {
3697     return PyBool_FromLong(self->check_hostname);
3698 }
3699 
3700 static int
set_check_hostname(PySSLContext * self,PyObject * arg,void * c)3701 set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3702 {
3703     int check_hostname;
3704     if (!PyArg_Parse(arg, "p", &check_hostname))
3705         return -1;
3706     if (check_hostname &&
3707             SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
3708         /* check_hostname = True sets verify_mode = CERT_REQUIRED */
3709         if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
3710             return -1;
3711         }
3712     }
3713     self->check_hostname = check_hostname;
3714     return 0;
3715 }
3716 
3717 static PyObject *
get_post_handshake_auth(PySSLContext * self,void * c)3718 get_post_handshake_auth(PySSLContext *self, void *c) {
3719 #if TLS1_3_VERSION
3720     return PyBool_FromLong(self->post_handshake_auth);
3721 #else
3722     Py_RETURN_NONE;
3723 #endif
3724 }
3725 
3726 #if TLS1_3_VERSION
3727 static int
set_post_handshake_auth(PySSLContext * self,PyObject * arg,void * c)3728 set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
3729     if (arg == NULL) {
3730         PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3731         return -1;
3732     }
3733     int pha = PyObject_IsTrue(arg);
3734 
3735     if (pha == -1) {
3736         return -1;
3737     }
3738     self->post_handshake_auth = pha;
3739 
3740     /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3741      * server sockets and SSL_set_post_handshake_auth() for client. */
3742 
3743     return 0;
3744 }
3745 #endif
3746 
3747 static PyObject *
get_protocol(PySSLContext * self,void * c)3748 get_protocol(PySSLContext *self, void *c) {
3749     return PyLong_FromLong(self->protocol);
3750 }
3751 
3752 typedef struct {
3753     PyThreadState *thread_state;
3754     PyObject *callable;
3755     char *password;
3756     int size;
3757     int error;
3758 } _PySSLPasswordInfo;
3759 
3760 static int
_pwinfo_set(_PySSLPasswordInfo * pw_info,PyObject * password,const char * bad_type_error)3761 _pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3762             const char *bad_type_error)
3763 {
3764     /* Set the password and size fields of a _PySSLPasswordInfo struct
3765        from a unicode, bytes, or byte array object.
3766        The password field will be dynamically allocated and must be freed
3767        by the caller */
3768     PyObject *password_bytes = NULL;
3769     const char *data = NULL;
3770     Py_ssize_t size;
3771 
3772     if (PyUnicode_Check(password)) {
3773         password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3774         if (!password_bytes) {
3775             goto error;
3776         }
3777         data = PyBytes_AS_STRING(password_bytes);
3778         size = PyBytes_GET_SIZE(password_bytes);
3779     } else if (PyBytes_Check(password)) {
3780         data = PyBytes_AS_STRING(password);
3781         size = PyBytes_GET_SIZE(password);
3782     } else if (PyByteArray_Check(password)) {
3783         data = PyByteArray_AS_STRING(password);
3784         size = PyByteArray_GET_SIZE(password);
3785     } else {
3786         PyErr_SetString(PyExc_TypeError, bad_type_error);
3787         goto error;
3788     }
3789 
3790     if (size > (Py_ssize_t)INT_MAX) {
3791         PyErr_Format(PyExc_ValueError,
3792                      "password cannot be longer than %d bytes", INT_MAX);
3793         goto error;
3794     }
3795 
3796     PyMem_Free(pw_info->password);
3797     pw_info->password = PyMem_Malloc(size);
3798     if (!pw_info->password) {
3799         PyErr_SetString(PyExc_MemoryError,
3800                         "unable to allocate password buffer");
3801         goto error;
3802     }
3803     memcpy(pw_info->password, data, size);
3804     pw_info->size = (int)size;
3805 
3806     Py_XDECREF(password_bytes);
3807     return 1;
3808 
3809 error:
3810     Py_XDECREF(password_bytes);
3811     return 0;
3812 }
3813 
3814 static int
_password_callback(char * buf,int size,int rwflag,void * userdata)3815 _password_callback(char *buf, int size, int rwflag, void *userdata)
3816 {
3817     _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3818     PyObject *fn_ret = NULL;
3819 
3820     PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3821 
3822     if (pw_info->callable) {
3823         fn_ret = _PyObject_CallNoArg(pw_info->callable);
3824         if (!fn_ret) {
3825             /* TODO: It would be nice to move _ctypes_add_traceback() into the
3826                core python API, so we could use it to add a frame here */
3827             goto error;
3828         }
3829 
3830         if (!_pwinfo_set(pw_info, fn_ret,
3831                          "password callback must return a string")) {
3832             goto error;
3833         }
3834         Py_CLEAR(fn_ret);
3835     }
3836 
3837     if (pw_info->size > size) {
3838         PyErr_Format(PyExc_ValueError,
3839                      "password cannot be longer than %d bytes", size);
3840         goto error;
3841     }
3842 
3843     PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3844     memcpy(buf, pw_info->password, pw_info->size);
3845     return pw_info->size;
3846 
3847 error:
3848     Py_XDECREF(fn_ret);
3849     PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3850     pw_info->error = 1;
3851     return -1;
3852 }
3853 
3854 /*[clinic input]
3855 _ssl._SSLContext.load_cert_chain
3856     certfile: object
3857     keyfile: object = NULL
3858     password: object = NULL
3859 
3860 [clinic start generated code]*/
3861 
3862 static PyObject *
_ssl__SSLContext_load_cert_chain_impl(PySSLContext * self,PyObject * certfile,PyObject * keyfile,PyObject * password)3863 _ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3864                                       PyObject *keyfile, PyObject *password)
3865 /*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
3866 {
3867     PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
3868     pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3869     void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
3870     _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
3871     int r;
3872 
3873     errno = 0;
3874     ERR_clear_error();
3875     if (keyfile == Py_None)
3876         keyfile = NULL;
3877     if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3878         PyErr_SetString(PyExc_TypeError,
3879                         "certfile should be a valid filesystem path");
3880         return NULL;
3881     }
3882     if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3883         PyErr_SetString(PyExc_TypeError,
3884                         "keyfile should be a valid filesystem path");
3885         goto error;
3886     }
3887     if (password && password != Py_None) {
3888         if (PyCallable_Check(password)) {
3889             pw_info.callable = password;
3890         } else if (!_pwinfo_set(&pw_info, password,
3891                                 "password should be a string or callable")) {
3892             goto error;
3893         }
3894         SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3895         SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3896     }
3897     PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
3898     r = SSL_CTX_use_certificate_chain_file(self->ctx,
3899         PyBytes_AS_STRING(certfile_bytes));
3900     PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3901     if (r != 1) {
3902         if (pw_info.error) {
3903             ERR_clear_error();
3904             /* the password callback has already set the error information */
3905         }
3906         else if (errno != 0) {
3907             ERR_clear_error();
3908             PyErr_SetFromErrno(PyExc_OSError);
3909         }
3910         else {
3911             _setSSLError(NULL, 0, __FILE__, __LINE__);
3912         }
3913         goto error;
3914     }
3915     PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
3916     r = SSL_CTX_use_PrivateKey_file(self->ctx,
3917         PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3918         SSL_FILETYPE_PEM);
3919     PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3920     Py_CLEAR(keyfile_bytes);
3921     Py_CLEAR(certfile_bytes);
3922     if (r != 1) {
3923         if (pw_info.error) {
3924             ERR_clear_error();
3925             /* the password callback has already set the error information */
3926         }
3927         else if (errno != 0) {
3928             ERR_clear_error();
3929             PyErr_SetFromErrno(PyExc_OSError);
3930         }
3931         else {
3932             _setSSLError(NULL, 0, __FILE__, __LINE__);
3933         }
3934         goto error;
3935     }
3936     PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
3937     r = SSL_CTX_check_private_key(self->ctx);
3938     PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3939     if (r != 1) {
3940         _setSSLError(NULL, 0, __FILE__, __LINE__);
3941         goto error;
3942     }
3943     SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3944     SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
3945     PyMem_Free(pw_info.password);
3946     Py_RETURN_NONE;
3947 
3948 error:
3949     SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3950     SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
3951     PyMem_Free(pw_info.password);
3952     Py_XDECREF(keyfile_bytes);
3953     Py_XDECREF(certfile_bytes);
3954     return NULL;
3955 }
3956 
3957 /* internal helper function, returns -1 on error
3958  */
3959 static int
_add_ca_certs(PySSLContext * self,void * data,Py_ssize_t len,int filetype)3960 _add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3961               int filetype)
3962 {
3963     BIO *biobuf = NULL;
3964     X509_STORE *store;
3965     int retval = 0, err, loaded = 0;
3966 
3967     assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3968 
3969     if (len <= 0) {
3970         PyErr_SetString(PyExc_ValueError,
3971                         "Empty certificate data");
3972         return -1;
3973     } else if (len > INT_MAX) {
3974         PyErr_SetString(PyExc_OverflowError,
3975                         "Certificate data is too long.");
3976         return -1;
3977     }
3978 
3979     biobuf = BIO_new_mem_buf(data, (int)len);
3980     if (biobuf == NULL) {
3981         _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3982         return -1;
3983     }
3984 
3985     store = SSL_CTX_get_cert_store(self->ctx);
3986     assert(store != NULL);
3987 
3988     while (1) {
3989         X509 *cert = NULL;
3990         int r;
3991 
3992         if (filetype == SSL_FILETYPE_ASN1) {
3993             cert = d2i_X509_bio(biobuf, NULL);
3994         } else {
3995             cert = PEM_read_bio_X509(biobuf, NULL,
3996                                      SSL_CTX_get_default_passwd_cb(self->ctx),
3997                                      SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3998                                     );
3999         }
4000         if (cert == NULL) {
4001             break;
4002         }
4003         r = X509_STORE_add_cert(store, cert);
4004         X509_free(cert);
4005         if (!r) {
4006             err = ERR_peek_last_error();
4007             if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
4008                 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
4009                 /* cert already in hash table, not an error */
4010                 ERR_clear_error();
4011             } else {
4012                 break;
4013             }
4014         }
4015         loaded++;
4016     }
4017 
4018     err = ERR_peek_last_error();
4019     if ((filetype == SSL_FILETYPE_ASN1) &&
4020             (loaded > 0) &&
4021             (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
4022             (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
4023         /* EOF ASN1 file, not an error */
4024         ERR_clear_error();
4025         retval = 0;
4026     } else if ((filetype == SSL_FILETYPE_PEM) &&
4027                    (loaded > 0) &&
4028                    (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
4029                    (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
4030         /* EOF PEM file, not an error */
4031         ERR_clear_error();
4032         retval = 0;
4033     } else {
4034         _setSSLError(NULL, 0, __FILE__, __LINE__);
4035         retval = -1;
4036     }
4037 
4038     BIO_free(biobuf);
4039     return retval;
4040 }
4041 
4042 
4043 /*[clinic input]
4044 _ssl._SSLContext.load_verify_locations
4045     cafile: object = NULL
4046     capath: object = NULL
4047     cadata: object = NULL
4048 
4049 [clinic start generated code]*/
4050 
4051 static PyObject *
_ssl__SSLContext_load_verify_locations_impl(PySSLContext * self,PyObject * cafile,PyObject * capath,PyObject * cadata)4052 _ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
4053                                             PyObject *cafile,
4054                                             PyObject *capath,
4055                                             PyObject *cadata)
4056 /*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
4057 {
4058     PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
4059     const char *cafile_buf = NULL, *capath_buf = NULL;
4060     int r = 0, ok = 1;
4061 
4062     errno = 0;
4063     if (cafile == Py_None)
4064         cafile = NULL;
4065     if (capath == Py_None)
4066         capath = NULL;
4067     if (cadata == Py_None)
4068         cadata = NULL;
4069 
4070     if (cafile == NULL && capath == NULL && cadata == NULL) {
4071         PyErr_SetString(PyExc_TypeError,
4072                         "cafile, capath and cadata cannot be all omitted");
4073         goto error;
4074     }
4075     if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
4076         PyErr_SetString(PyExc_TypeError,
4077                         "cafile should be a valid filesystem path");
4078         goto error;
4079     }
4080     if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
4081         PyErr_SetString(PyExc_TypeError,
4082                         "capath should be a valid filesystem path");
4083         goto error;
4084     }
4085 
4086     /* validata cadata type and load cadata */
4087     if (cadata) {
4088         Py_buffer buf;
4089         PyObject *cadata_ascii = NULL;
4090 
4091         if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
4092             if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4093                 PyBuffer_Release(&buf);
4094                 PyErr_SetString(PyExc_TypeError,
4095                                 "cadata should be a contiguous buffer with "
4096                                 "a single dimension");
4097                 goto error;
4098             }
4099             r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4100             PyBuffer_Release(&buf);
4101             if (r == -1) {
4102                 goto error;
4103             }
4104         } else {
4105             PyErr_Clear();
4106             cadata_ascii = PyUnicode_AsASCIIString(cadata);
4107             if (cadata_ascii == NULL) {
4108                 PyErr_SetString(PyExc_TypeError,
4109                                 "cadata should be an ASCII string or a "
4110                                 "bytes-like object");
4111                 goto error;
4112             }
4113             r = _add_ca_certs(self,
4114                               PyBytes_AS_STRING(cadata_ascii),
4115                               PyBytes_GET_SIZE(cadata_ascii),
4116                               SSL_FILETYPE_PEM);
4117             Py_DECREF(cadata_ascii);
4118             if (r == -1) {
4119                 goto error;
4120             }
4121         }
4122     }
4123 
4124     /* load cafile or capath */
4125     if (cafile || capath) {
4126         if (cafile)
4127             cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4128         if (capath)
4129             capath_buf = PyBytes_AS_STRING(capath_bytes);
4130         PySSL_BEGIN_ALLOW_THREADS
4131         r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4132         PySSL_END_ALLOW_THREADS
4133         if (r != 1) {
4134             ok = 0;
4135             if (errno != 0) {
4136                 ERR_clear_error();
4137                 PyErr_SetFromErrno(PyExc_OSError);
4138             }
4139             else {
4140                 _setSSLError(NULL, 0, __FILE__, __LINE__);
4141             }
4142             goto error;
4143         }
4144     }
4145     goto end;
4146 
4147   error:
4148     ok = 0;
4149   end:
4150     Py_XDECREF(cafile_bytes);
4151     Py_XDECREF(capath_bytes);
4152     if (ok) {
4153         Py_RETURN_NONE;
4154     } else {
4155         return NULL;
4156     }
4157 }
4158 
4159 /*[clinic input]
4160 _ssl._SSLContext.load_dh_params
4161     path as filepath: object
4162     /
4163 
4164 [clinic start generated code]*/
4165 
4166 static PyObject *
_ssl__SSLContext_load_dh_params(PySSLContext * self,PyObject * filepath)4167 _ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4168 /*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
4169 {
4170     FILE *f;
4171     DH *dh;
4172 
4173     f = _Py_fopen_obj(filepath, "rb");
4174     if (f == NULL)
4175         return NULL;
4176 
4177     errno = 0;
4178     PySSL_BEGIN_ALLOW_THREADS
4179     dh = PEM_read_DHparams(f, NULL, NULL, NULL);
4180     fclose(f);
4181     PySSL_END_ALLOW_THREADS
4182     if (dh == NULL) {
4183         if (errno != 0) {
4184             ERR_clear_error();
4185             PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4186         }
4187         else {
4188             _setSSLError(NULL, 0, __FILE__, __LINE__);
4189         }
4190         return NULL;
4191     }
4192     if (!SSL_CTX_set_tmp_dh(self->ctx, dh)) {
4193         DH_free(dh);
4194         return _setSSLError(NULL, 0, __FILE__, __LINE__);
4195     }
4196     DH_free(dh);
4197     Py_RETURN_NONE;
4198 }
4199 
4200 /*[clinic input]
4201 _ssl._SSLContext._wrap_socket
4202     sock: object(subclass_of="PySocketModule.Sock_Type")
4203     server_side: int
4204     server_hostname as hostname_obj: object = None
4205     *
4206     owner: object = None
4207     session: object = None
4208 
4209 [clinic start generated code]*/
4210 
4211 static PyObject *
_ssl__SSLContext__wrap_socket_impl(PySSLContext * self,PyObject * sock,int server_side,PyObject * hostname_obj,PyObject * owner,PyObject * session)4212 _ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
4213                                    int server_side, PyObject *hostname_obj,
4214                                    PyObject *owner, PyObject *session)
4215 /*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
4216 {
4217     char *hostname = NULL;
4218     PyObject *res;
4219 
4220     /* server_hostname is either None (or absent), or to be encoded
4221        as IDN A-label (ASCII str) without NULL bytes. */
4222     if (hostname_obj != Py_None) {
4223         if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
4224             return NULL;
4225     }
4226 
4227     res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4228                                       server_side, hostname,
4229                                       owner, session,
4230                                       NULL, NULL);
4231     if (hostname != NULL)
4232         PyMem_Free(hostname);
4233     return res;
4234 }
4235 
4236 /*[clinic input]
4237 _ssl._SSLContext._wrap_bio
4238     incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4239     outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4240     server_side: int
4241     server_hostname as hostname_obj: object = None
4242     *
4243     owner: object = None
4244     session: object = None
4245 
4246 [clinic start generated code]*/
4247 
4248 static PyObject *
_ssl__SSLContext__wrap_bio_impl(PySSLContext * self,PySSLMemoryBIO * incoming,PySSLMemoryBIO * outgoing,int server_side,PyObject * hostname_obj,PyObject * owner,PyObject * session)4249 _ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4250                                 PySSLMemoryBIO *outgoing, int server_side,
4251                                 PyObject *hostname_obj, PyObject *owner,
4252                                 PyObject *session)
4253 /*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
4254 {
4255     char *hostname = NULL;
4256     PyObject *res;
4257 
4258     /* server_hostname is either None (or absent), or to be encoded
4259        as IDN A-label (ASCII str) without NULL bytes. */
4260     if (hostname_obj != Py_None) {
4261         if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
4262             return NULL;
4263     }
4264 
4265     res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
4266                                       owner, session,
4267                                       incoming, outgoing);
4268 
4269     PyMem_Free(hostname);
4270     return res;
4271 }
4272 
4273 /*[clinic input]
4274 _ssl._SSLContext.session_stats
4275 [clinic start generated code]*/
4276 
4277 static PyObject *
_ssl__SSLContext_session_stats_impl(PySSLContext * self)4278 _ssl__SSLContext_session_stats_impl(PySSLContext *self)
4279 /*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
4280 {
4281     int r;
4282     PyObject *value, *stats = PyDict_New();
4283     if (!stats)
4284         return NULL;
4285 
4286 #define ADD_STATS(SSL_NAME, KEY_NAME) \
4287     value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4288     if (value == NULL) \
4289         goto error; \
4290     r = PyDict_SetItemString(stats, KEY_NAME, value); \
4291     Py_DECREF(value); \
4292     if (r < 0) \
4293         goto error;
4294 
4295     ADD_STATS(number, "number");
4296     ADD_STATS(connect, "connect");
4297     ADD_STATS(connect_good, "connect_good");
4298     ADD_STATS(connect_renegotiate, "connect_renegotiate");
4299     ADD_STATS(accept, "accept");
4300     ADD_STATS(accept_good, "accept_good");
4301     ADD_STATS(accept_renegotiate, "accept_renegotiate");
4302     ADD_STATS(accept, "accept");
4303     ADD_STATS(hits, "hits");
4304     ADD_STATS(misses, "misses");
4305     ADD_STATS(timeouts, "timeouts");
4306     ADD_STATS(cache_full, "cache_full");
4307 
4308 #undef ADD_STATS
4309 
4310     return stats;
4311 
4312 error:
4313     Py_DECREF(stats);
4314     return NULL;
4315 }
4316 
4317 /*[clinic input]
4318 _ssl._SSLContext.set_default_verify_paths
4319 [clinic start generated code]*/
4320 
4321 static PyObject *
_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext * self)4322 _ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4323 /*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
4324 {
4325     if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4326         _setSSLError(NULL, 0, __FILE__, __LINE__);
4327         return NULL;
4328     }
4329     Py_RETURN_NONE;
4330 }
4331 
4332 #ifndef OPENSSL_NO_ECDH
4333 /*[clinic input]
4334 _ssl._SSLContext.set_ecdh_curve
4335     name: object
4336     /
4337 
4338 [clinic start generated code]*/
4339 
4340 static PyObject *
_ssl__SSLContext_set_ecdh_curve(PySSLContext * self,PyObject * name)4341 _ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4342 /*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
4343 {
4344     PyObject *name_bytes;
4345     int nid;
4346     EC_KEY *key;
4347 
4348     if (!PyUnicode_FSConverter(name, &name_bytes))
4349         return NULL;
4350     assert(PyBytes_Check(name_bytes));
4351     nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4352     Py_DECREF(name_bytes);
4353     if (nid == 0) {
4354         PyErr_Format(PyExc_ValueError,
4355                      "unknown elliptic curve name %R", name);
4356         return NULL;
4357     }
4358     key = EC_KEY_new_by_curve_name(nid);
4359     if (key == NULL) {
4360         _setSSLError(NULL, 0, __FILE__, __LINE__);
4361         return NULL;
4362     }
4363     SSL_CTX_set_tmp_ecdh(self->ctx, key);
4364     EC_KEY_free(key);
4365     Py_RETURN_NONE;
4366 }
4367 #endif
4368 
4369 #if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
4370 static int
_servername_callback(SSL * s,int * al,void * args)4371 _servername_callback(SSL *s, int *al, void *args)
4372 {
4373     int ret;
4374     PySSLContext *ssl_ctx = (PySSLContext *) args;
4375     PySSLSocket *ssl;
4376     PyObject *result;
4377     /* The high-level ssl.SSLSocket object */
4378     PyObject *ssl_socket;
4379     const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
4380     PyGILState_STATE gstate = PyGILState_Ensure();
4381 
4382     if (ssl_ctx->set_sni_cb == NULL) {
4383         /* remove race condition in this the call back while if removing the
4384          * callback is in progress */
4385         PyGILState_Release(gstate);
4386         return SSL_TLSEXT_ERR_OK;
4387     }
4388 
4389     ssl = SSL_get_app_data(s);
4390     assert(PySSLSocket_Check(ssl));
4391 
4392     /* The servername callback expects an argument that represents the current
4393      * SSL connection and that has a .context attribute that can be changed to
4394      * identify the requested hostname. Since the official API is the Python
4395      * level API we want to pass the callback a Python level object rather than
4396      * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4397      * SSLObject) that will be passed. Otherwise if there's a socket then that
4398      * will be passed. If both do not exist only then the C-level object is
4399      * passed. */
4400     if (ssl->owner)
4401         ssl_socket = PyWeakref_GetObject(ssl->owner);
4402     else if (ssl->Socket)
4403         ssl_socket = PyWeakref_GetObject(ssl->Socket);
4404     else
4405         ssl_socket = (PyObject *) ssl;
4406 
4407     Py_INCREF(ssl_socket);
4408     if (ssl_socket == Py_None)
4409         goto error;
4410 
4411     if (servername == NULL) {
4412         result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
4413                                               Py_None, ssl_ctx, NULL);
4414     }
4415     else {
4416         PyObject *servername_bytes;
4417         PyObject *servername_str;
4418 
4419         servername_bytes = PyBytes_FromString(servername);
4420         if (servername_bytes == NULL) {
4421             PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4422             goto error;
4423         }
4424         /* server_hostname was encoded to an A-label by our caller; put it
4425          * back into a str object, but still as an A-label (bpo-28414)
4426          */
4427         servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4428         Py_DECREF(servername_bytes);
4429         if (servername_str == NULL) {
4430             PyErr_WriteUnraisable(servername_bytes);
4431             goto error;
4432         }
4433         result = PyObject_CallFunctionObjArgs(
4434             ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4435             ssl_ctx, NULL);
4436         Py_DECREF(servername_str);
4437     }
4438     Py_DECREF(ssl_socket);
4439 
4440     if (result == NULL) {
4441         PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
4442         *al = SSL_AD_HANDSHAKE_FAILURE;
4443         ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4444     }
4445     else {
4446         /* Result may be None, a SSLContext or an integer
4447          * None and SSLContext are OK, integer or other values are an error.
4448          */
4449         if (result == Py_None) {
4450             ret = SSL_TLSEXT_ERR_OK;
4451         } else {
4452             *al = (int) PyLong_AsLong(result);
4453             if (PyErr_Occurred()) {
4454                 PyErr_WriteUnraisable(result);
4455                 *al = SSL_AD_INTERNAL_ERROR;
4456             }
4457             ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4458         }
4459         Py_DECREF(result);
4460     }
4461 
4462     PyGILState_Release(gstate);
4463     return ret;
4464 
4465 error:
4466     Py_DECREF(ssl_socket);
4467     *al = SSL_AD_INTERNAL_ERROR;
4468     ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4469     PyGILState_Release(gstate);
4470     return ret;
4471 }
4472 #endif
4473 
4474 static PyObject *
get_sni_callback(PySSLContext * self,void * c)4475 get_sni_callback(PySSLContext *self, void *c)
4476 {
4477     PyObject *cb = self->set_sni_cb;
4478     if (cb == NULL) {
4479         Py_RETURN_NONE;
4480     }
4481     Py_INCREF(cb);
4482     return cb;
4483 }
4484 
4485 static int
set_sni_callback(PySSLContext * self,PyObject * arg,void * c)4486 set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4487 {
4488     if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4489         PyErr_SetString(PyExc_ValueError,
4490                         "sni_callback cannot be set on TLS_CLIENT context");
4491         return -1;
4492     }
4493 #if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
4494     Py_CLEAR(self->set_sni_cb);
4495     if (arg == Py_None) {
4496         SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4497     }
4498     else {
4499         if (!PyCallable_Check(arg)) {
4500             SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4501             PyErr_SetString(PyExc_TypeError,
4502                             "not a callable object");
4503             return -1;
4504         }
4505         Py_INCREF(arg);
4506         self->set_sni_cb = arg;
4507         SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4508         SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4509     }
4510     return 0;
4511 #else
4512     PyErr_SetString(PyExc_NotImplementedError,
4513                     "The TLS extension servername callback, "
4514                     "SSL_CTX_set_tlsext_servername_callback, "
4515                     "is not in the current OpenSSL library.");
4516     return -1;
4517 #endif
4518 }
4519 
4520 PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4521 "Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4522 \n\
4523 If the argument is None then the callback is disabled. The method is called\n\
4524 with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4525 See RFC 6066 for details of the SNI extension.");
4526 
4527 /*[clinic input]
4528 _ssl._SSLContext.cert_store_stats
4529 
4530 Returns quantities of loaded X.509 certificates.
4531 
4532 X.509 certificates with a CA extension and certificate revocation lists
4533 inside the context's cert store.
4534 
4535 NOTE: Certificates in a capath directory aren't loaded unless they have
4536 been used at least once.
4537 [clinic start generated code]*/
4538 
4539 static PyObject *
_ssl__SSLContext_cert_store_stats_impl(PySSLContext * self)4540 _ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4541 /*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
4542 {
4543     X509_STORE *store;
4544     STACK_OF(X509_OBJECT) *objs;
4545     X509_OBJECT *obj;
4546     int x509 = 0, crl = 0, ca = 0, i;
4547 
4548     store = SSL_CTX_get_cert_store(self->ctx);
4549     objs = X509_STORE_get0_objects(store);
4550     for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4551         obj = sk_X509_OBJECT_value(objs, i);
4552         switch (X509_OBJECT_get_type(obj)) {
4553             case X509_LU_X509:
4554                 x509++;
4555                 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
4556                     ca++;
4557                 }
4558                 break;
4559             case X509_LU_CRL:
4560                 crl++;
4561                 break;
4562             default:
4563                 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4564                  * As far as I can tell they are internal states and never
4565                  * stored in a cert store */
4566                 break;
4567         }
4568     }
4569     return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4570         "x509_ca", ca);
4571 }
4572 
4573 /*[clinic input]
4574 _ssl._SSLContext.get_ca_certs
4575     binary_form: bool = False
4576 
4577 Returns a list of dicts with information of loaded CA certs.
4578 
4579 If the optional argument is True, returns a DER-encoded copy of the CA
4580 certificate.
4581 
4582 NOTE: Certificates in a capath directory aren't loaded unless they have
4583 been used at least once.
4584 [clinic start generated code]*/
4585 
4586 static PyObject *
_ssl__SSLContext_get_ca_certs_impl(PySSLContext * self,int binary_form)4587 _ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4588 /*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
4589 {
4590     X509_STORE *store;
4591     STACK_OF(X509_OBJECT) *objs;
4592     PyObject *ci = NULL, *rlist = NULL;
4593     int i;
4594 
4595     if ((rlist = PyList_New(0)) == NULL) {
4596         return NULL;
4597     }
4598 
4599     store = SSL_CTX_get_cert_store(self->ctx);
4600     objs = X509_STORE_get0_objects(store);
4601     for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4602         X509_OBJECT *obj;
4603         X509 *cert;
4604 
4605         obj = sk_X509_OBJECT_value(objs, i);
4606         if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
4607             /* not a x509 cert */
4608             continue;
4609         }
4610         /* CA for any purpose */
4611         cert = X509_OBJECT_get0_X509(obj);
4612         if (!X509_check_ca(cert)) {
4613             continue;
4614         }
4615         if (binary_form) {
4616             ci = _certificate_to_der(cert);
4617         } else {
4618             ci = _decode_certificate(cert);
4619         }
4620         if (ci == NULL) {
4621             goto error;
4622         }
4623         if (PyList_Append(rlist, ci) == -1) {
4624             goto error;
4625         }
4626         Py_CLEAR(ci);
4627     }
4628     return rlist;
4629 
4630   error:
4631     Py_XDECREF(ci);
4632     Py_XDECREF(rlist);
4633     return NULL;
4634 }
4635 
4636 
4637 static PyGetSetDef context_getsetlist[] = {
4638     {"check_hostname", (getter) get_check_hostname,
4639                        (setter) set_check_hostname, NULL},
4640     {"_host_flags", (getter) get_host_flags,
4641                     (setter) set_host_flags, NULL},
4642 #if SSL_CTRL_GET_MAX_PROTO_VERSION
4643     {"minimum_version", (getter) get_minimum_version,
4644                         (setter) set_minimum_version, NULL},
4645     {"maximum_version", (getter) get_maximum_version,
4646                         (setter) set_maximum_version, NULL},
4647 #endif
4648     {"sni_callback", (getter) get_sni_callback,
4649                      (setter) set_sni_callback, PySSLContext_sni_callback_doc},
4650     {"options", (getter) get_options,
4651                 (setter) set_options, NULL},
4652     {"post_handshake_auth", (getter) get_post_handshake_auth,
4653 #ifdef TLS1_3_VERSION
4654                             (setter) set_post_handshake_auth,
4655 #else
4656                             NULL,
4657 #endif
4658                             NULL},
4659     {"protocol", (getter) get_protocol,
4660                  NULL, NULL},
4661     {"verify_flags", (getter) get_verify_flags,
4662                      (setter) set_verify_flags, NULL},
4663     {"verify_mode", (getter) get_verify_mode,
4664                     (setter) set_verify_mode, NULL},
4665     {NULL},            /* sentinel */
4666 };
4667 
4668 static struct PyMethodDef context_methods[] = {
4669     _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4670     _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4671     _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4672     _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4673     _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4674     _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4675     _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4676     _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4677     _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4678     _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4679     _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
4680     _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4681     _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
4682     _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
4683     {NULL, NULL}        /* sentinel */
4684 };
4685 
4686 static PyTypeObject PySSLContext_Type = {
4687     PyVarObject_HEAD_INIT(NULL, 0)
4688     "_ssl._SSLContext",                        /*tp_name*/
4689     sizeof(PySSLContext),                      /*tp_basicsize*/
4690     0,                                         /*tp_itemsize*/
4691     (destructor)context_dealloc,               /*tp_dealloc*/
4692     0,                                         /*tp_print*/
4693     0,                                         /*tp_getattr*/
4694     0,                                         /*tp_setattr*/
4695     0,                                         /*tp_reserved*/
4696     0,                                         /*tp_repr*/
4697     0,                                         /*tp_as_number*/
4698     0,                                         /*tp_as_sequence*/
4699     0,                                         /*tp_as_mapping*/
4700     0,                                         /*tp_hash*/
4701     0,                                         /*tp_call*/
4702     0,                                         /*tp_str*/
4703     0,                                         /*tp_getattro*/
4704     0,                                         /*tp_setattro*/
4705     0,                                         /*tp_as_buffer*/
4706     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
4707     0,                                         /*tp_doc*/
4708     (traverseproc) context_traverse,           /*tp_traverse*/
4709     (inquiry) context_clear,                   /*tp_clear*/
4710     0,                                         /*tp_richcompare*/
4711     0,                                         /*tp_weaklistoffset*/
4712     0,                                         /*tp_iter*/
4713     0,                                         /*tp_iternext*/
4714     context_methods,                           /*tp_methods*/
4715     0,                                         /*tp_members*/
4716     context_getsetlist,                        /*tp_getset*/
4717     0,                                         /*tp_base*/
4718     0,                                         /*tp_dict*/
4719     0,                                         /*tp_descr_get*/
4720     0,                                         /*tp_descr_set*/
4721     0,                                         /*tp_dictoffset*/
4722     0,                                         /*tp_init*/
4723     0,                                         /*tp_alloc*/
4724     _ssl__SSLContext,                          /*tp_new*/
4725 };
4726 
4727 
4728 /*
4729  * MemoryBIO objects
4730  */
4731 
4732 /*[clinic input]
4733 @classmethod
4734 _ssl.MemoryBIO.__new__
4735 
4736 [clinic start generated code]*/
4737 
4738 static PyObject *
_ssl_MemoryBIO_impl(PyTypeObject * type)4739 _ssl_MemoryBIO_impl(PyTypeObject *type)
4740 /*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
4741 {
4742     BIO *bio;
4743     PySSLMemoryBIO *self;
4744 
4745     bio = BIO_new(BIO_s_mem());
4746     if (bio == NULL) {
4747         PyErr_SetString(PySSLErrorObject,
4748                         "failed to allocate BIO");
4749         return NULL;
4750     }
4751     /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4752      * just that no data is currently available. The SSL routines should retry
4753      * the read, which we can achieve by calling BIO_set_retry_read(). */
4754     BIO_set_retry_read(bio);
4755     BIO_set_mem_eof_return(bio, -1);
4756 
4757     assert(type != NULL && type->tp_alloc != NULL);
4758     self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4759     if (self == NULL) {
4760         BIO_free(bio);
4761         return NULL;
4762     }
4763     self->bio = bio;
4764     self->eof_written = 0;
4765 
4766     return (PyObject *) self;
4767 }
4768 
4769 static void
memory_bio_dealloc(PySSLMemoryBIO * self)4770 memory_bio_dealloc(PySSLMemoryBIO *self)
4771 {
4772     BIO_free(self->bio);
4773     Py_TYPE(self)->tp_free(self);
4774 }
4775 
4776 static PyObject *
memory_bio_get_pending(PySSLMemoryBIO * self,void * c)4777 memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4778 {
4779     return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
4780 }
4781 
4782 PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4783 "The number of bytes pending in the memory BIO.");
4784 
4785 static PyObject *
memory_bio_get_eof(PySSLMemoryBIO * self,void * c)4786 memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4787 {
4788     return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4789                            && self->eof_written);
4790 }
4791 
4792 PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4793 "Whether the memory BIO is at EOF.");
4794 
4795 /*[clinic input]
4796 _ssl.MemoryBIO.read
4797     size as len: int = -1
4798     /
4799 
4800 Read up to size bytes from the memory BIO.
4801 
4802 If size is not specified, read the entire buffer.
4803 If the return value is an empty bytes instance, this means either
4804 EOF or that no data is available. Use the "eof" property to
4805 distinguish between the two.
4806 [clinic start generated code]*/
4807 
4808 static PyObject *
_ssl_MemoryBIO_read_impl(PySSLMemoryBIO * self,int len)4809 _ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4810 /*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4811 {
4812     int avail, nbytes;
4813     PyObject *result;
4814 
4815     avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
4816     if ((len < 0) || (len > avail))
4817         len = avail;
4818 
4819     result = PyBytes_FromStringAndSize(NULL, len);
4820     if ((result == NULL) || (len == 0))
4821         return result;
4822 
4823     nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4824     if (nbytes < 0) {
4825         Py_DECREF(result);
4826         _setSSLError(NULL, 0, __FILE__, __LINE__);
4827         return NULL;
4828     }
4829 
4830     /* There should never be any short reads but check anyway. */
4831     if (nbytes < len) {
4832         _PyBytes_Resize(&result, nbytes);
4833     }
4834 
4835     return result;
4836 }
4837 
4838 /*[clinic input]
4839 _ssl.MemoryBIO.write
4840     b: Py_buffer
4841     /
4842 
4843 Writes the bytes b into the memory BIO.
4844 
4845 Returns the number of bytes written.
4846 [clinic start generated code]*/
4847 
4848 static PyObject *
_ssl_MemoryBIO_write_impl(PySSLMemoryBIO * self,Py_buffer * b)4849 _ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4850 /*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
4851 {
4852     int nbytes;
4853 
4854     if (b->len > INT_MAX) {
4855         PyErr_Format(PyExc_OverflowError,
4856                      "string longer than %d bytes", INT_MAX);
4857         return NULL;
4858     }
4859 
4860     if (self->eof_written) {
4861         PyErr_SetString(PySSLErrorObject,
4862                         "cannot write() after write_eof()");
4863         return NULL;
4864     }
4865 
4866     nbytes = BIO_write(self->bio, b->buf, (int)b->len);
4867     if (nbytes < 0) {
4868         _setSSLError(NULL, 0, __FILE__, __LINE__);
4869         return NULL;
4870     }
4871 
4872     return PyLong_FromLong(nbytes);
4873 }
4874 
4875 /*[clinic input]
4876 _ssl.MemoryBIO.write_eof
4877 
4878 Write an EOF marker to the memory BIO.
4879 
4880 When all data has been read, the "eof" property will be True.
4881 [clinic start generated code]*/
4882 
4883 static PyObject *
_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO * self)4884 _ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4885 /*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
4886 {
4887     self->eof_written = 1;
4888     /* After an EOF is written, a zero return from read() should be a real EOF
4889      * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4890     BIO_clear_retry_flags(self->bio);
4891     BIO_set_mem_eof_return(self->bio, 0);
4892 
4893     Py_RETURN_NONE;
4894 }
4895 
4896 static PyGetSetDef memory_bio_getsetlist[] = {
4897     {"pending", (getter) memory_bio_get_pending, NULL,
4898                 PySSL_memory_bio_pending_doc},
4899     {"eof", (getter) memory_bio_get_eof, NULL,
4900             PySSL_memory_bio_eof_doc},
4901     {NULL},            /* sentinel */
4902 };
4903 
4904 static struct PyMethodDef memory_bio_methods[] = {
4905     _SSL_MEMORYBIO_READ_METHODDEF
4906     _SSL_MEMORYBIO_WRITE_METHODDEF
4907     _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
4908     {NULL, NULL}        /* sentinel */
4909 };
4910 
4911 static PyTypeObject PySSLMemoryBIO_Type = {
4912     PyVarObject_HEAD_INIT(NULL, 0)
4913     "_ssl.MemoryBIO",                         /*tp_name*/
4914     sizeof(PySSLMemoryBIO),                    /*tp_basicsize*/
4915     0,                                         /*tp_itemsize*/
4916     (destructor)memory_bio_dealloc,            /*tp_dealloc*/
4917     0,                                         /*tp_print*/
4918     0,                                         /*tp_getattr*/
4919     0,                                         /*tp_setattr*/
4920     0,                                         /*tp_reserved*/
4921     0,                                         /*tp_repr*/
4922     0,                                         /*tp_as_number*/
4923     0,                                         /*tp_as_sequence*/
4924     0,                                         /*tp_as_mapping*/
4925     0,                                         /*tp_hash*/
4926     0,                                         /*tp_call*/
4927     0,                                         /*tp_str*/
4928     0,                                         /*tp_getattro*/
4929     0,                                         /*tp_setattro*/
4930     0,                                         /*tp_as_buffer*/
4931     Py_TPFLAGS_DEFAULT,                        /*tp_flags*/
4932     0,                                         /*tp_doc*/
4933     0,                                         /*tp_traverse*/
4934     0,                                         /*tp_clear*/
4935     0,                                         /*tp_richcompare*/
4936     0,                                         /*tp_weaklistoffset*/
4937     0,                                         /*tp_iter*/
4938     0,                                         /*tp_iternext*/
4939     memory_bio_methods,                        /*tp_methods*/
4940     0,                                         /*tp_members*/
4941     memory_bio_getsetlist,                     /*tp_getset*/
4942     0,                                         /*tp_base*/
4943     0,                                         /*tp_dict*/
4944     0,                                         /*tp_descr_get*/
4945     0,                                         /*tp_descr_set*/
4946     0,                                         /*tp_dictoffset*/
4947     0,                                         /*tp_init*/
4948     0,                                         /*tp_alloc*/
4949     _ssl_MemoryBIO,                            /*tp_new*/
4950 };
4951 
4952 
4953 /*
4954  * SSL Session object
4955  */
4956 
4957 static void
PySSLSession_dealloc(PySSLSession * self)4958 PySSLSession_dealloc(PySSLSession *self)
4959 {
4960     /* bpo-31095: UnTrack is needed before calling any callbacks */
4961     PyObject_GC_UnTrack(self);
4962     Py_XDECREF(self->ctx);
4963     if (self->session != NULL) {
4964         SSL_SESSION_free(self->session);
4965     }
4966     PyObject_GC_Del(self);
4967 }
4968 
4969 static PyObject *
PySSLSession_richcompare(PyObject * left,PyObject * right,int op)4970 PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4971 {
4972     int result;
4973 
4974     if (left == NULL || right == NULL) {
4975         PyErr_BadInternalCall();
4976         return NULL;
4977     }
4978 
4979     if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4980         Py_RETURN_NOTIMPLEMENTED;
4981     }
4982 
4983     if (left == right) {
4984         result = 0;
4985     } else {
4986         const unsigned char *left_id, *right_id;
4987         unsigned int left_len, right_len;
4988         left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4989                                      &left_len);
4990         right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4991                                       &right_len);
4992         if (left_len == right_len) {
4993             result = memcmp(left_id, right_id, left_len);
4994         } else {
4995             result = 1;
4996         }
4997     }
4998 
4999     switch (op) {
5000       case Py_EQ:
5001         if (result == 0) {
5002             Py_RETURN_TRUE;
5003         } else {
5004             Py_RETURN_FALSE;
5005         }
5006         break;
5007       case Py_NE:
5008         if (result != 0) {
5009             Py_RETURN_TRUE;
5010         } else {
5011             Py_RETURN_FALSE;
5012         }
5013         break;
5014       case Py_LT:
5015       case Py_LE:
5016       case Py_GT:
5017       case Py_GE:
5018         Py_RETURN_NOTIMPLEMENTED;
5019         break;
5020       default:
5021         PyErr_BadArgument();
5022         return NULL;
5023     }
5024 }
5025 
5026 static int
PySSLSession_traverse(PySSLSession * self,visitproc visit,void * arg)5027 PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
5028 {
5029     Py_VISIT(self->ctx);
5030     return 0;
5031 }
5032 
5033 static int
PySSLSession_clear(PySSLSession * self)5034 PySSLSession_clear(PySSLSession *self)
5035 {
5036     Py_CLEAR(self->ctx);
5037     return 0;
5038 }
5039 
5040 
5041 static PyObject *
PySSLSession_get_time(PySSLSession * self,void * closure)5042 PySSLSession_get_time(PySSLSession *self, void *closure) {
5043     return PyLong_FromLong(SSL_SESSION_get_time(self->session));
5044 }
5045 
5046 PyDoc_STRVAR(PySSLSession_get_time_doc,
5047 "Session creation time (seconds since epoch).");
5048 
5049 
5050 static PyObject *
PySSLSession_get_timeout(PySSLSession * self,void * closure)5051 PySSLSession_get_timeout(PySSLSession *self, void *closure) {
5052     return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
5053 }
5054 
5055 PyDoc_STRVAR(PySSLSession_get_timeout_doc,
5056 "Session timeout (delta in seconds).");
5057 
5058 
5059 static PyObject *
PySSLSession_get_ticket_lifetime_hint(PySSLSession * self,void * closure)5060 PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
5061     unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
5062     return PyLong_FromUnsignedLong(hint);
5063 }
5064 
5065 PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
5066 "Ticket life time hint.");
5067 
5068 
5069 static PyObject *
PySSLSession_get_session_id(PySSLSession * self,void * closure)5070 PySSLSession_get_session_id(PySSLSession *self, void *closure) {
5071     const unsigned char *id;
5072     unsigned int len;
5073     id = SSL_SESSION_get_id(self->session, &len);
5074     return PyBytes_FromStringAndSize((const char *)id, len);
5075 }
5076 
5077 PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5078 "Session id");
5079 
5080 
5081 static PyObject *
PySSLSession_get_has_ticket(PySSLSession * self,void * closure)5082 PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5083     if (SSL_SESSION_has_ticket(self->session)) {
5084         Py_RETURN_TRUE;
5085     } else {
5086         Py_RETURN_FALSE;
5087     }
5088 }
5089 
5090 PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5091 "Does the session contain a ticket?");
5092 
5093 
5094 static PyGetSetDef PySSLSession_getsetlist[] = {
5095     {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5096               PySSLSession_get_has_ticket_doc},
5097     {"id",   (getter) PySSLSession_get_session_id, NULL,
5098               PySSLSession_get_session_id_doc},
5099     {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5100               NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5101     {"time", (getter) PySSLSession_get_time, NULL,
5102               PySSLSession_get_time_doc},
5103     {"timeout", (getter) PySSLSession_get_timeout, NULL,
5104               PySSLSession_get_timeout_doc},
5105     {NULL},            /* sentinel */
5106 };
5107 
5108 static PyTypeObject PySSLSession_Type = {
5109     PyVarObject_HEAD_INIT(NULL, 0)
5110     "_ssl.Session",                            /*tp_name*/
5111     sizeof(PySSLSession),                      /*tp_basicsize*/
5112     0,                                         /*tp_itemsize*/
5113     (destructor)PySSLSession_dealloc,          /*tp_dealloc*/
5114     0,                                         /*tp_print*/
5115     0,                                         /*tp_getattr*/
5116     0,                                         /*tp_setattr*/
5117     0,                                         /*tp_reserved*/
5118     0,                                         /*tp_repr*/
5119     0,                                         /*tp_as_number*/
5120     0,                                         /*tp_as_sequence*/
5121     0,                                         /*tp_as_mapping*/
5122     0,                                         /*tp_hash*/
5123     0,                                         /*tp_call*/
5124     0,                                         /*tp_str*/
5125     0,                                         /*tp_getattro*/
5126     0,                                         /*tp_setattro*/
5127     0,                                         /*tp_as_buffer*/
5128     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,   /*tp_flags*/
5129     0,                                         /*tp_doc*/
5130     (traverseproc)PySSLSession_traverse,       /*tp_traverse*/
5131     (inquiry)PySSLSession_clear,               /*tp_clear*/
5132     PySSLSession_richcompare,                  /*tp_richcompare*/
5133     0,                                         /*tp_weaklistoffset*/
5134     0,                                         /*tp_iter*/
5135     0,                                         /*tp_iternext*/
5136     0,                                         /*tp_methods*/
5137     0,                                         /*tp_members*/
5138     PySSLSession_getsetlist,                   /*tp_getset*/
5139 };
5140 
5141 
5142 /* helper routines for seeding the SSL PRNG */
5143 /*[clinic input]
5144 _ssl.RAND_add
5145     string as view: Py_buffer(accept={str, buffer})
5146     entropy: double
5147     /
5148 
5149 Mix string into the OpenSSL PRNG state.
5150 
5151 entropy (a float) is a lower bound on the entropy contained in
5152 string.  See RFC 4086.
5153 [clinic start generated code]*/
5154 
5155 static PyObject *
_ssl_RAND_add_impl(PyObject * module,Py_buffer * view,double entropy)5156 _ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
5157 /*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
5158 {
5159     const char *buf;
5160     Py_ssize_t len, written;
5161 
5162     buf = (const char *)view->buf;
5163     len = view->len;
5164     do {
5165         written = Py_MIN(len, INT_MAX);
5166         RAND_add(buf, (int)written, entropy);
5167         buf += written;
5168         len -= written;
5169     } while (len);
5170     Py_RETURN_NONE;
5171 }
5172 
5173 static PyObject *
PySSL_RAND(int len,int pseudo)5174 PySSL_RAND(int len, int pseudo)
5175 {
5176     int ok;
5177     PyObject *bytes;
5178     unsigned long err;
5179     const char *errstr;
5180     PyObject *v;
5181 
5182     if (len < 0) {
5183         PyErr_SetString(PyExc_ValueError, "num must be positive");
5184         return NULL;
5185     }
5186 
5187     bytes = PyBytes_FromStringAndSize(NULL, len);
5188     if (bytes == NULL)
5189         return NULL;
5190     if (pseudo) {
5191 #ifdef PY_OPENSSL_1_1_API
5192         ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5193 #else
5194         ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5195 #endif
5196         if (ok == 0 || ok == 1)
5197             return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5198     }
5199     else {
5200         ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5201         if (ok == 1)
5202             return bytes;
5203     }
5204     Py_DECREF(bytes);
5205 
5206     err = ERR_get_error();
5207     errstr = ERR_reason_error_string(err);
5208     v = Py_BuildValue("(ks)", err, errstr);
5209     if (v != NULL) {
5210         PyErr_SetObject(PySSLErrorObject, v);
5211         Py_DECREF(v);
5212     }
5213     return NULL;
5214 }
5215 
5216 /*[clinic input]
5217 _ssl.RAND_bytes
5218     n: int
5219     /
5220 
5221 Generate n cryptographically strong pseudo-random bytes.
5222 [clinic start generated code]*/
5223 
5224 static PyObject *
_ssl_RAND_bytes_impl(PyObject * module,int n)5225 _ssl_RAND_bytes_impl(PyObject *module, int n)
5226 /*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
5227 {
5228     return PySSL_RAND(n, 0);
5229 }
5230 
5231 /*[clinic input]
5232 _ssl.RAND_pseudo_bytes
5233     n: int
5234     /
5235 
5236 Generate n pseudo-random bytes.
5237 
5238 Return a pair (bytes, is_cryptographic).  is_cryptographic is True
5239 if the bytes generated are cryptographically strong.
5240 [clinic start generated code]*/
5241 
5242 static PyObject *
_ssl_RAND_pseudo_bytes_impl(PyObject * module,int n)5243 _ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5244 /*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
5245 {
5246     return PySSL_RAND(n, 1);
5247 }
5248 
5249 /*[clinic input]
5250 _ssl.RAND_status
5251 
5252 Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5253 
5254 It is necessary to seed the PRNG with RAND_add() on some platforms before
5255 using the ssl() function.
5256 [clinic start generated code]*/
5257 
5258 static PyObject *
_ssl_RAND_status_impl(PyObject * module)5259 _ssl_RAND_status_impl(PyObject *module)
5260 /*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
5261 {
5262     return PyLong_FromLong(RAND_status());
5263 }
5264 
5265 #ifndef OPENSSL_NO_EGD
5266 /* LCOV_EXCL_START */
5267 /*[clinic input]
5268 _ssl.RAND_egd
5269     path: object(converter="PyUnicode_FSConverter")
5270     /
5271 
5272 Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5273 
5274 Returns number of bytes read.  Raises SSLError if connection to EGD
5275 fails or if it does not provide enough data to seed PRNG.
5276 [clinic start generated code]*/
5277 
5278 static PyObject *
_ssl_RAND_egd_impl(PyObject * module,PyObject * path)5279 _ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5280 /*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
5281 {
5282     int bytes = RAND_egd(PyBytes_AsString(path));
5283     Py_DECREF(path);
5284     if (bytes == -1) {
5285         PyErr_SetString(PySSLErrorObject,
5286                         "EGD connection failed or EGD did not return "
5287                         "enough data to seed the PRNG");
5288         return NULL;
5289     }
5290     return PyLong_FromLong(bytes);
5291 }
5292 /* LCOV_EXCL_STOP */
5293 #endif /* OPENSSL_NO_EGD */
5294 
5295 
5296 
5297 /*[clinic input]
5298 _ssl.get_default_verify_paths
5299 
5300 Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5301 
5302 The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5303 [clinic start generated code]*/
5304 
5305 static PyObject *
_ssl_get_default_verify_paths_impl(PyObject * module)5306 _ssl_get_default_verify_paths_impl(PyObject *module)
5307 /*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
5308 {
5309     PyObject *ofile_env = NULL;
5310     PyObject *ofile = NULL;
5311     PyObject *odir_env = NULL;
5312     PyObject *odir = NULL;
5313 
5314 #define CONVERT(info, target) { \
5315         const char *tmp = (info); \
5316         target = NULL; \
5317         if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5318         else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5319             target = PyBytes_FromString(tmp); } \
5320         if (!target) goto error; \
5321     }
5322 
5323     CONVERT(X509_get_default_cert_file_env(), ofile_env);
5324     CONVERT(X509_get_default_cert_file(), ofile);
5325     CONVERT(X509_get_default_cert_dir_env(), odir_env);
5326     CONVERT(X509_get_default_cert_dir(), odir);
5327 #undef CONVERT
5328 
5329     return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
5330 
5331   error:
5332     Py_XDECREF(ofile_env);
5333     Py_XDECREF(ofile);
5334     Py_XDECREF(odir_env);
5335     Py_XDECREF(odir);
5336     return NULL;
5337 }
5338 
5339 static PyObject*
asn1obj2py(ASN1_OBJECT * obj)5340 asn1obj2py(ASN1_OBJECT *obj)
5341 {
5342     int nid;
5343     const char *ln, *sn;
5344 
5345     nid = OBJ_obj2nid(obj);
5346     if (nid == NID_undef) {
5347         PyErr_Format(PyExc_ValueError, "Unknown object");
5348         return NULL;
5349     }
5350     sn = OBJ_nid2sn(nid);
5351     ln = OBJ_nid2ln(nid);
5352     return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
5353 }
5354 
5355 /*[clinic input]
5356 _ssl.txt2obj
5357     txt: str
5358     name: bool = False
5359 
5360 Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5361 
5362 By default objects are looked up by OID. With name=True short and
5363 long name are also matched.
5364 [clinic start generated code]*/
5365 
5366 static PyObject *
_ssl_txt2obj_impl(PyObject * module,const char * txt,int name)5367 _ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5368 /*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
5369 {
5370     PyObject *result = NULL;
5371     ASN1_OBJECT *obj;
5372 
5373     obj = OBJ_txt2obj(txt, name ? 0 : 1);
5374     if (obj == NULL) {
5375         PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
5376         return NULL;
5377     }
5378     result = asn1obj2py(obj);
5379     ASN1_OBJECT_free(obj);
5380     return result;
5381 }
5382 
5383 /*[clinic input]
5384 _ssl.nid2obj
5385     nid: int
5386     /
5387 
5388 Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5389 [clinic start generated code]*/
5390 
5391 static PyObject *
_ssl_nid2obj_impl(PyObject * module,int nid)5392 _ssl_nid2obj_impl(PyObject *module, int nid)
5393 /*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
5394 {
5395     PyObject *result = NULL;
5396     ASN1_OBJECT *obj;
5397 
5398     if (nid < NID_undef) {
5399         PyErr_SetString(PyExc_ValueError, "NID must be positive.");
5400         return NULL;
5401     }
5402     obj = OBJ_nid2obj(nid);
5403     if (obj == NULL) {
5404         PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
5405         return NULL;
5406     }
5407     result = asn1obj2py(obj);
5408     ASN1_OBJECT_free(obj);
5409     return result;
5410 }
5411 
5412 #ifdef _MSC_VER
5413 
5414 static PyObject*
certEncodingType(DWORD encodingType)5415 certEncodingType(DWORD encodingType)
5416 {
5417     static PyObject *x509_asn = NULL;
5418     static PyObject *pkcs_7_asn = NULL;
5419 
5420     if (x509_asn == NULL) {
5421         x509_asn = PyUnicode_InternFromString("x509_asn");
5422         if (x509_asn == NULL)
5423             return NULL;
5424     }
5425     if (pkcs_7_asn == NULL) {
5426         pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5427         if (pkcs_7_asn == NULL)
5428             return NULL;
5429     }
5430     switch(encodingType) {
5431     case X509_ASN_ENCODING:
5432         Py_INCREF(x509_asn);
5433         return x509_asn;
5434     case PKCS_7_ASN_ENCODING:
5435         Py_INCREF(pkcs_7_asn);
5436         return pkcs_7_asn;
5437     default:
5438         return PyLong_FromLong(encodingType);
5439     }
5440 }
5441 
5442 static PyObject*
parseKeyUsage(PCCERT_CONTEXT pCertCtx,DWORD flags)5443 parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5444 {
5445     CERT_ENHKEY_USAGE *usage;
5446     DWORD size, error, i;
5447     PyObject *retval;
5448 
5449     if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5450         error = GetLastError();
5451         if (error == CRYPT_E_NOT_FOUND) {
5452             Py_RETURN_TRUE;
5453         }
5454         return PyErr_SetFromWindowsErr(error);
5455     }
5456 
5457     usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5458     if (usage == NULL) {
5459         return PyErr_NoMemory();
5460     }
5461 
5462     /* Now get the actual enhanced usage property */
5463     if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5464         PyMem_Free(usage);
5465         error = GetLastError();
5466         if (error == CRYPT_E_NOT_FOUND) {
5467             Py_RETURN_TRUE;
5468         }
5469         return PyErr_SetFromWindowsErr(error);
5470     }
5471     retval = PyFrozenSet_New(NULL);
5472     if (retval == NULL) {
5473         goto error;
5474     }
5475     for (i = 0; i < usage->cUsageIdentifier; ++i) {
5476         if (usage->rgpszUsageIdentifier[i]) {
5477             PyObject *oid;
5478             int err;
5479             oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5480             if (oid == NULL) {
5481                 Py_CLEAR(retval);
5482                 goto error;
5483             }
5484             err = PySet_Add(retval, oid);
5485             Py_DECREF(oid);
5486             if (err == -1) {
5487                 Py_CLEAR(retval);
5488                 goto error;
5489             }
5490         }
5491     }
5492   error:
5493     PyMem_Free(usage);
5494     return retval;
5495 }
5496 
5497 static HCERTSTORE
ssl_collect_certificates(const char * store_name)5498 ssl_collect_certificates(const char *store_name)
5499 {
5500 /* this function collects the system certificate stores listed in
5501  * system_stores into a collection certificate store for being
5502  * enumerated. The store must be readable to be added to the
5503  * store collection.
5504  */
5505 
5506     HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5507     static DWORD system_stores[] = {
5508         CERT_SYSTEM_STORE_LOCAL_MACHINE,
5509         CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5510         CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5511         CERT_SYSTEM_STORE_CURRENT_USER,
5512         CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5513         CERT_SYSTEM_STORE_SERVICES,
5514         CERT_SYSTEM_STORE_USERS};
5515     size_t i, storesAdded;
5516     BOOL result;
5517 
5518     hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5519                                      (HCRYPTPROV)NULL, 0, NULL);
5520     if (!hCollectionStore) {
5521         return NULL;
5522     }
5523     storesAdded = 0;
5524     for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5525         hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5526                                      (HCRYPTPROV)NULL,
5527                                      CERT_STORE_READONLY_FLAG |
5528                                      system_stores[i], store_name);
5529         if (hSystemStore) {
5530             result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5531                                      CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5532             if (result) {
5533                 ++storesAdded;
5534             }
5535             CertCloseStore(hSystemStore, 0);  /* flag must be 0 */
5536         }
5537     }
5538     if (storesAdded == 0) {
5539         CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5540         return NULL;
5541     }
5542 
5543     return hCollectionStore;
5544 }
5545 
5546 /*[clinic input]
5547 _ssl.enum_certificates
5548     store_name: str
5549 
5550 Retrieve certificates from Windows' cert store.
5551 
5552 store_name may be one of 'CA', 'ROOT' or 'MY'.  The system may provide
5553 more cert storages, too.  The function returns a list of (bytes,
5554 encoding_type, trust) tuples.  The encoding_type flag can be interpreted
5555 with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5556 a set of OIDs or the boolean True.
5557 [clinic start generated code]*/
5558 
5559 static PyObject *
_ssl_enum_certificates_impl(PyObject * module,const char * store_name)5560 _ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5561 /*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
5562 {
5563     HCERTSTORE hCollectionStore = NULL;
5564     PCCERT_CONTEXT pCertCtx = NULL;
5565     PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
5566     PyObject *result = NULL;
5567 
5568     result = PySet_New(NULL);
5569     if (result == NULL) {
5570         return NULL;
5571     }
5572     hCollectionStore = ssl_collect_certificates(store_name);
5573     if (hCollectionStore == NULL) {
5574         Py_DECREF(result);
5575         return PyErr_SetFromWindowsErr(GetLastError());
5576     }
5577 
5578     while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
5579         cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5580                                             pCertCtx->cbCertEncoded);
5581         if (!cert) {
5582             Py_CLEAR(result);
5583             break;
5584         }
5585         if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5586             Py_CLEAR(result);
5587             break;
5588         }
5589         keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5590         if (keyusage == Py_True) {
5591             Py_DECREF(keyusage);
5592             keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
5593         }
5594         if (keyusage == NULL) {
5595             Py_CLEAR(result);
5596             break;
5597         }
5598         if ((tup = PyTuple_New(3)) == NULL) {
5599             Py_CLEAR(result);
5600             break;
5601         }
5602         PyTuple_SET_ITEM(tup, 0, cert);
5603         cert = NULL;
5604         PyTuple_SET_ITEM(tup, 1, enc);
5605         enc = NULL;
5606         PyTuple_SET_ITEM(tup, 2, keyusage);
5607         keyusage = NULL;
5608         if (PySet_Add(result, tup) == -1) {
5609             Py_CLEAR(result);
5610             Py_CLEAR(tup);
5611             break;
5612         }
5613         Py_CLEAR(tup);
5614     }
5615     if (pCertCtx) {
5616         /* loop ended with an error, need to clean up context manually */
5617         CertFreeCertificateContext(pCertCtx);
5618     }
5619 
5620     /* In error cases cert, enc and tup may not be NULL */
5621     Py_XDECREF(cert);
5622     Py_XDECREF(enc);
5623     Py_XDECREF(keyusage);
5624     Py_XDECREF(tup);
5625 
5626     /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5627        associated with the store, in this case our collection store and the
5628        associated system stores. */
5629     if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
5630         /* This error case might shadow another exception.*/
5631         Py_XDECREF(result);
5632         return PyErr_SetFromWindowsErr(GetLastError());
5633     }
5634 
5635     /* convert set to list */
5636     if (result == NULL) {
5637         return NULL;
5638     } else {
5639         PyObject *lst = PySequence_List(result);
5640         Py_DECREF(result);
5641         return lst;
5642     }
5643 }
5644 
5645 /*[clinic input]
5646 _ssl.enum_crls
5647     store_name: str
5648 
5649 Retrieve CRLs from Windows' cert store.
5650 
5651 store_name may be one of 'CA', 'ROOT' or 'MY'.  The system may provide
5652 more cert storages, too.  The function returns a list of (bytes,
5653 encoding_type) tuples.  The encoding_type flag can be interpreted with
5654 X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5655 [clinic start generated code]*/
5656 
5657 static PyObject *
_ssl_enum_crls_impl(PyObject * module,const char * store_name)5658 _ssl_enum_crls_impl(PyObject *module, const char *store_name)
5659 /*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
5660 {
5661     HCERTSTORE hCollectionStore = NULL;
5662     PCCRL_CONTEXT pCrlCtx = NULL;
5663     PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5664     PyObject *result = NULL;
5665 
5666     result = PySet_New(NULL);
5667     if (result == NULL) {
5668         return NULL;
5669     }
5670     hCollectionStore = ssl_collect_certificates(store_name);
5671     if (hCollectionStore == NULL) {
5672         Py_DECREF(result);
5673         return PyErr_SetFromWindowsErr(GetLastError());
5674     }
5675 
5676     while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
5677         crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5678                                             pCrlCtx->cbCrlEncoded);
5679         if (!crl) {
5680             Py_CLEAR(result);
5681             break;
5682         }
5683         if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5684             Py_CLEAR(result);
5685             break;
5686         }
5687         if ((tup = PyTuple_New(2)) == NULL) {
5688             Py_CLEAR(result);
5689             break;
5690         }
5691         PyTuple_SET_ITEM(tup, 0, crl);
5692         crl = NULL;
5693         PyTuple_SET_ITEM(tup, 1, enc);
5694         enc = NULL;
5695 
5696         if (PySet_Add(result, tup) == -1) {
5697             Py_CLEAR(result);
5698             Py_CLEAR(tup);
5699             break;
5700         }
5701         Py_CLEAR(tup);
5702     }
5703     if (pCrlCtx) {
5704         /* loop ended with an error, need to clean up context manually */
5705         CertFreeCRLContext(pCrlCtx);
5706     }
5707 
5708     /* In error cases cert, enc and tup may not be NULL */
5709     Py_XDECREF(crl);
5710     Py_XDECREF(enc);
5711     Py_XDECREF(tup);
5712 
5713     /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5714        associated with the store, in this case our collection store and the
5715        associated system stores. */
5716     if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
5717         /* This error case might shadow another exception.*/
5718         Py_XDECREF(result);
5719         return PyErr_SetFromWindowsErr(GetLastError());
5720     }
5721     /* convert set to list */
5722     if (result == NULL) {
5723         return NULL;
5724     } else {
5725         PyObject *lst = PySequence_List(result);
5726         Py_DECREF(result);
5727         return lst;
5728     }
5729 }
5730 
5731 #endif /* _MSC_VER */
5732 
5733 /* List of functions exported by this module. */
5734 static PyMethodDef PySSL_methods[] = {
5735     _SSL__TEST_DECODE_CERT_METHODDEF
5736     _SSL_RAND_ADD_METHODDEF
5737     _SSL_RAND_BYTES_METHODDEF
5738     _SSL_RAND_PSEUDO_BYTES_METHODDEF
5739     _SSL_RAND_EGD_METHODDEF
5740     _SSL_RAND_STATUS_METHODDEF
5741     _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5742     _SSL_ENUM_CERTIFICATES_METHODDEF
5743     _SSL_ENUM_CRLS_METHODDEF
5744     _SSL_TXT2OBJ_METHODDEF
5745     _SSL_NID2OBJ_METHODDEF
5746     {NULL,                  NULL}            /* Sentinel */
5747 };
5748 
5749 
5750 #ifdef HAVE_OPENSSL_CRYPTO_LOCK
5751 
5752 /* an implementation of OpenSSL threading operations in terms
5753  * of the Python C thread library
5754  * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5755  */
5756 
5757 static PyThread_type_lock *_ssl_locks = NULL;
5758 
5759 #if OPENSSL_VERSION_NUMBER >= 0x10000000
5760 /* use new CRYPTO_THREADID API. */
5761 static void
_ssl_threadid_callback(CRYPTO_THREADID * id)5762 _ssl_threadid_callback(CRYPTO_THREADID *id)
5763 {
5764     CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
5765 }
5766 #else
5767 /* deprecated CRYPTO_set_id_callback() API. */
5768 static unsigned long
_ssl_thread_id_function(void)5769 _ssl_thread_id_function (void) {
5770     return PyThread_get_thread_ident();
5771 }
5772 #endif
5773 
_ssl_thread_locking_function(int mode,int n,const char * file,int line)5774 static void _ssl_thread_locking_function
5775     (int mode, int n, const char *file, int line) {
5776     /* this function is needed to perform locking on shared data
5777        structures. (Note that OpenSSL uses a number of global data
5778        structures that will be implicitly shared whenever multiple
5779        threads use OpenSSL.) Multi-threaded applications will
5780        crash at random if it is not set.
5781 
5782        locking_function() must be able to handle up to
5783        CRYPTO_num_locks() different mutex locks. It sets the n-th
5784        lock if mode & CRYPTO_LOCK, and releases it otherwise.
5785 
5786        file and line are the file number of the function setting the
5787        lock. They can be useful for debugging.
5788     */
5789 
5790     if ((_ssl_locks == NULL) ||
5791         (n < 0) || ((unsigned)n >= _ssl_locks_count))
5792         return;
5793 
5794     if (mode & CRYPTO_LOCK) {
5795         PyThread_acquire_lock(_ssl_locks[n], 1);
5796     } else {
5797         PyThread_release_lock(_ssl_locks[n]);
5798     }
5799 }
5800 
_setup_ssl_threads(void)5801 static int _setup_ssl_threads(void) {
5802 
5803     unsigned int i;
5804 
5805     if (_ssl_locks == NULL) {
5806         _ssl_locks_count = CRYPTO_num_locks();
5807         _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5808                                   sizeof(PyThread_type_lock));
5809         if (_ssl_locks == NULL) {
5810             PyErr_NoMemory();
5811             return 0;
5812         }
5813         for (i = 0;  i < _ssl_locks_count;  i++) {
5814             _ssl_locks[i] = PyThread_allocate_lock();
5815             if (_ssl_locks[i] == NULL) {
5816                 unsigned int j;
5817                 for (j = 0;  j < i;  j++) {
5818                     PyThread_free_lock(_ssl_locks[j]);
5819                 }
5820                 PyMem_Free(_ssl_locks);
5821                 return 0;
5822             }
5823         }
5824         CRYPTO_set_locking_callback(_ssl_thread_locking_function);
5825 #if OPENSSL_VERSION_NUMBER >= 0x10000000
5826         CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5827 #else
5828         CRYPTO_set_id_callback(_ssl_thread_id_function);
5829 #endif
5830     }
5831     return 1;
5832 }
5833 
5834 #endif  /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
5835 
5836 PyDoc_STRVAR(module_doc,
5837 "Implementation module for SSL socket operations.  See the socket module\n\
5838 for documentation.");
5839 
5840 
5841 static struct PyModuleDef _sslmodule = {
5842     PyModuleDef_HEAD_INIT,
5843     "_ssl",
5844     module_doc,
5845     -1,
5846     PySSL_methods,
5847     NULL,
5848     NULL,
5849     NULL,
5850     NULL
5851 };
5852 
5853 
5854 static void
parse_openssl_version(unsigned long libver,unsigned int * major,unsigned int * minor,unsigned int * fix,unsigned int * patch,unsigned int * status)5855 parse_openssl_version(unsigned long libver,
5856                       unsigned int *major, unsigned int *minor,
5857                       unsigned int *fix, unsigned int *patch,
5858                       unsigned int *status)
5859 {
5860     *status = libver & 0xF;
5861     libver >>= 4;
5862     *patch = libver & 0xFF;
5863     libver >>= 8;
5864     *fix = libver & 0xFF;
5865     libver >>= 8;
5866     *minor = libver & 0xFF;
5867     libver >>= 8;
5868     *major = libver & 0xFF;
5869 }
5870 
5871 PyMODINIT_FUNC
PyInit__ssl(void)5872 PyInit__ssl(void)
5873 {
5874     PyObject *m, *d, *r, *bases;
5875     unsigned long libver;
5876     unsigned int major, minor, fix, patch, status;
5877     PySocketModule_APIObject *socket_api;
5878     struct py_ssl_error_code *errcode;
5879     struct py_ssl_library_code *libcode;
5880 
5881     if (PyType_Ready(&PySSLContext_Type) < 0)
5882         return NULL;
5883     if (PyType_Ready(&PySSLSocket_Type) < 0)
5884         return NULL;
5885     if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5886         return NULL;
5887     if (PyType_Ready(&PySSLSession_Type) < 0)
5888         return NULL;
5889 
5890 
5891     m = PyModule_Create(&_sslmodule);
5892     if (m == NULL)
5893         return NULL;
5894     d = PyModule_GetDict(m);
5895 
5896     /* Load _socket module and its C API */
5897     socket_api = PySocketModule_ImportModuleAndAPI();
5898     if (!socket_api)
5899         return NULL;
5900     PySocketModule = *socket_api;
5901 
5902 #ifndef OPENSSL_VERSION_1_1
5903     /* Load all algorithms and initialize cpuid */
5904     OPENSSL_add_all_algorithms_noconf();
5905     /* Init OpenSSL */
5906     SSL_load_error_strings();
5907     SSL_library_init();
5908 #endif
5909 
5910 #ifdef HAVE_OPENSSL_CRYPTO_LOCK
5911     /* note that this will start threading if not already started */
5912     if (!_setup_ssl_threads()) {
5913         return NULL;
5914     }
5915 #elif OPENSSL_VERSION_1_1
5916     /* OpenSSL 1.1.0 builtin thread support is enabled */
5917     _ssl_locks_count++;
5918 #endif
5919 
5920     /* Add symbols to module dict */
5921     sslerror_type_slots[0].pfunc = PyExc_OSError;
5922     PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
5923     if (PySSLErrorObject == NULL)
5924         return NULL;
5925 
5926     /* ssl.CertificateError used to be a subclass of ValueError */
5927     bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5928     if (bases == NULL)
5929         return NULL;
5930     PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5931         "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5932         bases, NULL);
5933     Py_DECREF(bases);
5934     PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5935         "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5936         PySSLErrorObject, NULL);
5937     PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5938         "ssl.SSLWantReadError", SSLWantReadError_doc,
5939         PySSLErrorObject, NULL);
5940     PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5941         "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5942         PySSLErrorObject, NULL);
5943     PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5944         "ssl.SSLSyscallError", SSLSyscallError_doc,
5945         PySSLErrorObject, NULL);
5946     PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5947         "ssl.SSLEOFError", SSLEOFError_doc,
5948         PySSLErrorObject, NULL);
5949     if (PySSLCertVerificationErrorObject == NULL
5950         || PySSLZeroReturnErrorObject == NULL
5951         || PySSLWantReadErrorObject == NULL
5952         || PySSLWantWriteErrorObject == NULL
5953         || PySSLSyscallErrorObject == NULL
5954         || PySSLEOFErrorObject == NULL)
5955         return NULL;
5956     if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
5957         || PyDict_SetItemString(d, "SSLCertVerificationError",
5958                                 PySSLCertVerificationErrorObject) != 0
5959         || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5960         || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5961         || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5962         || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5963         || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
5964         return NULL;
5965     if (PyDict_SetItemString(d, "_SSLContext",
5966                              (PyObject *)&PySSLContext_Type) != 0)
5967         return NULL;
5968     if (PyDict_SetItemString(d, "_SSLSocket",
5969                              (PyObject *)&PySSLSocket_Type) != 0)
5970         return NULL;
5971     if (PyDict_SetItemString(d, "MemoryBIO",
5972                              (PyObject *)&PySSLMemoryBIO_Type) != 0)
5973         return NULL;
5974     if (PyDict_SetItemString(d, "SSLSession",
5975                              (PyObject *)&PySSLSession_Type) != 0)
5976         return NULL;
5977 
5978     PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5979                                PY_SSL_DEFAULT_CIPHER_STRING);
5980 
5981     PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5982                             PY_SSL_ERROR_ZERO_RETURN);
5983     PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5984                             PY_SSL_ERROR_WANT_READ);
5985     PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5986                             PY_SSL_ERROR_WANT_WRITE);
5987     PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5988                             PY_SSL_ERROR_WANT_X509_LOOKUP);
5989     PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5990                             PY_SSL_ERROR_SYSCALL);
5991     PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5992                             PY_SSL_ERROR_SSL);
5993     PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5994                             PY_SSL_ERROR_WANT_CONNECT);
5995     /* non ssl.h errorcodes */
5996     PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5997                             PY_SSL_ERROR_EOF);
5998     PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5999                             PY_SSL_ERROR_INVALID_ERROR_CODE);
6000     /* cert requirements */
6001     PyModule_AddIntConstant(m, "CERT_NONE",
6002                             PY_SSL_CERT_NONE);
6003     PyModule_AddIntConstant(m, "CERT_OPTIONAL",
6004                             PY_SSL_CERT_OPTIONAL);
6005     PyModule_AddIntConstant(m, "CERT_REQUIRED",
6006                             PY_SSL_CERT_REQUIRED);
6007     /* CRL verification for verification_flags */
6008     PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
6009                             0);
6010     PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
6011                             X509_V_FLAG_CRL_CHECK);
6012     PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
6013                             X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
6014     PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
6015                             X509_V_FLAG_X509_STRICT);
6016 #ifdef X509_V_FLAG_TRUSTED_FIRST
6017     PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
6018                             X509_V_FLAG_TRUSTED_FIRST);
6019 #endif
6020 
6021     /* Alert Descriptions from ssl.h */
6022     /* note RESERVED constants no longer intended for use have been removed */
6023     /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
6024 
6025 #define ADD_AD_CONSTANT(s) \
6026     PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
6027                             SSL_AD_##s)
6028 
6029     ADD_AD_CONSTANT(CLOSE_NOTIFY);
6030     ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
6031     ADD_AD_CONSTANT(BAD_RECORD_MAC);
6032     ADD_AD_CONSTANT(RECORD_OVERFLOW);
6033     ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
6034     ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
6035     ADD_AD_CONSTANT(BAD_CERTIFICATE);
6036     ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
6037     ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
6038     ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
6039     ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
6040     ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
6041     ADD_AD_CONSTANT(UNKNOWN_CA);
6042     ADD_AD_CONSTANT(ACCESS_DENIED);
6043     ADD_AD_CONSTANT(DECODE_ERROR);
6044     ADD_AD_CONSTANT(DECRYPT_ERROR);
6045     ADD_AD_CONSTANT(PROTOCOL_VERSION);
6046     ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
6047     ADD_AD_CONSTANT(INTERNAL_ERROR);
6048     ADD_AD_CONSTANT(USER_CANCELLED);
6049     ADD_AD_CONSTANT(NO_RENEGOTIATION);
6050     /* Not all constants are in old OpenSSL versions */
6051 #ifdef SSL_AD_UNSUPPORTED_EXTENSION
6052     ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
6053 #endif
6054 #ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
6055     ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
6056 #endif
6057 #ifdef SSL_AD_UNRECOGNIZED_NAME
6058     ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
6059 #endif
6060 #ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
6061     ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
6062 #endif
6063 #ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
6064     ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
6065 #endif
6066 #ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
6067     ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
6068 #endif
6069 
6070 #undef ADD_AD_CONSTANT
6071 
6072     /* protocol versions */
6073 #ifndef OPENSSL_NO_SSL2
6074     PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
6075                             PY_SSL_VERSION_SSL2);
6076 #endif
6077 #ifndef OPENSSL_NO_SSL3
6078     PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
6079                             PY_SSL_VERSION_SSL3);
6080 #endif
6081     PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
6082                             PY_SSL_VERSION_TLS);
6083     PyModule_AddIntConstant(m, "PROTOCOL_TLS",
6084                             PY_SSL_VERSION_TLS);
6085     PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
6086                             PY_SSL_VERSION_TLS_CLIENT);
6087     PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
6088                             PY_SSL_VERSION_TLS_SERVER);
6089     PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
6090                             PY_SSL_VERSION_TLS1);
6091     PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
6092                             PY_SSL_VERSION_TLS1_1);
6093     PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
6094                             PY_SSL_VERSION_TLS1_2);
6095 
6096     /* protocol options */
6097     PyModule_AddIntConstant(m, "OP_ALL",
6098                             SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
6099     PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
6100     PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
6101     PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
6102     PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
6103     PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
6104 #ifdef SSL_OP_NO_TLSv1_3
6105     PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
6106 #else
6107     PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
6108 #endif
6109     PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
6110                             SSL_OP_CIPHER_SERVER_PREFERENCE);
6111     PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
6112     PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
6113 #ifdef SSL_OP_SINGLE_ECDH_USE
6114     PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
6115 #endif
6116 #ifdef SSL_OP_NO_COMPRESSION
6117     PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
6118                             SSL_OP_NO_COMPRESSION);
6119 #endif
6120 #ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
6121     PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
6122                             SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
6123 #endif
6124 #ifdef SSL_OP_NO_RENEGOTIATION
6125     PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
6126                             SSL_OP_NO_RENEGOTIATION);
6127 #endif
6128 
6129 #ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
6130     PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
6131                             X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
6132 #endif
6133 #ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
6134     PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
6135                             X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
6136 #endif
6137 #ifdef X509_CHECK_FLAG_NO_WILDCARDS
6138     PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
6139                             X509_CHECK_FLAG_NO_WILDCARDS);
6140 #endif
6141 #ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
6142     PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
6143                             X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
6144 #endif
6145 #ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
6146     PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
6147                             X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
6148 #endif
6149 #ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
6150     PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
6151                             X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
6152 #endif
6153 
6154     /* protocol versions */
6155     PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
6156                             PY_PROTO_MINIMUM_SUPPORTED);
6157     PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
6158                             PY_PROTO_MAXIMUM_SUPPORTED);
6159     PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
6160     PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
6161     PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
6162     PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
6163     PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
6164 
6165 #define addbool(m, v, b) \
6166     Py_INCREF((b) ? Py_True : Py_False); \
6167     PyModule_AddObject((m), (v), (b) ? Py_True : Py_False);
6168 
6169 #if HAVE_SNI
6170     addbool(m, "HAS_SNI", 1);
6171 #else
6172     addbool(m, "HAS_SNI", 0);
6173 #endif
6174 
6175     addbool(m, "HAS_TLS_UNIQUE", 1);
6176 
6177 #ifndef OPENSSL_NO_ECDH
6178     addbool(m, "HAS_ECDH", 1);
6179 #else
6180     addbool(m, "HAS_ECDH", 0);
6181 #endif
6182 
6183 #if HAVE_NPN
6184     addbool(m, "HAS_NPN", 1);
6185 #else
6186     addbool(m, "HAS_NPN", 0);
6187 #endif
6188 
6189 #if HAVE_ALPN
6190     addbool(m, "HAS_ALPN", 1);
6191 #else
6192     addbool(m, "HAS_ALPN", 0);
6193 #endif
6194 
6195 #if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
6196     addbool(m, "HAS_SSLv2", 1);
6197 #else
6198     addbool(m, "HAS_SSLv2", 0);
6199 #endif
6200 
6201 #if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
6202     addbool(m, "HAS_SSLv3", 1);
6203 #else
6204     addbool(m, "HAS_SSLv3", 0);
6205 #endif
6206 
6207 #if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
6208     addbool(m, "HAS_TLSv1", 1);
6209 #else
6210     addbool(m, "HAS_TLSv1", 0);
6211 #endif
6212 
6213 #if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
6214     addbool(m, "HAS_TLSv1_1", 1);
6215 #else
6216     addbool(m, "HAS_TLSv1_1", 0);
6217 #endif
6218 
6219 #if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
6220     addbool(m, "HAS_TLSv1_2", 1);
6221 #else
6222     addbool(m, "HAS_TLSv1_2", 0);
6223 #endif
6224 
6225 #if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
6226     addbool(m, "HAS_TLSv1_3", 1);
6227 #else
6228     addbool(m, "HAS_TLSv1_3", 0);
6229 #endif
6230 
6231     /* Mappings for error codes */
6232     err_codes_to_names = PyDict_New();
6233     err_names_to_codes = PyDict_New();
6234     if (err_codes_to_names == NULL || err_names_to_codes == NULL)
6235         return NULL;
6236     errcode = error_codes;
6237     while (errcode->mnemonic != NULL) {
6238         PyObject *mnemo, *key;
6239         mnemo = PyUnicode_FromString(errcode->mnemonic);
6240         key = Py_BuildValue("ii", errcode->library, errcode->reason);
6241         if (mnemo == NULL || key == NULL)
6242             return NULL;
6243         if (PyDict_SetItem(err_codes_to_names, key, mnemo))
6244             return NULL;
6245         if (PyDict_SetItem(err_names_to_codes, mnemo, key))
6246             return NULL;
6247         Py_DECREF(key);
6248         Py_DECREF(mnemo);
6249         errcode++;
6250     }
6251     if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
6252         return NULL;
6253     if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
6254         return NULL;
6255 
6256     lib_codes_to_names = PyDict_New();
6257     if (lib_codes_to_names == NULL)
6258         return NULL;
6259     libcode = library_codes;
6260     while (libcode->library != NULL) {
6261         PyObject *mnemo, *key;
6262         key = PyLong_FromLong(libcode->code);
6263         mnemo = PyUnicode_FromString(libcode->library);
6264         if (key == NULL || mnemo == NULL)
6265             return NULL;
6266         if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6267             return NULL;
6268         Py_DECREF(key);
6269         Py_DECREF(mnemo);
6270         libcode++;
6271     }
6272     if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
6273         return NULL;
6274 
6275     /* OpenSSL version */
6276     /* SSLeay() gives us the version of the library linked against,
6277        which could be different from the headers version.
6278     */
6279     libver = OpenSSL_version_num();
6280     r = PyLong_FromUnsignedLong(libver);
6281     if (r == NULL)
6282         return NULL;
6283     if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6284         return NULL;
6285     parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6286     r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6287     if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6288         return NULL;
6289     r = PyUnicode_FromString(OpenSSL_version(OPENSSL_VERSION));
6290     if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6291         return NULL;
6292 
6293     libver = OPENSSL_VERSION_NUMBER;
6294     parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6295     r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6296     if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6297         return NULL;
6298 
6299     return m;
6300 }
6301