Blob Blame History Raw
From 3e388ac4eba63b466bf6b14b2088ea44c8a2bfe4 Mon Sep 17 00:00:00 2001
From: Krzysztof Kozlowski <krzk@kernel.org>
Date: Thu, 12 Jul 2018 18:13:16 +0200
Subject: [PATCH] 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>
Signed-off-by: Stephan Mueller <smueller@chronox.de>
---
 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 2481f8a..807cbfe 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);