From fd8614c5c5466a14a945db5b059c10c0fb8f76d9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Miro=20Hron=C4=8Dok?= <miro@hroncok.cz>
Date: Fri, 8 Dec 2017 22:34:12 +0100
Subject: [PATCH] bpo-30657: Fix CVE-2017-1000158 (#4664)

Fixes possible integer overflow in PyBytes_DecodeEscape.

Co-Authored-By: Jay Bosamiya <jaybosamiya@gmail.com>
---
 Misc/ACKS                                                 | 2 ++
 .../Security/2017-12-01-18-51-03.bpo-30657.Fd8kId.rst     | 2 ++
 Objects/bytesobject.c                                     | 8 +++++++-
 3 files changed, 11 insertions(+), 1 deletion(-)
 create mode 100644 Misc/NEWS.d/next/Security/2017-12-01-18-51-03.bpo-30657.Fd8kId.rst

diff --git a/Objects/bytesobject.c b/Objects/bytesobject.c
index 77dd45e84af8..9b29dc38b44f 100644
--- a/Objects/bytesobject.c
+++ b/Objects/bytesobject.c
@@ -970,7 +970,13 @@ PyObject *PyBytes_DecodeEscape(const char *s,
     char *p, *buf;
     const char *end;
     PyObject *v;
-    Py_ssize_t newlen = recode_encoding ? 4*len:len;
+    Py_ssize_t newlen;
+    /* Check for integer overflow */
+    if (recode_encoding && (len > PY_SSIZE_T_MAX / 4)) {
+        PyErr_SetString(PyExc_OverflowError, "string is too large");
+        return NULL;
+    }
+    newlen = recode_encoding ? 4*len:len;
     v = PyBytes_FromStringAndSize((char *)NULL, newlen);
     if (v == NULL)
         return NULL;
