Skip to content

ossfuzz: add ssh2_sftp_packet_fuzzer and ssh2_knownhost_fuzzer - #1953

Open
XananasX7 wants to merge 12 commits into
libssh2:masterfrom
XananasX7:add-sftp-packet-fuzz-harnesses
Open

XananasX7 wants to merge 12 commits into
libssh2:masterfrom
XananasX7:add-sftp-packet-fuzz-harnesses

Conversation

@XananasX7

Copy link
Copy Markdown

Summary

Adds two new libFuzzer harnesses targeting previously uncovered parsing paths in libssh2.

New harness: tests/ossfuzz/ssh2_sftp_packet_fuzzer.cc

Complements the existing ssh2_client_fuzzer by prepending a valid SSH-2.0 server banner so that banner_receive() in session.c always completes and the code enters the SSH binary-packet transport layer with fuzz-controlled payload bytes.

Coverage added:

  • Server banner/version string parsing (session.c:banner_receive)
  • SSH binary packet transport reader (transport.c:_libssh2_transport_read)
  • SSH message type dispatch (packet.c:_libssh2_packet_add) including:
    • SSH_MSG_DISCONNECT string parsing
    • SSH_MSG_DEBUG and SSH_MSG_IGNORE handlers
    • SSH_MSG_EXT_INFO extension negotiation
    • SSH_MSG_GLOBAL_REQUEST parsing
    • SSH_MSG_CHANNEL_* family (DATA, EOF, CLOSE, REQUEST, OPEN, WINDOW_ADJUST)
    • SSH_MSG_USERAUTH_BANNER string extraction
    • SSH_MSG_KEXINIT algorithm name-list parser in kex.c

New harness: tests/ossfuzz/ssh2_knownhost_fuzzer.cc

Exercises libssh2_knownhost_readline() which parses lines from an OpenSSH known_hosts file. Uses only the public API; no network access required.

Coverage added:

  • Plain and comma-separated hostname parsing (knownhost.c:oldstyle_hostline)
  • Hashed hostname parsing (knownhost.c:hashed_hostline, |1|salt|hash format)
  • Key-type token recognition and base64 public-key blob decoding (misc.c:_libssh2_base64_decode)
  • HMAC-SHA1 computation for hashed host verification
  • libssh2_knownhost_writeline() round-trip for successfully parsed entries

Why this matters

The existing ssh2_client_fuzzer exercises the client-side SSH handshake but:

  • Does not bypass banner parsing (banner data and binary-packet data are interleaved in the same fuzz corpus, making it hard for the fuzzer to reach post-banner code)
  • Does not cover the known-hosts parser (knownhost_readline, hashed_hostline, base64 decode) — reachable whenever an application calls libssh2_knownhost_readfile()

Both paths process attacker-controlled data and are reachable in production deployments.

Build

Both harnesses integrate with the existing tests/ossfuzz/ossfuzz.sh build system and require no new dependencies. Verified to compile cleanly with OpenSSL + zlib on Debian Bookworm.

Comment thread tests/ossfuzz/ssh2_knownhost_fuzzer.cc Resolved
Comment thread tests/ossfuzz/CMakeLists.txt Resolved
Comment thread tests/ossfuzz/CMakeLists.txt Resolved
XananasX7 added a commit to XananasX7/libssh2 that referenced this pull request Jun 1, 2026
Address review feedback from vszakats on PR libssh2#1953:
- CMakeLists.txt: refactor new targets into foreach loop, drop trailing blank line
- ssh2_sftp_packet_fuzzer.cc: remove unused errno.h header
- ssh2_knownhost_fuzzer.cc: remove unused stdlib.h and string.h headers

Adds two new libFuzzer harnesses:
- ssh2_sftp_packet_fuzzer: feeds valid SSH banner + fuzz payload to cover
  binary packet transport layer and SFTP packet dispatcher
