From 303c766d67cef5c357e9b3d3a97f7b480d29e1cb Mon Sep 17 00:00:00 2001
From: Krzysztof Kozlowski <krzk@kernel.org>
Date: Thu, 12 Jul 2018 18:13:16 +0200
Subject: [PATCH 1/3] Fix possible buffer overflow with strncpy and
 -Wstringop-truncation warning

If valid cipher name (to which netlink socket was bound) is longer than
CRYPTO_MAX_ALG_NAME defined in lib/cryptouser.h, then the strncpy() will
try to copy length of this cipher name into smaller buffer.

In libkcapi the CRYPTO_MAX_ALG_NAME (thus the size of the buffer) is
defined as 64 but since commit f437a3f477cc ("crypto: api - Extend
algorithm name limit to 128 bytes") in Linux kernel (v4.12), the kernel
defines it as 128.

It is error-prone to use source buffer length as limit of dst buffer.
Instead choose sizeof(dst buffer).

This also fixes the warning with GCC v8.1.0:

    lib/kcapi-kernel-if.c: In function '__kcapi_common_getinfo.isra.2':
    lib/kcapi-kernel-if.c:632:3: error: 'strncpy' output truncated before terminating nul copying as many bytes from a string as its length [-Werror=stringop-truncation]
        strncpy(req.cru.cru_name, ciphername, strlen(ciphername));
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Signed-off-by: Krzysztof Kozlowski <krzk@kernel.org>
Upstream-Status: Submitted
---
 lib/kcapi-kernel-if.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/lib/kcapi-kernel-if.c b/lib/kcapi-kernel-if.c
index 2481f8abde63..807cbfe219cd 100644
--- a/lib/kcapi-kernel-if.c
+++ b/lib/kcapi-kernel-if.c
@@ -627,9 +627,9 @@ static int __kcapi_common_getinfo(struct kcapi_handle *handle,
 
 	if (drivername)
 		strncpy(req.cru.cru_driver_name, ciphername,
-			strlen(ciphername));
+			sizeof(req.cru.cru_driver_name) - 1);
 	else
-		strncpy(req.cru.cru_name, ciphername, strlen(ciphername));
+		strncpy(req.cru.cru_name, ciphername, sizeof(req.cru.cru_name) - 1);
 
 	/* talk to netlink socket */
 	sd =  socket(AF_NETLINK, SOCK_RAW, NETLINK_CRYPTO);
-- 
2.7.4

