Skip to content

wincng: normalize fixed-width DH values before mpint encoding - #2583

Closed
Lv2dev wants to merge 5 commits into
libssh2:masterfrom
Lv2dev:codex/wincng-normalize-dh-mpints
Closed

Lv2dev wants to merge 5 commits into
libssh2:masterfrom
Lv2dev:codex/wincng-normalize-dh-mpints

Conversation

@Lv2dev

@Lv2dev Lv2dev commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • normalize fixed-width WinCNG bignums before SSH mpint serialization
  • apply the normalization to DH public values and DH/ECDH shared secrets
  • zero the removed tail bytes and add common bignum conversion tests

Problem

WinCNG returns DH public values and raw DH/ECDH shared secrets in fixed-width
buffers. The WinCNG bignum retained that buffer width as its numeric length.
When a value started with 0x00, libssh2 included the redundant byte in the
exchange hash even though RFC 4251 requires a canonical mpint representation.

The peer hashes the normalized integer, so the exchange hashes differ and a
valid server host-key signature is rejected. This appeared intermittently as
LIBSSH2_ERROR_KEY_EXCHANGE_FAILURE because it depends on the generated value.

The helper introduced here moves significant bytes to the start of the existing
allocation, explicitly clears the removed tail, and updates only the logical
length. It does not add an allocation or a new failure path.

Validation

  • scripts/checksrc-all.pl
  • MSVC Release build with the default WinCNG configuration
  • MSVC Release build with ENABLE_ECDSA_WINCNG=ON
  • test_simple in both configurations
  • WSL Clang/OpenSSL build with warnings as errors and project clang-tidy checks;
    test_simple passes
  • WSL Clang/libgcrypt and Clang/mbedTLS builds with warnings as errors;
    test_simple passes on each backend
  • earlier Windows connection investigation: 22,000 successful handshakes across default
    group exchange, group14, group16, and independent-process cases
    These connection runs were not repeated for the latest base update.

Reported-by: Dan Fandrich
Fixes #804
Ref: #2590 (tests)

@vszakats vszakats left a comment

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.

Can you say how did you stress test connections locally?

Comment thread src/wincng.c Resolved
Comment thread tests/test_simple.c Resolved
@Lv2dev

Lv2dev commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I pushed 34575bad to address both inline comments:

  • The helper is now file-local as static void wcng_bn_normalize() and is no longer declared in wincng.h.
  • The regression now goes through the common bignum API (ssh2_bn_init_from_bin(), ssh2_bn_from_bin(), ssh2_bn_bytes(), and ssh2_bn_to_bin()) and is enabled for every backend. It verifies that { 0, 0, 0x80, 0x42 } round-trips with the canonical two-byte magnitude { 0x80, 0x42 }.

Local checks after that change:

  • checksrc-all.pl: pass
  • MSVC Release, WinCNG: build + test_simple pass
  • MSVC Release, WinCNG with ENABLE_ECDSA_WINCNG=ON: build + test_simple pass
  • WSL GCC Release, OpenSSL: build + test_simple pass

For the connection stress testing, I used a local Docker OpenSSH server reached over loopback from a small Windows handshake driver linked to the MSVC WinCNG build. Every attempt created a fresh TCP socket and LIBSSH2_SESSION, set the requested KEX preference where applicable, ran libssh2_session_handshake(), recorded the result, and then discarded the session. Authentication and file transfer were not part of these measurements.

The unpatched WinCNG control failed intermittently in both serial and one-session-per-process runs, so concurrency was not required. Normalizing only the shared secret still left 41 failures in 10,000 handshakes; instrumentation on those remaining failures showed a redundant leading zero in the exported client public value. With both the public value and shared secret normalized, the runs completed as follows:

  • default/GEX: 10,000/10,000
  • forced group14: 4,000/4,000
  • forced group16: 4,000/4,000
  • fresh process per attempt: 4,000/4,000
  • total: 22,000/22,000 successful handshakes

The same local server path was also clean with the Windows OpenSSH client (2,000/2,000), and the WSL/OpenSSL control completed its tested KEX variants without failures.

The new upstream CI run is in progress. Please let me know if you would prefer the stress harness to be reduced into a repository test in a follow-up.

@vszakats

vszakats commented Sep 4, 2026

Copy link
Copy Markdown
Member

Thanks for the fixes! Just curious, are you real person or am I talking
to an LLM?

