From d90a44f2297a88df7887a25d3167c92209717fc8 Mon Sep 17 00:00:00 2001
From: David Mandelberg <david@mandelberg.org>
Date: Thu, 27 Mar 2025 16:19:15 -0400
Subject: [PATCH] Fix buffer overflow when processing extended keys

If I run tmux under valgrind, then run this command, where
`/proc/5187/fd/0` is tmux's stdin:

```
printf '\e[00000000000000000000000000000000000000000000000000000000000000000' > /proc/5187/fd/0
```

I got this error:

```
==5189== Conditional jump or move depends on uninitialised value(s)
==5189==    at 0x484DC78: strlen (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==5189==    by 0x4A62451: _IO_str_init_static_internal (strops.c:41)
==5189==    by 0x4A2D3FD: _IO_strfile_read (strfile.h:90)
==5189==    by 0x4A2D3FD: __isoc23_sscanf (isoc23_sscanf.c:28)
==5189==    by 0x19BA81: tty_keys_extended_key (tty-keys.c:1072)
==5189==    by 0x19BA81: tty_keys_next (tty-keys.c:822)
==5189==    by 0x19D9E7: tty_read_callback (tty.c:192)
==5189==    by 0x48B7136: ??? (in /usr/lib/x86_64-linux-gnu/libevent_core-2.1.so.7.0.1)
==5189==    by 0x48B793E: event_base_loop (in /usr/lib/x86_64-linux-gnu/libevent_core-2.1.so.7.0.1)
==5189==    by 0x17A766: proc_loop (proc.c:213)
==5189==    by 0x18EEF3: server_start (server.c:253)
==5189==    by 0x12D872: client_connect (client.c:164)
==5189==    by 0x12D872: client_main (client.c:295)
==5189==    by 0x128307: main (tmux.c:537)
```

This commit fixes that.

Addresses #4421
---
 tty-keys.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/tty-keys.c b/tty-keys.c
index 7b0da5a2..f78b84f2 100644
--- a/tty-keys.c
+++ b/tty-keys.c
@@ -1061,8 +1061,8 @@ tty_keys_extended_key(struct tty *tty, const char *buf, size_t len,
 		return (-1);
 
 	/* Copy to the buffer. */
-	memcpy(tmp, buf + 2, end);
-	tmp[end] = '\0';
+	memcpy(tmp, buf + 2, end - 2);
+	tmp[end - 2] = '\0';
 
 	/* Try to parse either form of key. */
 	if (buf[end] == '~') {