Skip to content

mbedtls: add support for AES-GCM ciphers - #2505

Closed
vszakats wants to merge 38 commits into
libssh2:masterfrom
vszakats:mbedgcm
Closed

vszakats wants to merge 38 commits into
libssh2:masterfrom
vszakats:mbedgcm

Conversation

@vszakats

@vszakats vszakats commented Aug 4, 2026 •

Copy link
Copy Markdown
Member

In addition to the original patch:

  • simplify cipher object. drop the allocation and double redirection,
    drop redundant encrypt member, shorten/dedupe names, replace algo
    with is_gcm.
  • replace heap alloc with stack buffer for GCM in ssh2_cipher_crypt().
  • use the algo argument instead of the context copy.
    (for speed and to match OpenSSL sibling code.)
  • fix returned error value on GCM auth fail.
  • increment IV on decrypt auth fail. Copilot suggestion. I cannot
    confirm this, so erring on the side caution to avoid a potential IV
    reuse.
  • support mbedTLS builds without GCM built-in, via MBEDTLS_GCM_C.
  • retrofit bounds check applied to OpenSSL backend earlier.
    Follow-up to a2ed82d openssl: fix potential OOB read/write with AES-GCM in ssh2_cipher_crypt() #2401
  • misc tidy-ups.

Original-patch-by: Adrian Moran
Closes #1764

@vszakats
vszakats marked this pull request as draft August 4, 2026 00:52
@vszakats

This comment was marked as resolved.

@vszakats vszakats changed the title mbedtls: try adding AES-GCM support mbedtls: add support for cipher AES-GCM Aug 4, 2026
@vszakats
vszakats marked this pull request as ready for review August 4, 2026 01:40
@vszakats
vszakats requested a review from Copilot August 4, 2026 01:40
@vszakats vszakats changed the title mbedtls: add support for cipher AES-GCM mbedtls: add support for AES-GCM ciphers Aug 4, 2026

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR enables AES-128-GCM and AES-256-GCM cipher support in the mbedTLS backend, and refactors the mbedTLS cipher context handling to support both “regular” ciphers and AEAD (GCM) under a unified context structure.

Changes:

  • Enable LIBSSH2_AES_GCM for the mbedTLS backend and add mbedTLS GCM header support.
  • Introduce a unified ssh2_cipher_ctx structure for mbedTLS that can hold either a mbedtls_cipher_context_t or a GCM context + IV.
  • Implement AES-GCM init/crypt/dtor paths using mbedtls_gcm_* APIs, while keeping existing non-GCM ciphers on the generic cipher API.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
src/mbedtls.h Enables AES-GCM and introduces a unified cipher context type for mbedTLS (cipher vs GCM union).
src/mbedtls.c Adds AES-GCM init/crypt/dtor implementation using mbedtls_gcm_*, and adapts the non-GCM path to the new unified context.
Suppressed comments (2)

src/mbedtls.c:196

  • The AES-GCM branch selection uses the algo argument instead of the algorithm stored in the cipher context. If algo ever diverges from the initialized context (or if a caller accidentally passes the wrong algo), this can route into the wrong union member (u.gcm vs u.cipher) and cause undefined behavior. Prefer branching on ctx->algo and mark the algo parameter unused in this backend.
    if(!ctx)
        return -1;

