From a2ed82d40964bbc0d64cd717aa0a5a892117d2e6 Mon Sep 17 00:00:00 2001
From: Viktor Szakats <commit@vsz.me>
Date: Thu, 23 Jul 2026 10:32:04 +0200
Subject: [PATCH] openssl: fix potential OOB read/write with AES-GCM in
 `ssh2_cipher_crypt()`

By applying two bounds checks to non-debug builds.

Reported-by: Vladimir Eli Tokarev
Fixes GHSA-c4f7-cvfc-33j7
Follow-up to 3c953c05d67eb1ebcfd3316f279f12c4b1d600b4 #797

Closes #2401
---
 src/openssl.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/src/openssl.c b/src/openssl.c
index 6a38b55b91..31ef6db371 100644
--- a/src/openssl.c
+++ b/src/openssl.c
@@ -945,13 +945,15 @@ int ssh2_cipher_crypt(ssh2_cipher_ctx *ctx, SSH2_CIPHER_T(algo), int encrypt,
     const int aadlen = (is_aesgcm && IS_FIRST(firstlast)) ? 4 : 0;
     /* size of AT, if present */
     const int authenticationtag = IS_LAST(firstlast) ? authlen : 0;
-    /* length to encrypt */
-    const int cryptlen = (unsigned int)blocksize - aadlen - authenticationtag;
+    unsigned int cryptlen; /* length to encrypt */
 
     (void)algo;
 
-    assert(blocksize <= sizeof(buf));
-    assert(cryptlen >= 0);
+    if(blocksize > sizeof(buf) ||
+       blocksize < (size_t)(aadlen + authenticationtag))
+        return 1;
+
+    cryptlen = (unsigned int)blocksize - aadlen - authenticationtag;
 
 #if LIBSSH2_AES_GCM
     /* First block */