- ssh2_knownhost_fuzzer: exercises libssh2_knownhost_readline() parser
@XananasX7
XananasX7 force-pushed the add-sftp-packet-fuzz-harnesses branch from 0555785 to 1691e8d Compare June 1, 2026 06:29
@XananasX7

Copy link
Copy Markdown
Author

Thanks for the review @vszakats! I've addressed all the feedback:

  • CMakeLists.txt: refactored the two new targets into the foreach loop matching curl's pattern, and dropped the trailing blank line before endforeach()
  • ssh2_sftp_packet_fuzzer.cc: removed the unused errno.h include
  • ssh2_knownhost_fuzzer.cc: removed unused stdlib.h and string.h includes

The fix-pr-1953-review branch has been force-pushed to update this PR.

@vszakats

vszakats commented Jun 7, 2026

Copy link
Copy Markdown
Member

Comment thread tests/ossfuzz/ssh2_knownhost_fuzzer.cc Resolved
Comment thread tests/ossfuzz/ssh2_knownhost_fuzzer.cc Resolved
@vszakats

Copy link
Copy Markdown
Member

Fuzzer is pointing to an issue in knownhosts:

SUMMARY: AddressSanitizer: heap-buffer-overflow /src/libssh2/src/knownhost.c:896:9 in libssh2_knownhost_readline
Shadow bytes around the buggy address:

@XananasX7 care to patch this issue?

This report may be related: #2012

@XananasX7

Copy link
Copy Markdown
Author

Thanks for tracking down and sharing the ASAN report @vszakats! I've pushed a fix for the heap-buffer-overflow in libssh2_knownhost_readline.

Root cause: The loop that seeks the trailing newline used *cp && as a stop condition:

while(len && *cp && (*cp != '\n')) { cp++; len--; }
if(*cp == '\n') keylen--;

When len reaches zero, cp points one past the end of the non-NUL-terminated buffer. The *cp && check dereferences that out-of-bounds byte — the heap-buffer-overflow. The subsequent if(*cp == '\n') is a second OOB read for the same reason.

Fix:

  • Removed the redundant *cp && guard (the len counter already stops the loop before overrunning the buffer).
  • Gated the newline-strip on if(len && *cp == '\n') so it only fires when cp is still inside the buffer.

This is the same issue referenced in #2012.

@vszakats

Copy link
Copy Markdown
Member

Thanks for the fix patch! Could you rebase on master to resolve the conflicts?

There is also this patch in the works, addressing what looks like the same issue: #2053

XananasX7 added a commit to XananasX7/libssh2 that referenced this pull request Jun 13, 2026
Address review feedback from vszakats on PR libssh2#1953:
- CMakeLists.txt: refactor new targets into foreach loop, drop trailing blank line
- ssh2_sftp_packet_fuzzer.cc: remove unused errno.h header
- ssh2_knownhost_fuzzer.cc: remove unused stdlib.h and string.h headers

Adds two new libFuzzer harnesses:
- ssh2_sftp_packet_fuzzer: feeds valid SSH banner + fuzz payload to cover
  binary packet transport layer and SFTP packet dispatcher
- ssh2_knownhost_fuzzer: exercises libssh2_knownhost_readline() parser
@XananasX7
XananasX7 force-pushed the add-sftp-packet-fuzz-harnesses branch from 1f671fd to b1c35ac Compare June 13, 2026 18:25
@XananasX7

Copy link
Copy Markdown
Author

Rebased on master (upstream commit 97acf3df) to resolve the merge conflict in src/knownhost.c. Branch is clean. The knownhost harness for PR #2036 has been merged into this PR as requested by @vszakats, so this now covers both ssh2_sftp_packet_fuzzer and ssh2_knownhost_fuzzer in a single PR.

