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