7860cb
diff --git a/compat.c b/compat.c
7860cb
index 46dfe3a9c2e..478a9403eea 100644
7860cb
--- a/compat.c
7860cb
+++ b/compat.c
7860cb
@@ -190,26 +190,26 @@ compat_pkalg_proposal(struct ssh *ssh, char *pkalg_prop)
7860cb
 char *
7860cb
 compat_kex_proposal(struct ssh *ssh, char *p)
7860cb
 {
7860cb
-	char *cp = NULL;
7860cb
+	char *cp = NULL, *cp2 = NULL;
7860cb
 
7860cb
 	if ((ssh->compat & (SSH_BUG_CURVE25519PAD|SSH_OLD_DHGEX)) == 0)
7860cb
 		return xstrdup(p);
7860cb
 	debug2_f("original KEX proposal: %s", p);
7860cb
 	if ((ssh->compat & SSH_BUG_CURVE25519PAD) != 0)
7860cb
-		if ((p = match_filter_denylist(p,
7860cb
+		if ((cp = match_filter_denylist(p,
7860cb
 		    "curve25519-sha256@libssh.org")) == NULL)
7860cb
 			fatal("match_filter_denylist failed");
7860cb
 	if ((ssh->compat & SSH_OLD_DHGEX) != 0) {
7860cb
-		cp = p;
7860cb
-		if ((p = match_filter_denylist(p,
7860cb
+		if ((cp2 = match_filter_denylist(cp ? cp : p,
7860cb
 		    "diffie-hellman-group-exchange-sha256,"
7860cb
 		    "diffie-hellman-group-exchange-sha1")) == NULL)
7860cb
 			fatal("match_filter_denylist failed");
7860cb
 		free(cp);
7860cb
+		cp = cp2;
7860cb
 	}
7860cb
-	debug2_f("compat KEX proposal: %s", p);
7860cb
-	if (*p == '\0')
7860cb
+	if (cp == NULL || *cp == '\0')
7860cb
 		fatal("No supported key exchange algorithms found");
7860cb
-	return p;
7860cb
+	debug2_f("compat KEX proposal: %s", cp);
7860cb
+	return cp;
7860cb
 }
7860cb