Skip to content

pem: merge file/blob codepaths - #2388

Closed
vszakats wants to merge 40 commits into
libssh2:masterfrom
vszakats:pemmerge2
Closed

vszakats wants to merge 40 commits into
libssh2:masterfrom
vszakats:pemmerge2

Conversation

@vszakats

@vszakats vszakats commented Jul 22, 2026 •

Copy link
Copy Markdown
Member

To further merge file/blob codepaths/behavior, and to reduce branching
at callers.

Also:

  • pem: add internal API ssh2_file_to_blob() to load a (PEM) file into
    memory. Use it internally.
    Make sure to null-terminate the returned blob, primarily for mbedTLS.
  • mbedtls, os400qc3: use ssh2_file_to_blob().
  • pem: fix to return LIBSSH2_ERROR_ALGO_UNSUPPORTED in
    ssh2_pem_parse() in no-MD5 builds (was: -1).
  • os400qc3: fix to scrub data before free in try_pem_load().

Note:

  • os400qc3: try_pem_load() has unique behavior of allowing multiple
    instances of private keys within a single file, but only when loading
    from a file. I could not positively confirm this to be valid/standard
    private file format, nor find a comment or commit message explaining
    the behavior. I've added (untested) support for this using the blob
    codepath, because the FILE * method is now gone from pem.c. It
    also seems one contributing factor why the file (vs blob) tracks are
    much different in this backend. After this patch, both could use
    ssh2_pem_parse() and possibly unify os400_pub_privkey_file/blob()
    and os400_rsa_new_priv_from_file/blob().

Follow-up to b560cb4 #2379
Follow-up to 6a95116 #2362
Follow-up to fe9442b #2359
Follow-up to 5b94157 #2354


  • openssl: try to untangle the different file/blob codepaths.
    e.g. in ssh2_rsa_new_priv(). → Separate PR.

Copilot AI review requested due to automatic review settings July 22, 2026 00:57
@vszakats
vszakats marked this pull request as draft July 22, 2026 00:58

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 consolidates PEM private key parsing from either a file (FILE*) or an in-memory blob into a single implementation, reducing duplicated logic across backends.

Changes:

  • Replaces ssh2_pem_parse_FILE() / ssh2_pem_parse_blob() with a unified ssh2_pem_parse() API.
  • Adds an internal helper to load a FILE* into a blob buffer for parsing.
  • Updates WinCNG, OS/400 QC3, and libgcrypt backends to call the unified PEM parser.

Reviewed changes

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

Show a summary per file
File Description
src/pem.c Introduces ssh2_pem_parse() and refactors file/blob PEM parsing into a unified path.
src/libssh2_priv.h Updates internal header prototypes to expose only the new unified PEM parsing API.
src/wincng.c Switches WinCNG private key loading to call ssh2_pem_parse().
src/os400qc3.c Switches OS/400 PEM parsing call sites to ssh2_pem_parse().
src/libgcrypt.c Switches libgcrypt RSA/DSA private key loading to ssh2_pem_parse() (but currently has an uninitialized FILE *fp bug).

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

Comment thread src/libgcrypt.c Resolved
Comment thread src/libgcrypt.c Resolved
Copilot AI review requested due to automatic review settings July 22, 2026 01:01

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

Comments suppressed due to low confidence (1)

src/libgcrypt.c:263

  • fp may be uninitialized when filename == NULL, but it is passed to ssh2_pem_parse() and later tested in if(fp) fclose(fp);. This is undefined behavior and can lead to crashes or closing an invalid pointer. Initialize fp to NULL so the blob codepath is safe.
    ret = ssh2_pem_parse(session, PEM_RSA_HEADER, PEM_RSA_FOOTER,
                         fp, blob, blob_len, passphrase,
                         &data, &datalen);
    if(fp)
        fclose(fp);

Copilot AI review requested due to automatic review settings July 22, 2026 01:52

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