I think this is the moment when libssh2 would need to have WinCNG
tests in CI (again) to verify if this fixes this long-running problem. I have
an idea for this, which would also hit this specific issue, but so far had
no capacity to implement it.

If you have suggestions for a WnCNG CI test, I'd be useful to see it, yes.
Note, I may have strong opinions on an proposal like this.

Refs:
#804
#1023 (to be reverted if this fix works)
#2049
curl/curl#16781

@mback2k: Your thoughts on this fix proposal?

@Lv2dev

Lv2dev commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor Author

I'm a real person and the owner of this account. I'm a native Korean speaker and not fluent in English, so I use an LLM to translate my comments into English.

The investigation and patch were AI-assisted. The builds, stress runs, hashes, and CI results I reported are outputs from commands actually executed in my environment, not generated estimates. I make sure I understand the root cause and the purpose of each change, verify the technical claims with reproducible tests, and take responsibility for the submission.

I'd be happy to help restore WinCNG runtime coverage in CI. Since you already have an idea and may have strong preferences about the design, could you outline the topology and constraints you have in mind, such as the runner and SSH server arrangement, minimum KEX coverage, acceptable runtime, and whether retries should remain only as a temporary comparison? I'll review those constraints and the references you shared before preparing a focused follow-up proposal or writing code.

@vszakats

vszakats commented Sep 4, 2026 •

Copy link
Copy Markdown
Member

I'd be happy to help restore WinCNG runtime coverage in CI. Since you already have an idea and may have strong preferences about the design, could you outline the topology and constraints you have in mind, such as the runner and SSH server arrangement, minimum KEX coverage, acceptable runtime, and whether retries should remain only as a temporary comparison? I'll review those constraints and the references you shared before preparing a focused follow-up proposal or writing code.

Short history: We traditionally had WinCNG tests running in AppVeyor CI,
using Docker machines running in GHA and communicating via a tunnel
(with a help of an external server kindly provided by Marc Hörsken). Sadly,
this setup became unstable over time and doesn't work (reliably) anymore,
due to factors outside our control.

Preferably WinCNG tests should reuse the existing test infrastructure
and Docker to make them mirror the tests we do on Linux. It'd be nice to
avoid the complexities of the previous Windows setup and run Docker on
the same CI machine where the tests are running. Ideally we shall not use
3rd-party GitHub Actions, Powershell code and generally keep complexity
and maintenance overhead at minimum. Probably the best place to run this
would be GHA (as opposed to AppVeyor CI), due to parallelism, and better
expected performance (we lose the option to run tests on old Windows,
and old MSVC versions, which I think is OK.)

[ A long shot, and this isn't the goal within this PR, but I'd much prefer
not using Docker for tests if at all possible. It'd allow running them
locally on any platform, and also allow them to run on macOS (and other
non-Linux platforms) in CI. It'd also allow to dynamically build test keys.
sshd insisting on a valid local user/pw is an issue here I think. ]

As for my idea on running tests: In curl we do run libssh2 tests via curl's
test harness (runtests). It runs without Docker and also supports
Windows, and other platforms. It also reproduced this particular WinCNG
issue as flaky fails (for this reason, we had to disable these tests in curl CI).
Therefore my idea is to build curl (e.g. the latest stable, or perhaps the
latest master) in libssh2 CI using the latest libssh2 sources, and use
runtests limited to SCP/SFTP tests. These tests can be run against
MSYS2 sshd, the Windows built-in OpenSSH server, or a specific
MS/Windows build installed manually, curl CI has logic for these already.

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.

🟡 Changes recommended

The fallback DH path must also normalize successful results before encoding.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

Normalizes fixed-width WinCNG DH/ECDH values before SSH mpint serialization.

Changes:

  • Adds in-place bignum normalization.
  • Normalizes native DH/ECDH outputs.
  • Adds regression coverage for leading-zero handling.
File summaries
File Review
tests/test_simple.c Test does not exercise the affected WinCNG output path.
src/wincng.c Fallback DH public values remain unnormalized.
Review details

Suppressed comments (2)

src/wincng.c:3230

  • This handles only successful BCRYPT_KDF_RAW_SECRET derivation. On systems where that KDF returns STATUS_NOT_SUPPORTED (documented above as pre-Windows 10), execution jumps to the fallback at wincng.c:3249-3251, which returns the fixed-width wcng_bn_mod_exp() result without normalization. The original intermittent non-canonical shared-secret mpint therefore remains on the supported fallback path; normalize successful fallback results as well.
        wcng_bn_normalize(secret);

