git: eef4e44a41e4 - stable/13 - telnet: Prevent buffer overflow in the user prompt for SRA

From: John Baldwin <jhb_at_FreeBSD.org>
Date: Tue, 29 Apr 2025 20:33:08 UTC
The branch stable/13 has been updated by jhb:

URL: https://cgit.FreeBSD.org/src/commit/?id=eef4e44a41e467416322d0ee8907262e4bb07d49

commit eef4e44a41e467416322d0ee8907262e4bb07d49
Author:     John Baldwin <jhb@FreeBSD.org>
AuthorDate: 2025-04-16 13:41:03 +0000
Commit:     John Baldwin <jhb@FreeBSD.org>
CommitDate: 2025-04-29 14:45:59 +0000

    telnet: Prevent buffer overflow in the user prompt for SRA
    
    The Secure RPC authenticator for telnet prompts the local user for the
    username to use for authentication.  Previously it was using sprintf()
    into a buffer of 256 bytes, but the username received over the wire
    can be up to 255 bytes long which would overflow the prompt buffer.
    Fix this in two ways: First, use snprintf() and check for overflow.
    If the prompt buffer overflows, fail authentication without prompting
    the user.  Second, add 10 bytes to the buffer size to account for the
    overhead of the prompt so that a maximally sized username fits.
    
    While here, replace a bare 255 in the subsequent telnet_gets call with
    an expression using sizeof() the relevant buffer.
    
    PR:             270263
    Reported by:    Robert Morris <rtm@lcs.mit.edu>
    Tested on:      CHERI
    Reviewed by:    emaste
    Differential Revision:  https://reviews.freebsd.org/D49832
    
    (cherry picked from commit 5737c2ae06e143e49496df2ab5a64f76d5456012)
---
 contrib/telnet/libtelnet/sra.c | 16 ++++++++++++----
 1 file changed, 12 insertions(+), 4 deletions(-)

diff --git a/contrib/telnet/libtelnet/sra.c b/contrib/telnet/libtelnet/sra.c
index 4a759685ca42..92ce5f6877d6 100644
--- a/contrib/telnet/libtelnet/sra.c
+++ b/contrib/telnet/libtelnet/sra.c
@@ -245,9 +245,10 @@ bad:
 void
 sra_reply(Authenticator *ap, unsigned char *data, int cnt)
 {
-	char uprompt[256],tuser[256];
+	char uprompt[256 + 10];	/* +10 for "User (): " */
+	char tuser[256];
 	Session_Key skey;
-	size_t i;
+	size_t i, len;
 
 	if (cnt-- < 1)
 		return;
@@ -270,8 +271,15 @@ sra_reply(Authenticator *ap, unsigned char *data, int cnt)
 
 		/* encode user */
 		memset(tuser,0,sizeof(tuser));
-		sprintf(uprompt,"User (%s): ",UserNameRequested);
-		telnet_gets(uprompt,tuser,255,1);
+		len = snprintf(uprompt, sizeof(uprompt), "User (%s): ",
+		    UserNameRequested);
+		if (len >= sizeof(uprompt)) {
+			if (auth_debug_mode) {
+				printf("SRA user name too long\r\n");
+			}
+			return;
+		}
+		telnet_gets(uprompt, tuser, sizeof(tuser) - 1, 1);
 		if (tuser[0] == '\n' || tuser[0] == '\r' )
 			strcpy(user,UserNameRequested);
 		else {