From 74d5c9d77e18eae87726ae7f9844c3653faccd29 Mon Sep 17 00:00:00 2001 From: "Erlend E. Aasland" Date: Sun, 11 Jun 2023 11:56:32 +0200 Subject: [PATCH 1/2] [3.11] gh-105375: Harden _ssl initialisation (#105599) (cherry picked from commit 01f4230460454d4a849a5ba93320142c1a0c93a8) Add proper error handling to prevent reference leaks and overwritten exceptions. Co-authored-by: Erlend E. Aasland --- ...-06-09-22-16-46.gh-issue-105375.EgVJOP.rst | 2 ++ Modules/_ssl.c | 21 +++++++++++++------ 2 files changed, 17 insertions(+), 6 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2023-06-09-22-16-46.gh-issue-105375.EgVJOP.rst diff --git a/Misc/NEWS.d/next/Library/2023-06-09-22-16-46.gh-issue-105375.EgVJOP.rst b/Misc/NEWS.d/next/Library/2023-06-09-22-16-46.gh-issue-105375.EgVJOP.rst new file mode 100644 index 00000000000000..49f7df68e927cb --- /dev/null +++ b/Misc/NEWS.d/next/Library/2023-06-09-22-16-46.gh-issue-105375.EgVJOP.rst @@ -0,0 +1,2 @@ +Fix bugs in :mod:`!_ssl` initialisation which could lead to leaked +references and overwritten exceptions. diff --git a/Modules/_ssl.c b/Modules/_ssl.c index 1a4102434ede2a..0f3e902ca2c57c 100644 --- a/Modules/_ssl.c +++ b/Modules/_ssl.c @@ -6052,17 +6052,26 @@ sslmodule_init_errorcodes(PyObject *module) errcode = error_codes; while (errcode->mnemonic != NULL) { - PyObject *mnemo, *key; - mnemo = PyUnicode_FromString(errcode->mnemonic); - key = Py_BuildValue("ii", errcode->library, errcode->reason); - if (mnemo == NULL || key == NULL) + PyObject *mnemo = PyUnicode_FromString(errcode->mnemonic); + if (mnemo == NULL) { return -1; - if (PyDict_SetItem(state->err_codes_to_names, key, mnemo)) + } + PyObject *key = Py_BuildValue("ii", errcode->library, errcode->reason); + if (key == NULL) { + Py_DECREF(mnemo); return -1; - if (PyDict_SetItem(state->err_names_to_codes, mnemo, key)) + } + if (PyDict_SetItem(state->err_codes_to_names, key, mnemo) < 0) { + Py_DECREF(key); + Py_DECREF(mnemo); return -1; + } + int rc = PyDict_SetItem(state->err_codes_to_names, key, mnemo); Py_DECREF(key); Py_DECREF(mnemo); + if (rc < 0) { + return -1; + } errcode++; } From d4e7579e23311900ff15a87e93803572c8e16cf6 Mon Sep 17 00:00:00 2001 From: "Erlend E. Aasland" Date: Sun, 11 Jun 2023 12:34:39 +0200 Subject: [PATCH 2/2] Fix merge --- Modules/_ssl.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/_ssl.c b/Modules/_ssl.c index 0f3e902ca2c57c..c1a8eaaa2fa0a9 100644 --- a/Modules/_ssl.c +++ b/Modules/_ssl.c @@ -6066,7 +6066,7 @@ sslmodule_init_errorcodes(PyObject *module) Py_DECREF(mnemo); return -1; } - int rc = PyDict_SetItem(state->err_codes_to_names, key, mnemo); + int rc = PyDict_SetItem(state->err_names_to_codes, mnemo, key); Py_DECREF(key); Py_DECREF(mnemo); if (rc < 0) {