Comment thread src/os400qc3.c Resolved
Comment thread src/os400qc3.c Resolved
Comment thread src/os400qc3.c Resolved
Comment thread src/os400qc3.c Resolved
Comment thread src/os400qc3.c Resolved
Comment thread src/os400qc3.c Resolved
Comment thread src/os400qc3.c Resolved
Copilot AI review requested due to automatic review settings July 22, 2026 02:19

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

Comments suppressed due to low confidence (1)

src/os400qc3.c:1993

  • try_pem_load() updates blob_offset incorrectly: ssh2_pem_parse() returns an offset relative to the provided slice (blob + blob_offset), but the code overwrites the absolute blob_offset with that relative value. This can cause the loop to re-parse the same region or skip incorrectly when multiple PEM objects are concatenated.
    while(blob_offset < blob_len) {
        ret = ssh2_pem_parse(session, header, trailer,
                             NULL, blob + blob_offset, blob_len - blob_offset,
                             passphrase,
                             &data, &datalen, &blob_offset);

Comment thread src/pem.c Resolved
Copilot AI review requested due to automatic review settings July 22, 2026 02:24

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

Comments suppressed due to low confidence (3)

src/os400qc3.c:1995

  • try_pem_load() uses blob_left for the loop condition, but calls ssh2_pem_parse() with blob_remain and decrements blob_remain afterwards. blob_remain is not declared here, which will not compile; even if renamed later, the loop would never make progress unless the same variable used in the condition is decremented.
    while(blob_left > 0) {
        ret = ssh2_pem_parse(session, header, trailer,
                             NULL, blob_pos, blob_remain,
                             passphrase,
                             &data, &datalen, &blob_offset);

src/pem.c:85

  • ssh2_file_to_blob() returns -1 when ssh2_fopen() fails but does not set a session error. This loses the specific failure reason for all new callers that rely on ssh2_file_to_blob()/ssh2_*pem_parse() (and some call sites may overwrite it with a misleading error).
    fp = ssh2_fopen(filename, "rb");
    if(!fp) {
        ret = ssh2_err(session, LIBSSH2_ERROR_FILE,

src/openssl.c:3537

  • On ssh2_openssh_pem_parse() failure this block unconditionally overwrites the session error with "Not an OpenSSH key file". With the new filename/blob merge, failures can now include file open/IO/alloc errors; overwriting them makes diagnosing failures harder and can be misleading.
    if(rc) {
        ssh2_err(session, LIBSSH2_ERROR_FILE, "Not an OpenSSH key file");
        return rc;
    }

Comment thread src/pem.c Resolved
Copilot AI review requested due to automatic review settings July 22, 2026 02:27

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

Comments suppressed due to low confidence (1)

src/os400qc3.c:1995

  • try_pem_load() uses blob_remain (undefined) instead of blob_left, which will not compile and also prevents the remaining-length counter from being updated correctly. This loop should pass the current remaining length to ssh2_pem_parse(), decrement the same variable after advancing blob_pos, and (defensively) break if blob_offset is 0 to avoid a potential infinite loop. Also free data on the early-success return to avoid leaking the decoded PEM buffer.
    while(blob_left > 0) {
        ret = ssh2_pem_parse(session, header, trailer,
                             NULL, blob_pos, blob_remain,
                             passphrase,
                             &data, &datalen, &blob_offset);

Copilot AI review requested due to automatic review settings July 22, 2026 02:34

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

Comment thread src/pem.c
Comment on lines 358 to 361
#else
ssh2_err(session, LIBSSH2_ERROR_ALGO_UNSUPPORTED,
"Unable to decrypt PEM, MD5 not enabled");
ret = -1;
goto out;

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 → #2390

Comment thread src/os400qc3.c Resolved
vszakats added a commit that referenced this pull request Jul 22, 2026
When processing encrypted PEM files.

Also: make sure to initialize returned pointer/length on fail.

Reported by Copilot
Bug: #2388 (comment)

Closes #2390
Copilot AI review requested due to automatic review settings July 22, 2026 08:54

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

Comment thread src/pem.c Resolved
Comment thread src/pem.c Resolved
Comment thread src/os400qc3.c Resolved
Comment thread src/os400qc3.c Resolved
Copilot AI review requested due to automatic review settings July 22, 2026 09:15
Copilot AI review requested due to automatic review settings July 22, 2026 09:38

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

Comments suppressed due to low confidence (2)

src/pem.c:173

  • ssh2_pem_parse() can be called with both filename == NULL and blob == NULL/blob_len == 0, but it currently dereferences blob via pem_readline() without validating inputs. Adding an early guard (similar to ssh2_openssh_pem_parse()) avoids a NULL dereference and ensures a consistent error is reported.
    *data = NULL;
    *datalen = 0;

    if(filename) {
        ret = ssh2_file_to_blob(session, filename, &filedata, &filedata_len);

src/pem.c:354

  • In the LIBSSH2_MD5_PEM disabled branch, ssh2_err(...) is called but its return value is not assigned to ret, so the function returns -1 instead of the specific error code. Assigning it keeps return codes consistent with other error paths in this function (e.g. unsupported algorithm).
#else
        ssh2_err(session, LIBSSH2_ERROR_ALGO_UNSUPPORTED,
                 "Unable to decrypt PEM, MD5 not enabled");
        goto out;

Copilot AI review requested due to automatic review settings July 22, 2026 09: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 7 out of 7 changed files in this pull request and generated 1 comment.

Comment thread src/mbedtls.c Resolved
Copilot AI review requested due to automatic review settings July 22, 2026 10: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

Copilot reviewed 7 out of 7 changed files in this pull request and generated 4 comments.

Comment thread src/pem.c Resolved
Comment thread src/pem.c Resolved
Comment thread src/pem.c Resolved
Comment thread src/os400qc3.c Resolved
Copilot AI review requested due to automatic review settings July 22, 2026 12:16

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

Comments suppressed due to low confidence (4)

src/pem.c:371

  • filedata holds the raw private-key file contents (loaded via ssh2_file_to_blob()), but it is freed without being scrubbed. This can leave key material in heap memory after parsing succeeds/fails.
    if(filedata)
        SSH2_FREE(session, filedata);

src/pem.c:797

  • When ssh2_openssh_pem_parse() loads a key from filename, filedata is freed without being scrubbed. Since this buffer contains raw private key material, it should be explicitly zeroed before freeing.
    if(filedata)
        SSH2_FREE(session, filedata);

src/os400qc3.c:2062

  • blob contains the full private-key file contents (PEM/DER) and is freed without being scrubbed. Since this is sensitive material, explicitly zero the buffer (including the extra NUL terminator added by ssh2_file_to_blob()) before freeing.
    SSH2_FREE(session, blob);

src/pem.c:180

  • ssh2_pem_parse() can be called with either a filename or a non-NULL blob+blob_len, but unlike ssh2_openssh_pem_parse() it does not validate that at least one source is provided. If it is ever called with filename == NULL and blob_len > 0 but blob == NULL, it will dereference a NULL pointer in pem_readline(). Add an explicit guard like the OpenSSH parser has.
    *data = NULL;
    *datalen = 0;

    if(filename) {
        ret = ssh2_file_to_blob(session, filename, &filedata, &filedata_len);
        if(ret)
            goto out;
        blob = filedata;
        blob_len = filedata_len;
    }

Comment thread src/os400qc3.c Resolved
Copilot AI review requested due to automatic review settings July 22, 2026 12:27

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

Comments suppressed due to low confidence (1)

src/pem.c:176

  • ssh2_pem_parse() dereferences blob inside pem_readline() without validating that a non-NULL blob was provided when filename is NULL. If a caller accidentally passes blob_len > 0 with blob == NULL (or otherwise violates the filename/blob contract), this will crash via a NULL dereference. ssh2_openssh_pem_parse() already defends against this case; it would be safer for ssh2_pem_parse() to do the same and return a proper libssh2 error instead of crashing.
    *data = NULL;
    *datalen = 0;

    if(filename) {

@vszakats vszakats closed this in 7bf902e Jul 22, 2026
@vszakats
vszakats deleted the pemmerge2 branch July 22, 2026 12:54
vszakats added a commit that referenced this pull request Jul 22, 2026
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