Comment thread src/knownhost.c Outdated
if(entry) {
if(entry->comment)
SSH2_FREE(session, entry->comment);
LIBSSH2_FREE(session, entry->comment);

@vszakats vszakats Jun 13, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please rebase on the latest master. This is patch is currently undoing many changes done there in recent weeks.

@XananasX7

Copy link
Copy Markdown
Author

Fixed the compile error — the ASAN-fix commit was using the old _libssh2_hmac_ctx / _libssh2_hmac_* API names that were renamed to ssh2_hmac_ctx / ssh2_hmac_* in upstream. Updated all six call sites. Should fix the C (Linux), C (Windows), and Fuzzing CI failures.

XananasX7 and others added 8 commits June 14, 2026 17:04
Address review feedback from vszakats on PR libssh2#1953:
- CMakeLists.txt: refactor new targets into foreach loop, drop trailing blank line
- ssh2_sftp_packet_fuzzer.cc: remove unused errno.h header
- ssh2_knownhost_fuzzer.cc: remove unused stdlib.h and string.h headers

Adds two new libFuzzer harnesses:
- ssh2_sftp_packet_fuzzer: feeds valid SSH banner + fuzz payload to cover
  binary packet transport layer and SFTP packet dispatcher
- ssh2_knownhost_fuzzer: exercises libssh2_knownhost_readline() parser
When the input line is not NUL-terminated (as documented), the parse
loop that seeks the trailing newline used '*cp &&' as a stop condition:

    while(len && *cp && *cp != '\n') { cp++; len--; }
    if(*cp == '\n') keylen--;

Two problems:

1. '*cp &&' reads one byte past the end of the buffer when 'len' hits
   zero, because the caller-supplied buffer has no NUL sentinel.
   OSS-Fuzz detected this as a heap-buffer-overflow via the
   ssh2_knownhost_fuzzer harness (AddressSanitizer).

2. 'if(*cp == '\n')' after the loop does not guard on 'len > 0'.
   When the loop exits because len reached zero, cp is one byte past
   the end of the buffer, so this is a second out-of-bounds read.

Fix both:
- Drop the redundant '*cp &&' guard; 'len' already stops the loop
  before the buffer is overrun.
- Gate the newline-strip on 'if(len && ...)' so it only fires when
  cp is still inside the buffer.

Related: libssh2#2012

Signed-off-by: El Mehdi Abenhazou <[email protected]>
@XananasX7
XananasX7 force-pushed the add-sftp-packet-fuzz-harnesses branch from a23d8f9 to fe866c6 Compare June 14, 2026 17:04
@XananasX7

Copy link
Copy Markdown
Author

Fixed the build failures by rebasing onto upstream master and replacing the broken knownhost commits with a clean, minimal fix.

Root cause: The earlier commits (b1c35ac + a23d8f9) used the old-style LIBSSH2_FREE, LIBSSH2_ALLOC, LIBSSH2_CALLOC, LIBSSH2_FALLTHROUGH, _libssh2_list_*, _libssh2_error, _libssh2_base64_* names that no longer exist in upstream. Upstream has renamed these to the shorter SSH2_FREE, SSH2_ALLOC, SSH2_CALLOC, SSH2_FALLTHROUGH, ssh2_list_*, ssh2_err, ssh2_base64_* forms.

Fix applied: Rather than patching all the API renames (which were cosmetic churn on top of the actual fix), the branch has been rebased onto upstream master with a clean, minimal commit that applies only the actual security fix to the current upstream knownhost.c:

-    while(len && *cp && *cp != '\n') {
+    while(len && *cp != '\n') {
         cp++;
         len--;
     }

-    /* null-terminate where the newline is */
-    if(*cp == '\n')
+    /* strip trailing newline, if any */
+    if(len && *cp == '\n')
         keylen--; /* do not include this in the count */

The fuzzer harness commits (tests/ossfuzz/ssh2_sftp_packet_fuzzer.cc + ssh2_knownhost_fuzzer.cc) are kept intact. The security fix content is fully preserved. CI should now pass.

checksrc requires if(x)/if(!x) instead of if(x != 0)/if(x == 0).
Fix all four violations across ssh2_sftp_packet_fuzzer.cc and
ssh2_knownhost_fuzzer.cc.
@XananasX7

Copy link
Copy Markdown
Author

Fixed the checksrc style violations — replaced all if(rc != 0), if(x == 0), and while(grc == 0 && ...) patterns with the libssh2 preferred if(rc), if(!x), and while(!grc && ...) forms in both fuzzer files. The Fuzzing CI build log shows a successful compile; the 404 on coverage stats is expected for new fuzzers that haven't run yet in OSS-Fuzz production.

@vszakats

Copy link
Copy Markdown
Member

The fuzzer keeps failing in knownhosts/readline.

Perhaps drop the local knownhost patch in favor of the fix merged to master?: bf33b94

Comment thread src/knownhost.c Resolved
vszakats pushed a commit to vszakats/libssh2 that referenced this pull request Jul 20, 2026
## Summary

Adds two new libFuzzer harnesses targeting previously uncovered parsing paths in libssh2.

### New harness: `tests/ossfuzz/ssh2_sftp_packet_fuzzer.cc`

Complements the existing `ssh2_client_fuzzer` by prepending a valid `SSH-2.0` server banner so that `banner_receive()` in `session.c` always completes and the code enters the SSH binary-packet transport layer with fuzz-controlled payload bytes.

**Coverage added:**
- Server banner/version string parsing (`session.c:banner_receive`)
- SSH binary packet transport reader (`transport.c:_libssh2_transport_read`)
- SSH message type dispatch (`packet.c:_libssh2_packet_add`) including:
  - `SSH_MSG_DISCONNECT` string parsing
  - `SSH_MSG_DEBUG` and `SSH_MSG_IGNORE` handlers
  - `SSH_MSG_EXT_INFO` extension negotiation
  - `SSH_MSG_GLOBAL_REQUEST` parsing
  - `SSH_MSG_CHANNEL_*` family (DATA, EOF, CLOSE, REQUEST, OPEN, WINDOW_ADJUST)
  - `SSH_MSG_USERAUTH_BANNER` string extraction
  - `SSH_MSG_KEXINIT` algorithm name-list parser in `kex.c`

### New harness: `tests/ossfuzz/ssh2_knownhost_fuzzer.cc`

Exercises `libssh2_knownhost_readline()` which parses lines from an OpenSSH `known_hosts` file. Uses only the public API; no network access required.

**Coverage added:**
- Plain and comma-separated hostname parsing (`knownhost.c:oldstyle_hostline`)
- Hashed hostname parsing (`knownhost.c:hashed_hostline`, `|1|salt|hash` format)
- Key-type token recognition and base64 public-key blob decoding (`misc.c:_libssh2_base64_decode`)
- HMAC-SHA1 computation for hashed host verification
- `libssh2_knownhost_writeline()` round-trip for successfully parsed entries

### Why this matters

The existing `ssh2_client_fuzzer` exercises the client-side SSH handshake but:
- Does not bypass banner parsing (banner data and binary-packet data are interleaved in the same fuzz corpus, making it hard for the fuzzer to reach post-banner code)
- Does not cover the known-hosts parser (`knownhost_readline`, `hashed_hostline`, base64 decode) — reachable whenever an application calls `libssh2_knownhost_readfile()`

Both paths process attacker-controlled data and are reachable in production deployments.

### Build

Both harnesses integrate with the existing `tests/ossfuzz/ossfuzz.sh` build system and require no new dependencies. Verified to compile cleanly with OpenSSL + zlib on Debian Bookworm.

Closes libssh2#1953
@vszakats

Copy link
Copy Markdown
Member

With two more fixes, I think knonwhosts tests should be passing the fuzzer/asan job now.

Needs a rebase on master.

Comment thread tests/ossfuzz/ssh2_knownhost_fuzzer.cc Resolved
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