Skip to content

src: drop casts, constify - #2420

Closed
vszakats wants to merge 27 commits into
libssh2:masterfrom
vszakats:casts2
Closed

vszakats wants to merge 27 commits into
libssh2:masterfrom
vszakats:casts2

Conversation

@vszakats

@vszakats vszakats commented Jul 24, 2026 •

Copy link
Copy Markdown
Member
  • change types to match common usage to reduce casts.
    (mostly unsigned char * to char *)
  • use non-unsigned variant of ssh2_get_string().
  • use void * arg in kex_value_hash() to avoid casts.
  • packet: replace magic number with sizeof() in ssh2_packet_add(),
    also make the constant static.
  • drop redundant casts missed earlier.

Follow-up to 907fe84 #2424

Copilot AI review requested due to automatic review settings July 24, 2026 00:02

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 cleans up internal string/byte handling by aligning pointer types with how the data is used (primarily treating textual protocol fields as char * / const char *) and removing redundant casts, which reduces noise across the SSH session, key parsing, and SCP/userauth code paths.

Changes:

  • Convert several session fields and local variables from unsigned char * to char * where they represent textual data (banners, kbd-int name/instruction, SCP command buffers, etc.).
  • Update parsing call sites to match these type changes (adding necessary casts when calling helpers like ssh2_get_string() / ssh2_copy_string()).
  • Constify and adjust helper APIs used for kex algorithm negotiation (ssh2_kex_agree_instr and related call sites).

Reviewed changes

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

Show a summary per file
File Description
src/userauth.c Removes redundant casts when passing kbd-int name/instruction into the response callback.
src/userauth_kbd_packet.c Adjusts ssh2_copy_string() calls to store into char * session fields.
src/session.c Treats local/remote banners as char * and removes casts around strlen/strncmp.
src/scp.c Treats SCP command buffers and quoting helpers as char * to reduce casting.
src/publickey.c Aligns comment attribute handling with const char * usage.
src/pem.c Treats OpenSSH key header strings as char * and updates parsing/strcmp call sites.
src/packet.c Uses char * for disconnect/debug message strings and constifies strict-kex marker usage.
src/os400qc3.c Removes redundant cast when passing decoded PEM data into key-loading proc.
src/openssl.c Uses char * for parsed key type strings and removes redundant casts in comparisons/calls.
src/misc.c Removes redundant casts in timing-safe compare implementation.
src/mbedtls.c Uses char * for parsed curve name and removes redundant cast in curve lookup.
src/libssh2_priv.h Updates session struct field types and constifies ssh2_kex_agree_instr signature.
src/kex.c Propagates kex string type changes and constifies negotiation helpers and value-hash inputs.
src/hostkey.c Uses char * for parsed ECDSA type/domain strings and removes redundant casts.

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

Comment thread src/pem.c
Comment on lines +401 to 403
char *ciphername = NULL;
char *kdfname = NULL;
unsigned char *kdf = NULL;

@vszakats vszakats Jul 24, 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.

Separate issue.

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.

PR → #2421

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.

Related:

via: #2420 (review)

Pull request overview

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

Comments suppressed due to low confidence (2)

src/openssl.c:3369

  • ssh2_get_string() returns a pointer/length slice that is not NUL-terminated (see ssh2_get_string() in src/misc.c). Here buf is treated as a C string via strcmp() / strlen() (also indirectly in ossl_ecdsa_curve_type_from_name()), which can read past the end of the SSH string and into subsequent decrypted data (OOB read) for malformed inputs. Capture the returned length and either compare using length-bounded logic (len + memcmp/strncmp) or copy the type into a bounded, NUL-terminated buffer before calling any C-string APIs.

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

    rc = ssh2_get_string(decrypted, (unsigned char **)&buf, NULL);
    if(rc || !buf) {
        rc = ssh2_err(session, LIBSSH2_ERROR_PROTO,
                      "Public key type in decrypted key data not found");
        goto cleanup;
    }

