Skip to content

Infinite loop in _libssh2_pem_parse_memory() when END marker follows BEGIN immediately (CWE-835) #2013

Closed

Description

@afldl

GitHub Issue — libssh2 Infinite Loop in PEM Parser (CWE-835)

Title: Infinite Loop in _libssh2_pem_parse_memory() When PEM End Marker Follows Begin Marker Immediately (CWE-835)

CWE

CWE-835: Loop with Unreachable Exit Condition (Infinite Loop)

Affected Versions

libssh2 <= 1.11.1 (all versions with _libssh2_pem_parse_memory() / libssh2_knownhost_readline())

Description

Summary

_libssh2_pem_parse_memory() in pem.c enters an infinite loop when parsing PEM data where the -----END ...----- marker directly follows the -----BEGIN ...----- marker (no base64 data between them). The function also loops infinitely when the PEM data does not contain the end marker at all and readline_memory() returns empty lines after data exhaustion.

Vulnerable Component

  • File: src/pem.c:244-268 (_libssh2_pem_parse_memory)
  • Trigger path: libssh2_userauth_publickey_frommemory() → _libssh2_pem_parse_memory()
  • Also affects: Any API that loads PEM private keys (RSA, DSA, EC, PKCS#8)

Root Cause

The function has two loops:

First loop (lines 184-193) — searches for headerbegin. Has if(!*line) break; at line 191, correctly exits on empty line.

Second loop (lines 244-268) — accumulates base64 and searches for headerend. Missing the !*line check. Between the two loops, at line 195, a readline_memory() call consumes the first line after headerbegin. If that line IS the headerend marker, it is consumed but never compared to headerend. The second loop then reads subsequent lines looking for headerend which was already consumed, creating an infinite loop.

// pem.c:195-268
if(readline_memory(line, LINE_SIZE, filedata, filedata_len, &off)) {
    return -1;  // reads first line after BEGIN — could be the END marker!
}

// ... encrypted key handling skipped ...

*line = '\0';

do {
    if(*line) {
        // accumulate base64...
    }
    *line = '\0';
    if(readline_memory(line, LINE_SIZE, filedata, filedata_len, &off)) {
        ret = -1;
        goto out;
    }
} while(strcmp(line, headerend) != 0);  // BUG: no break on empty line

Additionally, readline_memory() (line 71-94) always returns 0 (success) and always increments *filedata_offset by 1 (line 92), even after data exhaustion. This means after the input is consumed, every call returns an empty line with the offset incrementing forever. The second loop's strcmp("", headerend) never matches, and without a !*line check, the loop never exits.

Attack Vector

A remote attacker can trigger this by providing a malformed SSH private key file. Applications that load SSH keys from untrusted sources (e.g., SSH clients reading keys from a compromised filesystem, or server applications accepting key uploads) will hang indefinitely.

PoC — 2-byte input triggers infinite loop via public API:

// Craft a PEM file with no base64 between BEGIN and END
const char *pem = "-----BEGIN RSA PRIVATE KEY-----\n"
                  "-----END RSA PRIVATE KEY-----\n";
// Or simply any data without the END marker that starts with the BEGIN marker

Impact

  • Denial of Service: Thread/process hangs indefinitely consuming CPU
  • No memory corruption: This is a logic bug, not a memory safety issue
  • No information leak: No data is exposed

Steps to Reproduce

# Build libssh2 with ASAN
git clone https://github.com/libssh2/libssh2.git && cd libssh2
mkdir build && cd build
cmake .. -DCMAKE_C_COMPILER=clang \
  -DCMAKE_C_FLAGS="-g -fsanitize=address -fno-omit-frame-pointer -O1" \
  -DCMAKE_BUILD_TYPE=Debug
make -j$(nproc)

# Create PoC — PEM with empty body
printf '-----BEGIN RSA PRIVATE KEY-----\n-----END RSA PRIVATE KEY-----\n' > /tmp/poc.pem

# Compile test program
cat > test.c << 'EOF'
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libssh2.h>
int main(int argc, char **argv) {
    FILE *f = fopen(argv[1], "rb");
    fseek(f, 0, SEEK_END); long sz = ftell(f); fseek(f, 0, SEEK_SET);
    char *buf = malloc(sz);
    fread(buf, 1, sz, f); fclose(f);
    buf[sz-1] = '\0';
    LIBSSH2_SESSION *session = libssh2_session_init();
    // This will hang forever:
    libssh2_userauth_publickey_frommemory(session, "user", 4,
                                           buf, sz, buf, sz, "");
    libssh2_session_free(session);
    free(buf);
    return 0;
}
EOF
clang -g -fsanitize=address -fno-omit-frame-pointer -O1 test.c \
  -I../include src/libssh2.a -lssl -lcrypto -o test

timeout 5 ./test /tmp/poc.pem
# Result: timeout after 5 seconds — process is hung in infinite loop

Suggested Fix

Add if(!*line) { ret = -1; goto out; } after the readline_memory call at line 264, matching the pattern in the first loop:

--- a/src/pem.c
+++ b/src/pem.c
@@ -262,6 +262,11 @@ int _libssh2_pem_parse_memory(LIBSSH2_SESSION *session,
         if(readline_memory(line, LINE_SIZE, filedata, filedata_len, &off)) {
             ret = -1;
             goto out;
         }
+        if(!*line) {
+            ret = -1;
+            goto out;
+        }
     } while(strcmp(line, headerend) != 0);

Additionally, readline_memory() should detect end-of-data and return a non-zero value instead of always returning 0, to prevent other callers from having the same issue.

Credit

Discovered through ASAN-guided fuzzing with the PathDiff differential fuzzing framework.

References

Activity

  1. vszakats commented on Jun 10, 2026

    @vszakats
    Member

    This looks to have been fixed earlier via:
    141b035 #1746

    It also doesn't reproduce with current master.

  2. vszakats commented on Jun 10, 2026

    @vszakats
    Member

    Thanks for reporting, closing this as already fixed. If it (or a variation) still happens
    in current master, feel free to reopen or open a new issue.

  3. afldl commented on Jun 10, 2026

    @afldl
    Author

    Thanks for the pointer to #1746. That PR did fix the first loop (the one searching for headerbegin) by adding the if(!*line) break guard.

    However, the second loop — the one that accumulates base64 and looks for headerend — still has the same problem. On current master (src/pem.c lines 243-267):

        do {
            if(*line) {
                /* accumulate base64 */
            }
    
            *line = '\0';
    
            if(readline_memory(line, LINE_SIZE, filedata, filedata_len, &off)) {
                ret = -1;
                goto out;
            }
        } while(strcmp(line, headerend));

    No !*line check here. readline_memory() still always returns 0 and increments off unconditionally, so once the input is consumed, every call returns an empty string with off ticking up forever. strcmp("", headerend) never matches.

    The PoC from the report (-----BEGIN RSA PRIVATE KEY-----\n-----END RSA PRIVATE KEY-----\n) hits this path because the END marker gets consumed by the readline_memory call between the two loops (line 194), and the second loop never sees it.

    Could you re-check with that specific input on master?

  4. vszakats commented on Jun 11, 2026

    @vszakats
    Member

    It may be due to the report and repro code using OpenSSL, but
    OpenSSL builds don't use this code path. Seems to need wincng.

    I could replicate with an insolated example.

    edit: I also wonder why though readline_memory() result is
    checked, it's always returning success.

  5. vszakats commented on Jun 11, 2026

    @vszakats
    Member

    @afldl Can you verify/retest with patch #2032?

  6. afldl commented on Jun 11, 2026

    @afldl
    Author

    ok

  7. added a commit that references this issue on Jun 11, 2026
    8e8e3fc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions