git/list[1] front-page[2] threads[3] people[4] search[5] about
 

[PATCH] strlcpy(): safer and faster version

From
AGAndriy Makukha via GitGitGadget <gitgitgadget@gmail.com>
Date
Dec 16, 2021, 17:31 UTC
Message-ID
<pull.1097.git.1639675881065.gitgitgadget@gmail.com>
From: Andrii Makukha <andriy.makukha@gmail.com>

Original strlcpy() has a significant disadvantage of being both unsafe and inefficient. It unnecessarily calculates length of `src` which may result in a segmentation fault if `src` is not terminated with a NUL-character.

In this fix, if `src` is too long, strlcpy() returns `size`. This allows to still detect an error while fixing the mentioned vulnerabilities. It deviates from original strlcpy(), but for a good reason.

Signed-off-by: Andrii Makukha <andriy.makukha@gmail.com>
---
    strlcpy(): safer and faster version
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-1097%2Famakukha%2Fmaint-v1
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-1097/amakukha/maint-v1
Pull-Request: https://github.com/gitgitgadget/git/pull/1097
 compat/strlcpy.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
diff --git a/compat/strlcpy.c b/compat/strlcpy.c
index 4024c360301..e7fd11015c7 100644
--- a/compat/strlcpy.c
+++ b/compat/strlcpy.c
@@ -2,7 +2,12 @@
 
 size_t gitstrlcpy(char *dest, const char *src, size_t size)
 {
-	size_t ret = strlen(src);
+	/*
+	 * NOTE: original strlcpy returns full length of src, but this is
+	 * unsafe. This implementation returns `size` if src is too long.
+	 * This behaviour is faster and still allows to detect an issue.
+	 */
+	size_t ret = strnlen(src, size);
 
 	if (size) {
 		size_t len = (ret >= size) ? size - 1 : ret;

base-commit: e9d7761bb94f20acc98824275e317fa82436c25d
-- 
gitgitgadget
Next: Jeff King
Message 1 of 5 in “strlcpy(): safer and faster version”
  1. strlcpy(): safer and faster versionAndriy Makukha via GitGitGadget, Dec 16, 2021
  2. Jeff KingDec 16, 2021
  3. Junio C HamanoDec 16, 2021
  4. Ævar Arnfjörð BjarmasonDec 17, 2021
  5. Junio C HamanoDec 17, 2021

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.