src/openssl.c:3470

  • Same issue as above: buf comes from ssh2_get_string() and is not NUL-terminated, but is compared with strcmp(). For malformed inputs this can cause OOB reads. Capture the string length and use length-bounded comparisons, or create a bounded NUL-terminated copy before using strcmp()/strlen().
    rc = ssh2_get_string(decrypted, (unsigned char **)&buf, NULL);
    if(rc || !buf) {
        rc = ssh2_err(session, LIBSSH2_ERROR_PROTO,
                      "Public key type in decrypted key data not found");
        goto cleanup;

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.

Related:

via #2426 (review)

Pull request overview

This PR updates the WinCNG ECDSA private-key parsing path to use the newer internal API that returns char * buffers, removing the need for an (unsigned char **)&keytype pointer cast in wcng_ecdsa_new_private_parse().

Changes:

  • Replace ssh2_get_string(... (unsigned char **)&keytype ...) with ssh2_get_chars(...) when reading the ECDSA key type.
Comments suppressed due to low confidence (1)

src/wincng.c:2370

  • ssh2_get_chars() (like ssh2_get_string()) returns a length-delimited SSH “string” that is not NUL-terminated, but wcng_ecdsa_curve_type_from_name() uses strcmp(). This can read past the end of the keytype field (UB / potential crash) when parsing OpenSSH private key blobs. Consider NUL-terminating a temporary copy before calling wcng_ecdsa_curve_type_from_name(), or changing the helper to accept a length and use memcmp().
    result = ssh2_get_chars(&data_buffer, &keytype, &keytype_len);
    if(result != LIBSSH2_ERROR_NONE)
        goto cleanup;

    result = wcng_ecdsa_curve_type_from_name(keytype, &curve_type);

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

@vszakats vszakats Jul 24, 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.

@vszakats vszakats Jul 24, 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.

mbedtls.c:    if(ssh2_get_chars(decrypted, &name, NULL))
openssl.c:    rc = ssh2_get_chars(decrypted, &buf, NULL);
openssl.c:    rc = ssh2_get_chars(decrypted, &buf, NULL);
pem.c:    if(ssh2_get_chars(&decoded, &ciphername, &tmp_len) ||
pem.c:    if(ssh2_get_chars(&decoded, &kdfname, &tmp_len) ||
wincng.c:    result = ssh2_get_chars(&data_buffer, &keytype, &keytype_len);

Copilot AI review requested due to automatic review settings July 24, 2026 00:12

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 14 out of 14 changed files in this pull request and generated 7 comments.

Comments suppressed due to low confidence (4)

src/packet.c:740

  • Casting &message/&language (type char **) to unsigned char ** for ssh2_get_string() is undefined behavior. Read into a temporary unsigned char * and then assign to the char * variables.
                ssh2_get_string(&buf, (unsigned char **)&message,
                                &message_len);
                ssh2_get_string(&buf, (unsigned char **)&language,
                                &language_len);

src/packet.c:795

  • Casting &message/&language (type char **) to unsigned char ** for ssh2_get_string() is undefined behavior. Use a temporary unsigned char * and then assign to the char * variables.
                    ssh2_get_string(&buf, (unsigned char **)&message,
                                    &message_len);
                    ssh2_get_string(&buf, (unsigned char **)&language,
                                    &language_len);

src/openssl.c:3466

  • Casting &buf (a char **) to unsigned char ** for ssh2_get_string() is undefined behavior. Read into a temporary unsigned char * and then assign to buf.
    rc = ssh2_get_string(decrypted, (unsigned char **)&buf, NULL);

src/hostkey.c:652

  • Casting &domain (a char **) to unsigned char ** for ssh2_get_string() is undefined behavior. Read into a temporary unsigned char * and then assign to domain.
    if(ssh2_get_string(&buf, (unsigned char **)&domain, &len) || len != 8)
        return -1;

Comment thread src/userauth_kbd_packet.c Resolved
Comment thread src/pem.c Resolved
Comment thread src/packet.c Resolved
Comment thread src/mbedtls.c Resolved
Comment thread src/openssl.c Resolved
Comment thread src/hostkey.c Resolved
Comment thread src/kex.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 11 out of 11 changed files in this pull request and generated no new comments.

Comments suppressed due to low confidence (2)

src/openssl.c:3369

  • ssh2_get_string() returns a pointer/length slice that is not NUL-terminated (see ssh2_get_string() in src/misc.c). Here buf is treated as a C string via strcmp() / strlen() (also indirectly in ossl_ecdsa_curve_type_from_name()), which can read past the end of the SSH string and into subsequent decrypted data (OOB read) for malformed inputs. Capture the returned length and either compare using length-bounded logic (len + memcmp/strncmp) or copy the type into a bounded, NUL-terminated buffer before calling any C-string APIs.

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

    rc = ssh2_get_string(decrypted, (unsigned char **)&buf, NULL);
    if(rc || !buf) {
        rc = ssh2_err(session, LIBSSH2_ERROR_PROTO,
                      "Public key type in decrypted key data not found");
        goto cleanup;
    }

src/openssl.c:3470

  • Same issue as above: buf comes from ssh2_get_string() and is not NUL-terminated, but is compared with strcmp(). For malformed inputs this can cause OOB reads. Capture the string length and use length-bounded comparisons, or create a bounded NUL-terminated copy before using strcmp()/strlen().
    rc = ssh2_get_string(decrypted, (unsigned char **)&buf, NULL);
    if(rc || !buf) {
        rc = ssh2_err(session, LIBSSH2_ERROR_PROTO,
                      "Public key type in decrypted key data not found");
        goto cleanup;

vszakats added a commit that referenced this pull request Jul 24, 2026
Also use it from `ssh2_match_string()` to reduce casts.

Apparently casting the return pointer of `ssh2_get_string()` buffer is
frowned upon, though existing practice and not completelely clear if UB
or not.

Current practice (with two exceptions, now reduced to one in WinCNG
code) is to declare the return buffer as `unsigned char *`, then cast
that result everywhere on use. It results in excessive casts. The
frowned-upon alternative to avoid this, is to declare as `char *` and
pass it to `ssh2_get_string()` as `(unsigned char **)&data`. This new
API avoid this, and allows to declare as `char *data`, retrieve it
without cast, and use it without casts too.

Ref: #2420
Ref: a7d05f9 #2422

Closes #2424
vszakats added 6 commits July 24, 2026 14:23
This reverts commit 1d5b950.
This reverts commit 99f1a1f2f3e2ce3bc2f3de4d8f4f6cde10aac5da.
Copilot AI review requested due to automatic review settings July 24, 2026 12:23

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 12 out of 12 changed files in this pull request and generated 3 comments.

Comment thread src/mbedtls.c Resolved
Comment thread src/packet.c Resolved
Comment thread src/openssl.c Resolved
Copilot AI review requested due to automatic review settings July 24, 2026 12:39

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 12 out of 12 changed files in this pull request and generated 1 comment.

Comment thread src/packet.c Resolved
Copilot AI review requested due to automatic review settings July 24, 2026 12:43

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 12 out of 12 changed files in this pull request and generated no new comments.

Copilot AI review requested due to automatic review settings July 24, 2026 12:48
@vszakats vszakats closed this in 74a09eb Jul 24, 2026
@vszakats
vszakats deleted the casts2 branch July 24, 2026 12:57

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 12 out of 12 changed files in this pull request and generated no new comments.

Comments suppressed due to low confidence (7)

src/pem.c:468

  • ssh2_get_chars() returns a length-delimited SSH string that is not NUL-terminated (see ssh2_get_chars() in src/misc.c). Using strcmp() on ciphername/kdfname can read past the end of the field for malformed inputs. Use length-bounded comparisons based on the SSH string length.
    if((!passphrase || strlen(passphrase) == 0) &&
       strcmp(ciphername, "none")) {
        /* passphrase required */

src/openssl.c:3381

  • ssh2_get_chars() returns a non-NUL-terminated SSH string, but buf is compared with strcmp(). For malformed key blobs this can trigger out-of-bounds reads. Use length-bounded comparisons based on the SSH string length (the 4 bytes preceding buf).
    if(!strcmp("ssh-ed25519", buf) &&
       (!want_method || !strcmp("ssh-ed25519", want_method)))
        rc = ossl_ed25519_openssh_priv_to_pubkey(session, decrypted,

src/openssl.c:3397

  • buf returned by ssh2_get_chars() is a length-delimited field and not NUL-terminated, but this code uses strcmp() for method dispatch. Replace with length-bounded comparisons to avoid OOB reads on malformed key blobs.
    if(!strcmp("ssh-rsa", buf) &&
       (!want_method || !strcmp("ssh-rsa", want_method)))
        rc = ossl_rsa_openssh_priv_to_pubkey(session, decrypted,

src/openssl.c:3418

  • ossl_ecdsa_curve_type_from_name() uses strlen()/strcmp() and therefore requires a NUL-terminated input, but buf comes from ssh2_get_chars() and is not NUL-terminated. Dispatch on the curve name using the SSH string length and memcmp() (and set type accordingly) to avoid out-of-bounds reads on malformed input.
    else if(ossl_ecdsa_curve_type_from_name(buf, &type) == 0 &&
            (!want_method || !strcmp("ssh-ecdsa", want_method)))

src/openssl.c:3488

  • In ssh2_sk_pubkey(), buf is returned by ssh2_get_chars() and is not NUL-terminated, but is compared using strcmp(). Use the SSH string length and memcmp() to avoid OOB reads when parsing malformed key blobs.
    if(!strcmp("[email protected]", buf)) {
        *algorithm = LIBSSH2_HOSTKEY_TYPE_ED25519;
        rc = ossl_ed25519_sk_openssh_priv_to_pubkey(session, decrypted, method,

src/mbedtls.c:1038

  • ssh2_get_chars() returns a length-delimited string that is not NUL-terminated, but mbed_ecdsa_curve_type_from_name() uses strlen()/strcmp(). This can read past the end of the field for malformed OpenSSH key blobs. Use the SSH string length and memcmp() instead of passing the slice to string APIs.
    if(ssh2_get_chars(decrypted, &name, NULL))
        goto failed;

    if(mbed_ecdsa_curve_type_from_name(name, &type))
        goto failed;

src/pem.c:510

  • ciphername comes from ssh2_get_chars() and is not NUL-terminated, so strcmp(ciphername, "none") and the method selection loop can read past the end of the field for malformed inputs. Compare using the SSH string length (and ensure the ciphername length matches the candidate method name length) before calling memcmp().
    if(ciphername && strcmp(ciphername, "none")) {
        const struct crypt_method **all_methods, *cur_method;

vszakats added a commit to vszakats/libssh2 that referenced this pull request Jul 24, 2026
To make sure readers expecting a null-terminated string do not read past
the decoded buffer.

"`ciphername`/`kdfname` (in `pem_parse_data_openssh()`) are obtained via
`ssh2_get_string()` from the base64-decoded key blob and later compared
with `strcmp()`. The decoded buffer from `ssh2_base64_decode()` is not
NUL-terminated, so these `strcmp()` calls can read past the end of the
allocation if an attacker crafts lengths such that no `\0` occurs before
the buffer end. NUL-terminate the decoded buffer immediately after
decoding to make later string comparisons bounded by the allocation."

Reported by Copilot
Bug: libssh2#2420 (comment)
Ref: 0fcb662 libssh2#2403
vszakats added a commit to vszakats/libssh2 that referenced this pull request Jul 24, 2026
To make sure readers expecting a null-terminated string do not read past
the decoded buffer.

"`ciphername`/`kdfname` (in `pem_parse_data_openssh()`) are obtained via
`ssh2_get_string()` from the base64-decoded key blob and later compared
with `strcmp()`. The decoded buffer from `ssh2_base64_decode()` is not
NUL-terminated, so these `strcmp()` calls can read past the end of the
allocation if an attacker crafts lengths such that no `\0` occurs before
the buffer end. NUL-terminate the decoded buffer immediately after
decoding to make later string comparisons bounded by the allocation."

Reported by Copilot
Bug: libssh2#2420 (comment)
Ref: 0fcb662 libssh2#2403
vszakats added a commit that referenced this pull request Jul 24, 2026
…arsing

Before this patch some checks were using `strcmp()` on received/read
buffers that may not necessarily have a null-terminator. Fix by always
using the buffer length returned by the buffer reader, compare this
length with the expected one, and use `memcmp()` to verify the content.

When reading ECDSA/ED25519 OpenSSH-formatted keys in
`mbed_parse_openssh_key()`, `ossl_key_from_openssh()`, OpenSSL's
`ssh2_sk_pubkey()`, `pem_parse_data_openssh()`,
`wcng_ecdsa_new_private_parse()`.

Introduce `SSH2_IS_LITERAL()` macro to hide the delicate logic of
comparing a non-null-terminated memory buffer with a string literal.

Reported by Copilot
Bug: #2420 (comment)
Bug: #2420 (review)
Bug: #2426 (review)
Bug: #2420 (comment)
Bug: #2420 (comment)
Ref: 0fcb662 #2403

Closes #2421
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