Partial backport of:

From 35d5917652106aede47621bb3f64044604164043 Mon Sep 17 00:00:00 2001
From: "djm@openbsd.org" <djm@openbsd.org>
Date: Thu, 4 Sep 2025 00:29:09 +0000
Subject: [PATCH] upstream: Improve rules for %-expansion of username.

Usernames passed on the commandline will no longer be subject to
% expansion. Some tools invoke ssh with connection information
(i.e. usernames and host names) supplied from untrusted sources.
These may contain % expansion sequences which could yield
unexpected results.

Since openssh-9.6, all usernames have been subject to validity
checking. This change tightens the validity checks by refusing
usernames that include control characters (again, these can cause
surprises when supplied adversarially).

This change also relaxes the validity checks in one small way:
usernames supplied via the configuration file as literals (i.e.
include no % expansion characters) are not subject to these
validity checks. This allows usernames that contain arbitrary
characters to be used, but only via configuration files. This
is done on the basis that ssh's configuration is trusted.

Pointed out by David Leadbeater, ok deraadt@

OpenBSD-Commit-ID: e2f0c871fbe664aba30607321575e7c7fc798362
---
 ssh.c | 33 ++++++++++++++++++++++++++-------
 1 file changed, 26 insertions(+), 7 deletions(-)

--- a/ssh.c
+++ b/ssh.c
@@ -634,6 +634,8 @@ valid_ruser(const char *s)
 	if (*s == '-')
 		return 0;
 	for (i = 0; s[i] != 0; i++) {
+		if (iscntrl((u_char)s[i]))
+			return 0;
 		if (strchr("'`\";&<>|(){}", s[i]) != NULL)
 			return 0;
 		/* Disallow '-' after whitespace */