tests/test_simple.c:305

  • This test does not exercise the reported regression: the previous ssh2_bn_from_bin() implementation already removed leading zero bytes, so the test still passes if all three new normalization calls are reverted. Please cover a fixed-width value produced by the WinCNG DH/ECDH output path (including the updated logical length and cleared tail), so the test fails without this fix.
    if(ssh2_bn_from_bin(bn, fixed_width, sizeof(fixed_width))) {
  • Files reviewed: 2/2 changed files
  • Comments generated: 1
  • Review effort level: Balanced

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/wincng.c
memcpy(pub->bignum, (unsigned char *)dh_key_blob +
sizeof(*dh_key_blob) + 2 * dh_key_blob->cbKey,
dh_key_blob->cbKey);
wcng_bn_normalize(pub);

@mback2k mback2k left a comment

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.

This PR itself looks good to me and may finally fix the random issues we had, but of course this will require longer testing as the removed part in ssh2_bn_from_bin had the same purpose which is now replaced and generalized.

Comment thread src/wincng.c Outdated
if(!bn || !bn->bignum || !bn->length)
return;

while(offset + 1 < bn->length && !bn->bignum[offset])

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.

I think the conditions here should be switched around as the bignum being zero is the primary condition.

@mback2k mback2k left a comment

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 implement the requested changes.

@mback2k

mback2k commented Sep 4, 2026 •

Copy link
Copy Markdown
Member

I also agree with @vszakats regarding the long-term wishes for a better Windows testsuite, although I would really like to fix the AppVeyor CI, I currently have no time or clue how to do that. WSL could also be an option on GHA to run the Windows tests against a proper Linux-based OpenSSH server as the Windows-version is not completely compatible.

@Lv2dev

Lv2dev commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, @vszakats and @mback2k. I've pushed af506998 with the code and test updates:

  • Reordered the normalization loop conditions as requested.
  • Normalized both DH public values and shared secrets on the RSA-based fallback paths.
  • Expanded the common bignum cases and added native/fallback output tests, including logical lengths and cleared buffer tails. The helper remains file-local, and the common bignum test remains enabled across backends.

The native DH and P-256 ECDH shared-secret tests use fixed vectors. The native DH public-value check compares a fresh key with its CNG export, so detecting omitted normalization there depends on a leading-zero sample. The test itself does not retry or require such a sample. In local mutation checks, six omissions were detected on the first run; the native public-value omission was detected on the 33rd sample.

All 92 existing CI checks for this commit passed. The WinCNG SSH runtime job we discussed has not been added yet.

For that job, I propose building a pinned curl revision against this PR's WinCNG libssh2 on a GHA Windows x64 runner and running curl's SCP/SFTP tests. I'd first check the WSL/Linux OpenSSH option on the same runner against curl's harness and your constraints on setup complexity, third-party Actions, and PowerShell.

Would you prefer this CI work in this PR, or as a follow-up PR?

@vszakats

vszakats commented Sep 5, 2026 •

Copy link
Copy Markdown
Member

For that job, I propose building a pinned curl revision against this PR's WinCNG libssh2 on a GHA Windows x64 runner and running curl's SCP/SFTP tests. I'd first check the WSL/Linux OpenSSH option on the same runner against curl's harness and your constraints on setup complexity, third-party Actions, and PowerShell.

Just to clarify, the curl runtests method does not require or use WSL.

(edit: it might use it, but it seems to be a deep rabbit hole, which
has not been tried before, and with complexities. Since we have zero
tests now, the MSYS2 and the Microsoft port of OpenSSH seems to
be fine enough to know if WinCNG works at all.)

Would you prefer this CI work in this PR, or as a follow-up PR?

I think it'd be easier to handle in a separate PR, then rebase this one,
once we settled on it.

Comment thread tests/test_simple.c Outdated
rc |= test_ssh2_dh_native_normalization();
#if LIBSSH2_ECDSA
rc |= test_ssh2_ecdh_normalization(session);
#endif

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.

Can we avoid the backend-specific (esp. Windows-specific) code in tests?
Either test the primitives for all backends, or drop things from there that are
WinCNG-specific.

@vszakats

vszakats commented Sep 5, 2026 •

Copy link
Copy Markdown
Member

I also agree with @vszakats regarding the long-term wishes for a better Windows testsuite, although I would really like to fix the AppVeyor CI, I currently have no time or clue how to do that. WSL could also be an option on GHA to run the Windows tests against a proper Linux-based OpenSSH server as the Windows-version is not completely compatible.

I think the major issue with AppVeyor CI is that it makes the PR push cycles
take a long time. Even without tests, it used to take 45-60 minutes up until
a few month ago. With cuts and optimizations I could reduce this to 10 minutes
(half of this is waiting to for the machines to spin up), which made iteration
practical again, and ~matches the time a GHA cycle takes. Running tests there
would make it run slow again and working on libssh2 super time-consuming,
and painful. (Most users, myself included, also cannot cancel a job, so one
sometimes need to wait many hours till all the queued up tests complete;
when working on multiple PRs in parallel, and/or pushing to master at the same
time.)

GHA works much better in this regard, by running jobs in parallel, spinning
up machines faster, and there is an option to cancel jobs as a last resort.

To emulate pre-10 Windows versions (only offered by AppVeyor CI) we can
introduce an env to disable hasAlgDHwithKDF and test that codepath on
GHA.

@vszakats

vszakats commented Sep 5, 2026 •

Copy link
Copy Markdown
Member

@vszakats

vszakats commented Sep 5, 2026 •

Copy link
Copy Markdown
Member

With this PR applied as of e95a1ee,
there seems to be a intermittent hang:
https://github.com/libssh2/libssh2/actions/runs/33996868038/job/101388864311
(There is chance this just the baseline flakiness/hangs seen with runtests on Windows, or a pre-existing WinCNG-backend-specific issue)

Runs fine on the next run:
https://github.com/libssh2/libssh2/actions/runs/33997352596

@Lv2dev

Lv2dev commented Sep 6, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for testing this in #2590. I've pushed 50e26317 to remove the WinCNG-specific tests and buffer checks from test_simple.c, keeping the common bignum tests.

Comment thread tests/test_simple.c Resolved
Comment thread tests/test_simple.c Resolved
Comment thread tests/test_simple.c Resolved
vszakats added a commit that referenced this pull request Sep 7, 2026
…_from_bin()`

To better hide backend-specific differences and t bring the init
sub-steps (1. allocation, 2. conversion) close to each other.

Also:
- HACKING_CRYPTO.md: fix docs for `ssh2_bn_from_bin()` and
  `ssh2_bn_set_word()`.

Ref: #2583 (comment)

Closes #2594
@vszakats vszakats mentioned this pull request Sep 7, 2026
4 tasks done
Comment thread tests/test_simple.c Outdated
Comment on lines +319 to +325
ssh2_bn *bn = ssh2_bn_init_from_bin();

#ifndef LIBSSH2_LIBGCRYPT
if(!bn)
return 1;
#endif
if(ssh2_bn_from_bin(bn, tests[i].input, tests[i].length) ||

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

Suggested change
ssh2_bn *bn = ssh2_bn_init_from_bin();
#ifndef LIBSSH2_LIBGCRYPT
if(!bn)
return 1;
#endif
if(ssh2_bn_from_bin(bn, tests[i].input, tests[i].length) ||
ssh2_bn *bn = NULL;
if(ssh2_bn_from_bin(&bn, tests[i].input, tests[i].length) ||

Maybe this, to sync with master, aligning platforms.

Comment thread src/wincng.c Outdated
}
}

int ssh2_bn_from_bin(ssh2_bn *bn, const unsigned char *bin, size_t len)

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.

Suggested change
int ssh2_bn_from_bin(ssh2_bn *bn, const unsigned char *bin, size_t len)
int ssh2_bn_from_bin(ssh2_bn **bn, const unsigned char *bin, size_t len)

Needs a rebase on master for this and related changes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I've rebased onto the latest master and updated the WinCNG implementation and tests for the new ssh2_bn_from_bin() API in 7eaca5dd. The special initializer and libgcrypt-specific exception are removed.

All 92 CI checks passed. Thanks for simplifying the initialization API.

Trim redundant leading zero bytes from WinCNG DH public values and DH/ECDH shared secrets before SSH mpint serialization. Add a Windows regression test for normalization and zeroization.
Keep the WinCNG helper file-local and cover leading-zero normalization through the common bignum conversion API so the regression runs across crypto backends.
Apply leading-zero normalization to successful RSA-backed DH fallback
results before mpint encoding. Put the zero-byte condition first in
the normalization loop as requested in review.

Expand the common bignum conversion cases and check cleared buffer
tails. Exercise native DH and P-256 ECDH with fixed shared-secret
vectors, and compare fresh DH public values with their CNG exports.

Validation: test_simple passed with warnings as errors on MSVC WinCNG
with ECDSA off/on and on WSL OpenSSL. Seven individual normalization
or clearing mutations were detected; the native public-value mutation
needed a leading-zero random sample. checksrc also passed.
Lv2dev and others added 2 commits September 8, 2026 10:02
Keep the common bignum conversion cases and remove Windows-specific
fixtures, internal-buffer checks and zero-representation cases from the
shared test file, as requested in review.

Preserve libgcrypt initialization handling and leave the WinCNG
normalization implementation unchanged.
Start the common conversion test with a NULL bignum and pass its address
to the new ssh2_bn_from_bin() API. Let the backend perform allocation
and report failure, removing the special initializer and libgcrypt guard.
Keep the size comparison aligned with the upstream size_t return type.

Co-Authored-By: OpenAI Codex <[email protected]>
@Lv2dev
Lv2dev force-pushed the codex/wincng-normalize-dh-mpints branch from fb1261e to 7eaca5d Compare September 8, 2026 01:07
@vszakats

vszakats commented Sep 8, 2026

Copy link
Copy Markdown
Member

@mback2k Your change request has been addressed, is that correct?

@vszakats vszakats closed this in f216bbe Sep 8, 2026
@vszakats

vszakats commented Sep 8, 2026

Copy link
Copy Markdown
Member

Thanks @Lv2dev, merged now!

vszakats added a commit that referenced this pull request Sep 8, 2026
The WinCNG backend has been missing runtime tests for a while. To
restore some level of testing, this PR make use of curl's regression
test suite (`runtests`) to run SCP/SFTP-specific tests with the
master/PR libssh2 revision at hand. Some tests need to be disabled when
using the built-in Windows OpenSSH server.

The current CI jobs reproduce the long-running WinCNG flaky failure
reported in #804 reliability.

Note, if these CI jobs make libssh2 CI a pain to use, they will be
removed. This has a reasonably fair chance to happen, based on the
experience with curl CI with Windows.

Also:
- test both ECDH and non-ECDH builds.
- test build on x64 and ARM64.
- test with both Windows built-in OpenSSH port and MSYS2's sshd.
- enable debug logging in libssh2 while running the tests.
- for extra stress, run each of the 56-57 tests 6 times.
  This may be lowered in a future commit to avoid flakiness and reduce
  CI load and job times.

Caveats:
- as seen in curl CI, runtests may result in hangs due to broken pipes
  and error 2304 for undiscovered reasons.
  Discussion: curl/curl#14854
- MSBuild has an undisablable "smart" feature that sometimes marks a
  successful run a failure.
  Refs:
  curl/curl@a477789
  curl/curl#18301
- these tests are different in scope than libssh2's own.
- tests sometime fail flaky with:
  ```
  Failure Event: -43 - Failed getting banner
  ```
  Ref: https://github.com/libssh2/libssh2/actions/runs/34134974899/job/101783681252?pr=2590
- running on modern runner machines, the Win10-introduced DH algo is
  always enabled.

Ref: #2049
Ref: #2583

Closes #2590
vszakats added a commit to vszakats/libssh2 that referenced this pull request Sep 11, 2026
Should no longer be necessary after fixing the root cause.
(Though we do not run these tests in CI at the moment.)

Ref: libssh2#804
Follow-up to f216bbe libssh2#2583
Follow-up to bc120a3 libssh2#1023
vszakats added a commit that referenced this pull request Sep 11, 2026
Should no longer be necessary after fixing the root cause.
(Though we do not run these tests in CI at the moment.)

Ref: #804
Follow-up to f216bbe #2583
Follow-up to bc120a3 #1023

Closes #2603
vszakats added a commit that referenced this pull request Oct 13, 2026
In an attempt to improve stability / reduce flakiness of these tests.
Especially the ECDSA-enable ones were prone to mass fail.

```
22:49:30.110000 * Failure establishing ssh session: -43, Failed getting banner
```
Ref: https://github.com/libssh2/libssh2/actions/runs/38480041149/job/115580107883#step:11:1034

This is a different failure than the long-chased flaky -8 kex failures,
which was fixed earlier and did not reoccur since then.

Follow-up to 5bfa574 #2603
Follow-up to f216bbe #2583
Follow-up to bb8e095 #2590

Closes #2666
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.

WinCNG test failures

4 participants