Return-Path: Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1755683AbcCTMe0 (ORCPT ); Sun, 20 Mar 2016 08:34:26 -0400 Received: from mail-wm0-f68.google.com ([74.125.82.68]:34797 "EHLO mail-wm0-f68.google.com" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1755651AbcCTMeN (ORCPT ); Sun, 20 Mar 2016 08:34:13 -0400 From: Nicolai Stange To: Herbert Xu Cc: Tadeusz Struk , Michal Marek , Andrzej Zaborowski , Stephan Mueller , Arnd Bergmann , linux-kernel@vger.kernel.org, Nicolai Stange Subject: [PATCH v2 08/14] lib/mpi: mpi_read_buffer(): fix buffer overflow Date: Sun, 20 Mar 2016 13:31:29 +0100 Message-Id: <1458477095-4619-9-git-send-email-nicstange@gmail.com> X-Mailer: git-send-email 2.7.3 In-Reply-To: <1458477095-4619-1-git-send-email-nicstange@gmail.com> References: <1458477095-4619-1-git-send-email-nicstange@gmail.com> Sender: linux-kernel-owner@vger.kernel.org List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Length: 1540 Lines: 50 Currently, mpi_read_buffer() writes full limbs to the output buffer and moves memory around to purge leading zero limbs afterwards. However, with commit 9cbe21d8f89d ("lib/mpi: only require buffers as big as needed for the integer") the caller is only required to provide a buffer large enough to hold the result without the leading zeros. This might result in a buffer overflow for small MP numbers with leading zeros. Fix this by coping the result to its final destination within the output buffer and not copying the leading zeros at all. Fixes: 9cbe21d8f89d ("lib/mpi: only require buffers as big as needed for the integer") Signed-off-by: Nicolai Stange --- lib/mpi/mpicoder.c | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/lib/mpi/mpicoder.c b/lib/mpi/mpicoder.c index a999ee1..27582e2 100644 --- a/lib/mpi/mpicoder.c +++ b/lib/mpi/mpicoder.c @@ -201,16 +201,9 @@ int mpi_read_buffer(MPI a, uint8_t *buf, unsigned buf_len, unsigned *nbytes, #else #error please implement for this limb size. #endif - memcpy(p, &alimb, BYTES_PER_MPI_LIMB); - p += BYTES_PER_MPI_LIMB; - if (lzeros > 0) { - mpi_limb_t *limb1 = (void *)p - sizeof(alimb); - mpi_limb_t *limb2 = (void *)p - sizeof(alimb) - + lzeros; - *limb1 = *limb2; - p -= lzeros; - lzeros -= sizeof(alimb); - } + memcpy(p, &alimb + lzeros, BYTES_PER_MPI_LIMB - lzeros); + p += BYTES_PER_MPI_LIMB - lzeros; + lzeros = 0; } return 0; } -- 2.7.3