Skip to content

fix(privval,p2p): validate chain ID and reject invalid ephemeral keys - #1344

Merged
lklimek merged 9 commits into
v1.6-devfrom
fix/privval-signer-validation
Jun 17, 2026
Merged

lklimek merged 9 commits into
v1.6-devfrom
fix/privval-signer-validation

Conversation

@lklimek

@lklimek lklimek commented Jun 16, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Hardens the gRPC SignerServer and the secret-connection handshake on the signing and peer-connection paths.

Changes

  • Chain-ID validation — the gRPC SignerServer handlers reject any request whose chain ID does not match the server's configured chain ID (validateChainID, privval/grpc/server.go), so a signer cannot be driven to sign against an unexpected chain.
  • Invalid ephemeral-key rejection — the secret-connection handshake relies on curve25519.X25519 (Go's crypto/ecdh), which returns an error for invalid / low-order Curve25519 public keys, so degenerate ephemeral keys are rejected during the Diffie-Hellman exchange.
  • Insecure-connection visibility — the non-TLS connection fallback is logged at Warn (previously Info) so operators notice unencrypted signer connections.
  • Tests — added coverage for chain-ID validation (privval/grpc/server_test.go) and the secret-connection handshake (privval/secret_connection_test.go).

Breaking changes

None.

🤖 Co-authored by Claudius the Magnificent AI Agent

Add input validation on the signing and connection paths:

- Validate the chain ID in all gRPC SignerServer handlers and reject
  requests whose chain ID does not match the expected value.
- Reject low-order Curve25519 ephemeral public keys during the encrypted
  connection handshake (privval and internal/p2p/conn secret connection),
  making ErrSmallOrderRemotePubKey reachable.
- Raise the log level of the non-TLS connection fallback from Info to Warn
  so operators notice unencrypted signer connections.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>
@coderabbitai

coderabbitai Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 0929c228-6c88-4c5b-902d-75c1313153cb

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Two independent security hardening changes: (1) both internal/p2p/conn and privval MakeSecretConnection now reject remote Curve25519 ephemeral keys that match a libsodium-compatible low-order point blocklist using constant-time comparison, returning ErrSmallOrderRemotePubKey; (2) SignerServer gRPC RPCs now validate ChainId on every request, returning InvalidArgument on mismatch.

Changes

Curve25519 Low-Order Point Rejection

Layer / File(s) Summary
Low-order blocklist and MakeSecretConnection guard
internal/p2p/conn/secret_connection.go, privval/secret_connection.go
Adds lowOrderPoints blocklist and constant-time isLowOrderPoint helper (masking the high bit) in both packages; inserts early rejection guard in MakeSecretConnection before the DH exchange, returning ErrSmallOrderRemotePubKey; adds crypto/subtle import.
Low-order rejection tests (both packages)
internal/p2p/conn/low_order_test.go, privval/secret_connection_test.go
Adds TestIsLowOrderPoint (normal and high-bit-set encodings), TestMakeSecretConnectionRejectsLowOrderKey (scripted net.Pipe peer returning each low-order key), TestMakeSecretConnectionHandshakeSucceeds (normal handshake), and the scriptEphPeer concurrent read/write helper in both test files.

gRPC SignerServer Chain-ID Validation

Layer / File(s) Summary
validateChainID helper and per-RPC guards
privval/grpc/server.go
Adds SignerServer.validateChainID returning gRPC InvalidArgument on mismatch; all five RPC handlers (GetPubKey, GetThresholdPubKey, GetProTxHash, SignVote, SignProposal) call it before any backend logic.
Chain-ID validation test, insecure-connection warning, and utils comment
privval/grpc/server_test.go, privval/grpc/util.go, privval/utils.go
Adds TestSignerServerChainIDValidation with a spyPV wrapper to assert InvalidArgument on mismatch and no backend invocation on rejection; upgrades the DialRemoteSigner insecure-connection log from Info to Warn; rewrites NewSignerListener TODO comment for static-key pinning.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

final review

Suggested reviewers

  • QuantumExplorer

Poem

🐰 A rabbit checks keys with a careful eye,
Low-order points — rejected, goodbye!
Chain IDs must match, no mismatch allowed,
ErrSmallOrderRemotePubKey said aloud.
Constant-time hops keep timing attacks at bay,
The warren stays safe — hip-hip-hooray! 🔐

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 78.95% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The PR title accurately and concisely summarizes the two main changes: chain ID validation in privval and rejection of invalid ephemeral keys in p2p.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/privval-signer-validation

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@lklimek
lklimek requested a review from Copilot June 16, 2026 12:13
@lklimek
lklimek marked this pull request as ready for review June 16, 2026 12:13
@lklimek
lklimek requested a review from QuantumExplorer as a code owner June 16, 2026 12:13
@lklimek

lklimek commented Jun 16, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

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 hardens the remote signing and secret-connection paths by (1) enforcing chain-ID consistency on the gRPC signer API and (2) rejecting known low-order Curve25519 ephemeral public keys during the encrypted handshake, plus making the lack of TLS on signer gRPC connections more visible to operators.

Changes:

  • Added chain ID validation to all SignerServer gRPC handlers and return InvalidArgument on mismatch.
  • Rejected known low-order Curve25519 ephemeral public keys early in both secret-connection handshakes (privval and internal/p2p/conn), making ErrSmallOrderRemotePubKey reachable.
  • Raised the non-TLS gRPC dial logging from Info to Warn and added new unit tests for these behaviors.

Reviewed changes

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

Show a summary per file
File Description
privval/utils.go Updated TCP listener TODO comment to reflect bidirectional key pinning/verification needs.
privval/secret_connection.go Added low-order ephemeral key rejection and constant-time low-order point check helper.
privval/secret_connection_test.go Added tests for low-order point detection and handshake rejection/success cases.
privval/grpc/util.go Raised insecure (non-TLS) signer gRPC connection message to Warn with remediation guidance.
privval/grpc/server.go Added chain ID validation and applied it to all signer API handlers.
privval/grpc/server_test.go Added unit test ensuring chain ID mismatch is rejected and backend methods are not invoked.
internal/p2p/conn/secret_connection.go Added low-order ephemeral key rejection and constant-time low-order point check helper.
internal/p2p/conn/low_order_test.go Added tests for low-order point detection and handshake rejection behavior in p2p secret connection.

Comment thread privval/secret_connection_test.go Resolved
Comment thread internal/p2p/conn/low_order_test.go Resolved
Comment thread privval/secret_connection.go Resolved
Comment thread internal/p2p/conn/secret_connection.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/p2p/conn/low_order_test.go`:
- Around line 62-64: The drain branch of the select statement in both test
locations currently ignores the error returned from the scriptDone channel,
allowing false positives when scriptEphPeer encounters unexpected errors. At
internal/p2p/conn/low_order_test.go lines 62-64, change the receive branch from
`case <-scriptDone:` to `case err := <-scriptDone:` and add `require.NoError(t,
err)` to assert no error occurred. Apply the identical change at
privval/secret_connection_test.go lines 64-66, updating the same select case to
capture and assert the error value to ensure scripted-peer failures are properly
caught and cause test failures rather than being silently ignored.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0f1608d5-5010-4b14-8ce2-d4dcc93db358

📥 Commits

Reviewing files that changed from the base of the PR and between a0d701b and e961665.

📒 Files selected for processing (8)
  • internal/p2p/conn/low_order_test.go
  • internal/p2p/conn/secret_connection.go
  • privval/grpc/server.go
  • privval/grpc/server_test.go
  • privval/grpc/util.go
  • privval/secret_connection.go
  • privval/secret_connection_test.go
  • privval/utils.go

Comment thread internal/p2p/conn/low_order_test.go Resolved
Comment thread internal/p2p/conn/secret_connection.go Resolved
Comment thread privval/secret_connection.go Resolved
Comment thread privval/utils.go Resolved
lklimek added 5 commits June 16, 2026 16:13
…test errors

Move the duplicated Curve25519 low-order point list into a single internal
package (internal/libs/x25519) consumed by both the privval and p2p
secret-connection handshakes, preserving the existing early reject of such
ephemeral keys. Capture and assert the handshake script error in the affected
tests so a failing script no longer passes silently.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>
Drop the hand-rolled low-order point pre-check from the privval and p2p
secret-connection handshakes. curve25519.X25519 (backed by crypto/ecdh)
already returns an error for low-order points instead of producing an
all-zero shared secret, so the explicit check and its
ErrSmallOrderRemotePubKey error were redundant. Document the reliance at the
Diffie-Hellman step and keep a regression test in internal/libs/x25519 that
pins the standard-library rejection. The end-to-end handshake tests still
assert that a low-order remote ephemeral key is rejected.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>
…9 helper package

Remove the internal/libs/x25519 package. Low-order point rejection is now
covered directly in the privval and p2p secret-connection tests, which drive
the real MakeSecretConnection handshake with low-order remote ephemeral keys
and assert it is rejected by curve25519.X25519. Each test file carries its own
copy of the known low-order points so the tests are self-contained. Repoint the
Diffie-Hellman comment to these tests instead of the removed package.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>
Drop the duplicate internal/p2p/conn low-order key regression test and
revert the accompanying secret_connection.go cleanup. The privval
handshake test already pins the curve25519.X25519 low-order rejection
behaviour this branch relies on, so the node-to-node copy is redundant.
Keeps the change focused on the privval signer path.
@thepastaclaw

thepastaclaw commented Jun 17, 2026 •

Copy link
Copy Markdown

✅ Review complete (commit 501aa7f)

@thepastaclaw thepastaclaw 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.

Code Review

PR adds chain-ID validation to all five SignerServer gRPC RPCs and relies on crypto/ecdh-backed X25519 to reject low-order Curve25519 points, with a test fixture covering all 7 libsodium blocklist entries. Validated against source: the chain-ID check rejects mismatches before invoking the backend signer, but treats empty-vs-empty as a match — a hardening gap relative to the PR's stated 'reject empty/unexpected chain IDs' invariant. Note: codex-general ran in degraded mode (Go toolchain unavailable in sandbox); claude-general independently confirmed handler wiring and X25519 behavior locally.

🟡 1 suggestion(s) | 💬 1 nitpick(s)

🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `privval/grpc/server.go`:
- [SUGGESTION] privval/grpc/server.go:37-42: validateChainID accepts empty chain ID when server chain ID is also empty
  The check is a single equality comparison, so a SignerServer instantiated with chainID="" (the CLI flag in cmd/priv_val_server/main.go can be overridden to empty, and NewSignerServer does not validate non-empty) will accept any request whose ChainId is also empty and pass it to the backend signer (e.g. SignVote at server.go:123 forwards req.ChainId verbatim). The PR's stated hardening invariant explicitly calls out rejecting 'empty/unexpected chain IDs before touching the backend signer.' Exploitability requires operator misconfiguration, so this is a defense-in-depth gap rather than an immediate vulnerability, but tightening the helper closes the documented invariant.

Comment thread privval/grpc/server.go Resolved
Comment thread privval/secret_connection_test.go Resolved
The ErrSmallOrderRemotePubKey error was declared but never returned or
referenced anywhere. The secret connection handshake relies on
curve25519.X25519 (crypto/ecdh) to reject invalid/low-order ephemeral
public keys, so this sentinel error is dead code.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@lklimek
lklimek requested a review from thepastaclaw June 17, 2026 10:30

@thepastaclaw thepastaclaw 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.

Code Review

Cumulative review at head 00ab1dd. The new commit cleanly removes the previously dropped/unused ErrSmallOrderRemotePubKey symbol from internal/p2p/conn — that prior cleanup note is resolved. Two carry-forward findings remain valid against current source: validateChainID still treats empty-vs-empty as a match (defense-in-depth gap relative to the PR's stated invariant), and the Curve25519 low-order test fixture still omits the RFC-7748 high-bit-set encodings of p-1/p/p+1. Codex ran in degraded mode (sandbox blocked some test execution), but Claude independently verified handler wiring and X25519 behavior; findings do not depend on test execution.

Carried-forward open findings

  • SUGGESTION privval/grpc/server.go:37 — validateChainID accepts empty chain ID when server chain ID is also empty
    The helper is a single equality comparison, so a SignerServer instantiated with chainID="" (NewSignerServer at server.go:25-31 performs no non-empty check, and cmd/priv_val_server/main.go forwards a CLI flag that may be empty) accepts any request whose ChainId is also empty and passes it to the backend signer — SignVote at server.go:123 forwards req.ChainId verbatim into PrivValidator.SignVote, where it is bound into canonical sign-bytes. Threat model: a misconfigured signer started with --chain-id "" silently signs votes/proposals with an empty chain ID, defeating the domain-separation guarantee this PR is meant to add. Exploitability requires operator misconfiguration, so this is a defense-in-depth gap rather than an immediate vulnerability, but tightening the helper closes the PR's documented invariant of rejecting empty/unexpected chain IDs before touching the backend signer.

  • NITPICK privval/secret_connection_test.go:21 — Low-order rejection test omits high-bit-set encodings of p-1/p/p+1
    RFC 7748 §5 specifies that X25519 ignores the most-significant bit of byte 31 on input, so the Montgomery encodings p-1, p, and p+1 each have a second valid wire form with bit 7 of byte 31 set (0xff instead of 0x7f). The current crypto/ecdh-backed curve25519.X25519 rejects both encodings, so this is a coverage gap rather than a behavior bug — but adding the three high-bit variants pins the boundary behavior this PR's low-order invariant depends on, guarding against a future toolchain change loosening the check on high-bit-set encodings.

Resolved prior notes

  • internal/p2p/conn still carries unused ErrSmallOrderRemotePubKey after the scope-reverting commit: Fixed in commit 00ab1dd ("fix(p2p): drop unused ErrSmallOrderRemotePubKey"). Grep across the repo confirms no remaining references to the symbol in source files.

The inline findings above were already open on prior review threads, so I am not duplicating inline comments. This body-only review records automated review coverage for commit 00ab1dd2.

lklimek and others added 2 commits June 17, 2026 13:20
A SignerServer configured with an empty chainID previously accepted any
request whose ChainId was also empty, because validateChainID was a single
equality check. Guard both sides explicitly: an unconfigured server now
returns FailedPrecondition, a request that omits the chain ID returns
InvalidArgument, and a genuine mismatch keeps returning InvalidArgument.

Extends TestSignerServerChainIDValidation with "unconfigured server
rejected" (FailedPrecondition) and "empty request rejected"
(InvalidArgument) subtests across every RPC handler, asserting the privVal
backend is never reached on rejection.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
RFC 7748 §5 mandates that X25519 ignores the most-significant bit of byte
31, so the p-1, p and p+1 low-order encodings each have a second valid
wire form with bit 7 of byte 31 set (0xff instead of 0x7f). Add those
three variants to the lowOrderPoints table so the rejection test proves
curve25519.X25519 refuses both wire forms.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@thepastaclaw thepastaclaw 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.

Code Review

Cumulative review at head 501aa7f confirms all three prior findings are resolved: validateChainID at privval/grpc/server.go:39-50 now rejects empty server chainID (FailedPrecondition) and empty request chainID (InvalidArgument) before the equality check, with handler-level coverage via a spy PrivValidator in privval/grpc/server_test.go; the Curve25519 low-order fixture at privval/secret_connection_test.go:43-55 now includes the three high-bit-set encodings of p-1/p/p+1 per RFC 7748 §5; and ErrSmallOrderRemotePubKey is fully removed from source. Both Claude agents and Codex agree no in-scope blocking or suggestion-level issues remain. Codex ran in degraded mode (sandbox blocked binding 127.0.0.1:0 for the full ./privval package), but ./privval/grpc and the new TestMakeSecretConnectionRejectsLowOrderKey passed; the chain-ID and low-order findings were verified independently by reading the code, so the degraded coverage does not change the outcome.

@lklimek
lklimek merged commit f4dc89c into v1.6-dev Jun 17, 2026
16 checks passed
@lklimek
lklimek deleted the fix/privval-signer-validation branch June 17, 2026 12:43
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.

3 participants