#if LIBSSH2_AES_GCM
    /* Check if this is a GCM algorithm based on stored algo type */
    if(algo == MBEDTLS_CIPHER_AES_128_GCM ||
       algo == MBEDTLS_CIPHER_AES_256_GCM) {
        const int authlen = 16;  /* GCM authentication tag length */

src/mbedtls.c:210

  • cryptlen is computed by narrowing blocksize (size_t) to unsigned int. If blocksize ever exceeds UINT_MAX, the cast truncates and the subsequent allocation / encryption will operate on the wrong length, which can lead to incorrect encryption and potential memory safety issues. Use size_t for cryptlen and avoid the narrowing cast; also prefer mbedtls_calloc(1, cryptlen) to avoid internal multiplication overflow.
        if(blocksize < (size_t)(aadlen + authenticationtag))
            return -1;

        cryptlen = (unsigned int)blocksize - aadlen - authenticationtag;

        /* Allocate temporary buffer for output */
        if(cryptlen > 0) {
            buf = mbedtls_calloc(cryptlen, 1);

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/mbedtls.c Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

Suppressed comments (4)

src/mbedtls.h:48

  • <mbedtls/gcm.h> is included unconditionally, but GCM support is already feature-gated by MBEDTLS_GCM_C/LIBSSH2_AES_GCM. To keep builds that disable/omit the GCM module aligned with other optional mbedTLS includes (e.g., ECDH/ECDSA), include this header only when MBEDTLS_GCM_C is enabled.
#include <mbedtls/cipher.h>
#include <mbedtls/gcm.h>
#ifdef MBEDTLS_ECDH_C
# include <mbedtls/ecdh.h>

src/mbedtls.c:271

  • After moving the IV increment to the start-of-packet path, the increment at the end of the IS_LAST(firstlast) block should be removed (and the now-unused i variable dropped) to avoid incrementing twice per packet.
            /* Increment IV for next packet */
            for(i = 11; i >= 4; i--)
                if(++ctx->u.gcm.iv[i])
                    break;

src/mbedtls.c:223

  • The IV (invocation counter) is currently incremented after processing the last block. In the OpenSSL backend, the counter is incremented at the start of the packet (before AAD/payload processing). To avoid nonce/counter sequencing differences between backends, increment the IV in the IS_FIRST(firstlast) path before calling mbedtls_gcm_starts().

This issue also appears on line 268 of the same file.

        /* First block: start GCM operation */
        if(IS_FIRST(firstlast)) {
            ret = mbedtls_gcm_starts(&ctx->u.gcm.ctx,
                                     encrypt ? MBEDTLS_GCM_ENCRYPT
                                             : MBEDTLS_GCM_DECRYPT,
                                     ctx->u.gcm.iv, 12);

src/mbedtls.c:192

  • This comment says GCM detection is based on the stored algorithm type, but the check uses the algo argument. Either update the comment to match the code, or switch the check to ctx->algo for consistency with ssh2_cipher_dtor().
    /* Check if this is a GCM algorithm based on stored algo type */
    if(algo == MBEDTLS_CIPHER_AES_128_GCM ||
       algo == MBEDTLS_CIPHER_AES_256_GCM) {

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

Suppressed comments (1)

src/mbedtls.c:211

  • The AES-GCM path allocates and frees a temporary heap buffer on every crypt() call (often per 16-byte block), which is likely to be a significant performance hit and allocator churn in the transport hot path. Consider doing the GCM update in-place (if supported by mbedTLS), using a fixed-size stack buffer for small blocks, or keeping a reusable scratch buffer in the cipher context so you only allocate once per session/packet.
        /* Allocate temporary buffer for output */
        if(cryptlen > 0) {
            buf = mbedtls_calloc(cryptlen, 1);
            if(!buf)
                return -1;
        }

Comment thread src/mbedtls.c
Comment on lines +245 to +265
if(IS_LAST(firstlast)) {
unsigned char finish_buf[16];
int i;

finish_olen = 0;
if(mbedtls_gcm_finish(&ctx->u.gcm.ctx,
finish_buf, sizeof(finish_buf),
&finish_olen, tag, authlen))
return -1;

if(encrypt)
memcpy(block + blocksize - authlen, tag, authlen);
else if(ssh2_timingsafe_bcmp(tag, block + blocksize - authlen,
authlen))
return -1; /* GCM auth failed */

/* Increment IV for next packet */
for(i = 11; i >= 4; i--)
if(++ctx->u.gcm.iv[i])
break;
}

@vszakats vszakats Aug 4, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this accurate?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I go with this suggestion (with different code though).

@vszakats vszakats Aug 4, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But, I'm still more than uncertain if this is correct. My thought is
to avoid an IV reuse, even if it means to break the connection.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

Suppressed comments (1)

src/mbedtls.c:245

  • In the AES-GCM decrypt path, authentication failure returns immediately before advancing the per-packet IV/counter. If the session continues after a failed packet (or if decryption is retried), this can cause IV reuse with the same key, which is catastrophic for GCM. The OpenSSL backend advances the invocation counter at the start of processing the packet, so it always moves forward even on tag failure; mbedTLS should likewise advance the IV even when the tag comparison fails.
            if(encrypt)
                memcpy(block + blocksize - authlen, tag, authlen);
            else if(ssh2_timingsafe_bcmp(tag, block + blocksize - authlen,
                                         authlen))
                return -1;  /* GCM auth failed */

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

Comment thread src/mbedtls.c
Comment on lines +249 to +252
/* Increment IV for next packet */
for(i = 11; i >= 4; i--)
if(++ctx->u.gcm.iv[i])
break;

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LLM seems to be on a spiral of doom here.

According to tests, moving the IV increment to the FIRST block breaks AES-GCM here.

So no, not doing this.

@vszakats vszakats closed this in d5ba5bc Aug 4, 2026
@vszakats
vszakats deleted the mbedgcm branch August 4, 2026 13:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants