Compare commits

...
57 Commits
Author SHA1 Message Date
Gopher Robot 45460e0797 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I1dc78ceffd32c80457b284aa1bcefb6dfc2757ba
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/788222
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2026-06-08 08:52:49 -07:00
mohammadmseet-hue d37c95e27d pkcs12: limit PBKDF iteration count to prevent CPU exhaustion
The PKCS#12 PBKDF iteration count is read directly from
the input file with no upper bound. A crafted 83-byte .p12
file can set iterations to 2^31-1 (2147483647), causing
Decode() to block a CPU core permanently.

This change adds a maximum iteration limit of 1000000 in
both verifyMac and pbDecrypterFor. Any file that specifies
more iterations than this cap is rejected with an error.

For reference, OpenSSL caps PBKDF2 at 10000000 iterations,
and scrypt is bounded by its memory-hardness parameters.
The 1000000 limit is generous for legitimate PKCS#12 files
while still preventing denial of service.

Fixes golang/go#78524

Change-Id: I1d12d6f5d90e347ca0dc113678abc51b0cff8d85
GitHub-Last-Rev: a0370d492dd4735cc7c1bb082b359ad79863fdae
GitHub-Pull-Request: golang/crypto#343
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/759900
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2026-06-04 06:58:05 -07:00
povcfe e2ffffe738 ssh: reject incomplete gssapi-with-mic configurations
Make the runtime gssapi-with-mic guard match the existing
configuration and method advertisement checks.

An incomplete GSSAPIWithMICConfig can be treated as unavailable when
building the advertised auth method list, while still remaining
reachable from the runtime auth dispatcher. Treat incomplete
configurations as not configured.

This change introduces a single internal completeness check for
GSSAPIWithMICConfig and uses it for the startup authentication
validation, the runtime gssapi-with-mic dispatch guard, and the
advertised authentication method list.

The change also adds a regression test. The test configures a server
with a normal PasswordCallback, a GSSAPIWithMICConfig with Server set,
and AllowLogin intentionally unset. It then uses a custom client auth
method that explicitly sends a USERAUTH_REQUEST with Method set to
gssapi-with-mic even though the server does not advertise that method,
and verifies that authentication fails cleanly with
"ssh: gssapi-with-mic auth not configured".

No golang/go issue reference is available yet.

Change-Id: I9a0c965d3a56192bd68309aa41e2c1f91952036c
GitHub-Last-Rev: 0267bda8e15e7c258ba3b92cd54f0941534c5fc9
GitHub-Pull-Request: golang/crypto#345
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/773460
Reviewed-by: Mark Freeman <markfreeman@google.com>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2026-06-02 00:25:39 -07:00
Mike Nolta 60e158ad30 ssh/test: isolate CLI tests from user SSH config and agent
Pass -F none and -o IdentityAgent=none to ssh(1) invocations in the
CLI tests. Without these flags, a user's ~/.ssh/config can enable
Control{Master,Persist}, which causes the ssh process to fork a
background daemon that holds stdout/stderr pipes open, preventing
CombinedOutput from ever returning. The agent flag prevents keys loaded
in the user's SSH agent from being offered to the server before the test
key, which would exhaust MaxAuthTries and cause a disconnect.

Fixes golang/go#79411

Change-Id: Id5b073e6df661006183d000928d7ef6e6096b933
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/777900
Reviewed-by: Mark Freeman <markfreeman@google.com>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2026-06-02 00:25:33 -07:00
Nicola Murino 1b77d23dc8 ssh/knownhosts: reject lines with multiple or unknown markers
Previously, parseLine would accept lines with multiple markers (e.g.,
"@cert-authority @revoked ...") or unknown markers (e.g., "@unknown ...").
In these cases, the second or unknown marker was incorrectly parsed as
the hostname. This often resulted in confusing downstream errors (like
"illegal base64 data") because field positions were shifted.

OpenSSH's hostfile.c strictly enforces a limit of one marker per line
and validates that markers must be exactly "@cert-authority" or
"@revoked".

This change adds a check to ensure that the parsed hostname does not
start with '@'. This effectively catches both multiple markers (where
the second marker becomes the host) and unknown markers (which are not
consumed as markers and thus become the host), enforcing strict
compliance with the OpenSSH format.

This issue was found during a security audit by NCC Group Cryptography
Services, sponsored by Teleport, and was assessed and is being fixed as
a non-security bug.

Change-Id: I13bb04d1f2610483ad9c6d1020e5100b6feded90
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/782428
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Mark Freeman <markfreeman@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
2026-06-02 00:24:36 -07:00
Nicola Murino 3872a2bc69 ssh/knownhosts: verify declared key type matches decoded key
The parseLine function previously ignored the key type field (e.g.,
"ssh-rsa") in known_hosts entries, relying solely on the type
information embedded within the base64-encoded key blob.

OpenSSH's sshkey_read implementation explicitly verifies that the key
type declared in the text matches the type of the parsed key, returning
SSH_ERR_KEY_TYPE_MISMATCH if they differ.

This change adds a check to ensure the declared key type matches
key.Type(), returning an error for malformed lines where they diverge.

This issue was found during a security audit by NCC Group Cryptography
Services, sponsored by Teleport, and was assessed and is being fixed as
a non-security bug.

Change-Id: Id4f35c74055f5691088273630b50cdd02c81bfe9
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/782427
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
2026-06-02 00:24:24 -07:00
Nicola Murino 9f72eccdf6 ssh/knownhosts: treat only ASCII space and tab as whitespace
The previous implementation used bytes.TrimSpace, which strips all
Unicode whitespace categories (e.g., non-breaking spaces). However,
OpenSSH's known_hosts parser (hostfile.c) strictly treats only ASCII
space (0x20) and horizontal tab (0x09) as separators.

This discrepancy meant the Go parser might interpret fields differently
than OpenSSH, potentially treating parts of a key or hostname as
separators if they contained Unicode whitespace.

This change replaces bytes.TrimSpace with a local trimSpace helper that
only trims " \t", ensuring parsing behavior consistent with the
reference implementation.

This issue was found during a security audit by NCC Group Cryptography
Services, sponsored by Teleport, and was assessed and is being fixed as
a non-security bug.

Change-Id: Ia536889636de2c167d2507c01e3f1b7c033c9a8f
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/782426
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
2026-06-02 00:24:19 -07:00
Nicola Murino 8f405a4109 ssh: validate ECDSA curve matches expected algorithm
Previously, parseECDSA determined the curve purely based on the key
blob content, ignoring the algorithm identifier passed to parsePubKey.

This allowed a mismatch where a key could be encoded with an algorithm
type of "ecdsa-sha2-nistp256" but contain a NIST P-384 or P-521 curve.
The parser would succeed, returning a key with a type different from
the one indicated by the caller/wire format.

This change updates parseECDSA to accept the expected algorithm type
and verify that it matches the curve specified in the key data. This
matches the behavior of OpenSSH's ssh_ecdsa_deserialize_public in
ssh-ecdsa.c, which rejects a curve identifier that does not correspond
to the key algorithm name.

This issue was found during a security audit by NCC Group Cryptography
Services, sponsored by Teleport, and was assessed and is being fixed as
a non-security bug.

Change-Id: I9c748be948cca65e2f41089bb7510466d3bb316a
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/782425
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
2026-06-02 00:24:14 -07:00
Nicola Murino bb41b3dbe6 ssh: improve DH GEX group selection using PreferredBits
Previously, the server selected the Diffie-Hellman group based solely on
the MaxBits value provided by the client. This resulted in suboptimal
modulus selection, often ignoring the client's PreferredBits or selecting
a larger-than-necessary group.

This change implements a "best fit" selection algorithm similar to
OpenSSH's choose_dh logic. It attempts to find the smallest available
group larger than or equal to the client's PreferredBits, falling back to
the largest available group within the accepted range if no group above
the preference is available.

Additionally, this commit caches the parsed Oakley groups using
sync.OnceValue, avoiding repeated big.Int parsing on every handshake
while keeping the cost out of package initialization.

This issue was found during a security audit by NCC Group Cryptography
Services, sponsored by Teleport, and was assessed and is being fixed as
a non-security bug.

Change-Id: Idfa81bbcf354a7fb7b541cb4bbeb6e4a0181398a
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/782424
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Mark Freeman <markfreeman@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: David Chase <drchase@google.com>
2026-06-02 00:23:03 -07:00
Nicola Murino e04e721997 ssh/agent: validate ed25519 private key length in Add
insertKey and insertCert assume an ed25519.PrivateKey is exactly
64 bytes long: a 32-byte seed followed by a 32-byte public key.
The expression []byte(k)[32:] panics with "slice bounds out of
range" when a shorter slice is passed, which is reachable through
the exported Add API and crashes the caller process.

Reject ed25519 keys whose length is not ed25519.PrivateKeySize in
all four branches (value and pointer variants of insertKey and
insertCert), using the same error wording already used by
parseEd25519Cert in server.go.

This issue was found during a security audit by NCC Group
Cryptography Services, sponsored by Teleport, and was assessed
and is being fixed as a non-security bug.

Change-Id: I4a053835588aad4c3482fe1ca8045542cd960500
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/782423
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2026-06-02 00:22:54 -07:00
Nicola Murino b315afd69a ssh: limit bcrypt KDF rounds in OpenSSH private key decryption
passphraseProtectedOpenSSHKey decodes the bcrypt round count from
the key file and passes it directly to bcrypt_pbkdf.Key, whose
running time is linear in that count. Files specifying very large
round values cause the decryption to consume excessive CPU time:
a uint32 maximum is several months of work on commodity hardware.

Cap the accepted round count at 2048 (128x the default of 16, a
few seconds of CPU on a modern core). OpenSSH itself does not
impose an upper bound, but accepting arbitrary values turns key
loading into a resource-exhaustion footgun for any code that
processes files supplied by end users.

This issue was found during a security audit by NCC Group
Cryptography Services, sponsored by Teleport, and was assessed
and is being fixed as a non-security bug.

Change-Id: I01112bdf1b484ae4fab5dc8841d1a272f112df74
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/782422
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2026-06-02 00:22:48 -07:00
Nicola Murino d4a85f4749 ssh/agent: limit RSA key size on Add requests
parseRSAKey and parseRSACert build an rsa.PrivateKey directly from
the Add request body and then call priv.Precompute(). The CRT
coefficient recomputation in Precompute() is cubic in the size of
the prime factors, so accepting RSA keys with arbitrary modulus
and prime sizes can consume excessive CPU resources during a
single Add operation.

Add a checkRSAKeyParams helper that enforces the same bounds as
parseRSA in the ssh package (modulus <= 8192 bits, exponent <= 24
bits, exponent >= 3 and odd) plus a cap of 4096 bits on each prime
factor, and call it from both parseRSAKey and parseRSACert before
priv.Precompute().

The previous inline check on the exponent (BitLen > 30) is
subsumed by the new helper, which tightens it to BitLen > 24 for
consistency with parseRSA.

Change-Id: I6f0bbbfdc1db13d62a1f85e1d0e6ae517f000443
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/782421
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
2026-06-02 00:22:42 -07:00
Nicola Murino 6f39c5226a ssh: limit RSA key size in OpenSSH private key parsing
parseOpenSSHPrivateKey builds an rsa.PrivateKey directly from the
unmarshalled OpenSSH key blob, bypassing parseRSA and its modulus
limit. Validate() and Precompute() then perform several modular
exponentiations whose cost grows with the size of the prime factors;
in particular Precompute() recomputes the CRT coefficient as
q^(p-2) mod p, which is cubic in |p|. A maliciously crafted key with
oversized N and P can keep the CPU busy for hours or days during a
single load.

Mirror the parseRSA validation here: cap the modulus at 8192 bits
(the same limit enforced by crypto/tls), reject exponents larger than
24 bits, and reject invalid exponent values (< 3 or even). In addition,
bound each prime factor at 4096 bits to prevent the CRT computation
from becoming the dominant cost.

This issue was found during a security audit by NCC Group Cryptography
Services, sponsored by Teleport, and was assessed and is being fixed as
a non-security bug.

Change-Id: Ia5991f25dd41a22eddd7cf63a8fc5106de9e9663
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/782420
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2026-06-02 00:22:37 -07:00
Nicola Murino 4c4d20b72c ssh: fix spinloop in mux SendRequest drain on closed channel
The drain loop added in 4e7a738 ("ssh: fix deadlock on unexpected
global responses") receives from m.globalResponses without checking
the comma-ok flag. Once mux.loop closes globalResponses on connection
teardown, the loop spins forever on the zero value, pinning a CPU
core for every concurrent SendRequest caller.

Use the comma-ok idiom to detect the closed channel and break out.

Change-Id: Icf0a7419fe5b206b7a4f70429fa9f25d0b5af731
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/783681
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Neal Patel <nealpatel@google.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Neal Patel <neal@golang.org>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
2026-05-28 10:16:30 -07:00
Nicola Murino e3e62d9601 ssh: fix spinloop in channel SendRequest drain on closed channel
The drain loop added in 3c7c869 ("ssh: fix deadlock on unexpected
channel responses") receives from ch.msg without checking the comma-ok
flag. Once ch.msg is closed by channel.close(), receives succeed
immediately with the zero value, so the default arm is never taken
and the loop spins forever, pinning a CPU core for every concurrent
SendRequest caller on a torn-down channel.

Use the comma-ok idiom to detect the closed channel and break out.

Fixes golang/go#79658

Change-Id: Id80aa5d8429550c7a68e8759aed9ffba3aabb006
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/783680
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
Reviewed-by: Neal Patel <neal@golang.org>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Neal Patel <nealpatel@google.com>
2026-05-28 10:16:26 -07:00
Nicola Murino 5adb68b3e6 ssh: cap total userauth attempts per server connection
serverAuthenticate only bounded real failures via MaxAuthTries.
PartialSuccessError responses and the publickey isQuery short-circuit
both kept the loop running without incrementing authFailures, so a
client could keep the server processing SSH_MSG_USERAUTH_REQUEST
messages indefinitely on a single connection.

Add an unconditional cap, maxAuthServerAttempts = 128, on the total
number of userauth requests handled per connection. The counter is
incremented at the top of the loop before method dispatch, so every
method and every isQuery / partial-success path counts. When the cap
is exceeded the server sends SSH_MSG_DISCONNECT with reason 2 ("too
many authentication attempts"), mirroring the MaxAuthTries handling.
The bound is well below OpenSSH's hard cap of 1024 but above any
realistic multi-step auth flow.

Change-Id: I56779fc55cd00ddfd32ec938f8de3a49be0145dc
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/781903
Reviewed-by: Junyang Shao <shaojunyang@google.com>
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
2026-05-27 09:40:09 -07:00
Neal Patel 9beb694f97 ssh: prevent malformed exit-status panic
A malicious server can crash any client by sending
a truncated exit-status payload, which triggers a
panic in binary.BigEndian.Uint32.

Change-Id: Iff4fe182b40210c99d46562f6c3b5ecf38bb98b4
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/780181
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
Reviewed-by: David Chase <drchase@google.com>
2026-05-25 19:49:21 -07:00
Nicola Murino e5306b2f3e ssh/agent: support parallel signing using request pipelining
Make NewClient automatically pipeline concurrent requests over its
connection when the supplied io.ReadWriter also implements io.Closer.
In this mode the client writes requests to the wire as soon as the
write path is available and dispatches responses back to callers in
FIFO order via a dedicated reader goroutine, instead of fully
serializing each call. Up to 32 requests may be in flight on a single
connection.

This lets an agent that load-balances signing across multiple backend
devices keep several of them busy concurrently without forcing callers
to maintain their own connection pool. Aggregate throughput scales
roughly linearly with the number of backend devices up to the
in-flight cap; the protocol's in-order response requirement means
slow requests still delay subsequent ones on the same connection,
which is unchanged.

The pipelined path requires io.Closer because, on a Write error, the
background reader goroutine must be unblocked by closing the
underlying connection; otherwise it would remain parked forever
waiting for a response that will never arrive, leaking the goroutine
and desynchronising the FIFO routing of responses for subsequent
successful writes. When the supplied transport does not implement
io.Closer, NewClient falls back to the previous fully-serialized
behavior: a single in-flight call at a time, with no background
goroutine.

Fixes golang/go#78473

Change-Id: Icf14e5e8ca897506d68fb32c14fc72c774cd97b2
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/768483
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2026-05-21 19:39:50 -07:00
dingandCyrus Katrak d2fe592df1 ssh: add openssh controlmaster socket support
Adds support for establishing SSH sessions over an existing "ControlMaster" [unix domain] socket in proxy mode.

Details of the protocol can be found here: https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.mux
More details about ControlMaster sockets can be found here: https://linux.die.net/man/5/ssh_config

Fixes golang/go#32958

Co-authored-by: Cyrus Katrak <ckatrak@slack-corp.com>
Change-Id: Ia3ae8893262f5060ed3fadfcbe97619c9659145b
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/733040
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
2026-05-21 19:39:36 -07:00
Nicola Murino d59570d1a3 ssh: add AuthCallback to ClientConfig
Add ClientAuthCallback, a hook invoked before each authentication
attempt that allows the client to dynamically select an auth method
based on server capabilities, partial successes, or previous failures.

clientAuthenticate tracks partial successes in a slice and passes
them to AuthCallback via ClientAuthContext.PartialSuccessMethods,
along with the list of failed methods and currently allowed methods.
When AuthCallback returns a non-nil AuthMethod, it is used for the
next attempt, bypassing the static findNext selection. When it
returns (nil, nil), the static config.Auth selection proceeds as
before. If AuthCallback returns (nil, error) the handshake aborts
immediately with that error.

To bound resource use when AuthCallback keeps supplying methods, the
client caps the total number of authentication attempts (failures and
partial successes combined) at 64; exceeding the cap aborts the
handshake with an error.

Fixes golang/go#76146

Change-Id: I0d02bea7b9dd724e95e5d9d49d85306666c0df7a
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/717140
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2026-05-21 19:36:57 -07:00
Nicola Murino 4aab0d9d6a ssh: return partial success immediately from publickey auth
Change publicKeyCallback to return authPartialSuccess to the caller
immediately when a signer receives partial success, instead of
continuing to try remaining signers internally.

The caller (clientAuthenticate) already handles authPartialSuccess
by not adding the method to "tried", so findNext can re-select
publickey on the next iteration. When it does, all signers are
tried again from the beginning.

Change-Id: Icc87721aa56ef59a357e409aa046640a27e5fc46
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/757900
Reviewed-by: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2026-05-21 19:36:47 -07:00
Gopher Robot a1c0d99298 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: Ia739869d49c750c7fa578b9dbd7bb998d8c87087
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/781683
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Nicholas Husin <nsh@golang.org>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Nicholas Husin <husin@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Damien Neil <dneil@google.com>
2026-05-21 17:26:06 -07:00
Nicola 3c7c86938f ssh: fix deadlock on unexpected channel responses
Previously, channel.handlePacket sent channelRequestSuccess and
channelRequestFailure messages to ch.msg unconditionally via the default
arm of its type switch. Because ch.msg is a bounded buffer (chanSize),
a peer that sends a burst of unsolicited channel request responses for
an open, idle channel fills the buffer and blocks the mux read loop on
the next send. That stalls all packet processing on the connection,
and because readLoop then backs up on t.incoming, closing the
underlying net.Conn does not unblock either goroutine: user code
observes Close() returning promptly while Wait() hangs and the mux,
readLoop, and kexLoop goroutines leak permanently.

This change mirrors the fix for the mux-level SendRequest path: a
sentRequestPending atomic gate is set while a SendRequest with
WantReply is in flight, handlePacket drops responses when the gate is
closed, and uses a non-blocking send otherwise. SendRequest drains
any spurious response that slipped through before discarding it, so
the caller always observes the reply to its own request.

This aligns with OpenSSH, which silently ignores channel confirm
messages that do not match a pending request.

Fixes golang/go#79564
Fixes CVE-2026-39830

Change-Id: I15e2add4bf7876bb0c6f921f8b57203d97e83f47
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/781664
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Neal Patel <nealpatel@google.com>
Reviewed-by: Neal Patel <nealpatel@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2026-05-21 17:09:12 -07:00
Neal Patel 533fb3f7e4 ssh: fix source-address critical option bypass
Previously, CVE-2024-45337 fixed an authorization bypass
for misused ssh server configurations; if any other type
of callback is passed other than public key, then the
source-address validation would be skipped.

Fixes CVE-2026-46595
Fixes golang/go#79570

Change-Id: I08d86a961048a232c8672f23000e693ed5a0e2fd
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/781642
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Neal Patel <nealpatel@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2026-05-21 17:03:26 -07:00
Neal Patel abbc44d451 ssh: fix incorrect operator order
Arithmetic is incorrectly applied to 'byte'
instead of 'int' resulting in a possible
overflow that allows for a panic.

Fixes CVE-2026-46597
Fixes golang/go#79561

Change-Id: I83edabeeda676f0209d29d5e2554890bbd0eef8f
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/781620
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Nicholas Husin <nsh@golang.org>
Reviewed-by: Nicholas Husin <husin@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2026-05-21 17:03:25 -07:00
Nicola Murino e052873987 ssh: fix infinite loop on large channel writes due to integer overflow
The internal 'min' helper function in channel.go incorrectly cast the
input data length (int) to uint32 before comparing it with the
maximum packet size. On 64-bit systems, if the data length is a
multiple of 2^32 (approx. 4GB), this cast results in 0.

Consequently, the function returns 0, causing the WriteExtended loop
to spin indefinitely because it attempts to reserve 0 bytes while
the remaining data length is still positive.

This change renames the helper to 'minPayloadSize' to avoid confusion
with the Go 1.21 built-in 'min' and updates the logic to use int64
for comparisons, preventing truncation and the resulting infinite loop.

This issue was found during a security audit by NCC Group Cryptography
Services, sponsored by Teleport.

Fixes golang/go#79567
Fixes CVE-2026-39834

Change-Id: Id5bf81d9f06c7042452acffe1c76580ff878665e
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/781663
Reviewed-by: Neal Patel <nealpatel@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2026-05-21 17:03:23 -07:00
Nicola Murino b61cf853a8 ssh: enforce user presence verification for security keys
Previously the library did not verify the "User Presence" (UP) bit in
signatures generated by FIDO/U2F security keys
(sk-ecdsa-sha2-nistp256@openssh.com and sk-ssh-ed25519@openssh.com).
This allowed signatures without physical interaction to be accepted
if the underlying hardware produced them, deviating from the default
secure behavior expected by the FIDO standards and OpenSSH.

skECDSAPublicKey.Verify and skEd25519PublicKey.Verify now enforce
the user-presence bit (0x01, constant flagUserPresence) by default.
Signatures whose flags byte has UP clear fail with the sentinel
errSKMissingUserPresence.

The server public-key authentication path honors the OpenSSH
"no-touch-required" extension as an opt-out. noTouchAllowed reports
true when the extension is present either in the Permissions
returned by PublicKeyCallback (authorized_keys-level opt-out) or in
the certificate's own Extensions (CA-level opt-out); in that case
skKeyWithoutUP is used to derive a clone of the SK public key (and,
for certificates, a clone of the wrapping Certificate whose inner
Key is the cloned SK key) whose Verify accepts UP-clear signatures.
The originals are never mutated, so a per-session opt-out cannot
leak across authentication attempts or connections. Matching
OpenSSH, the opt-out is read only from Extensions, never from
CriticalOptions.

skKeyWithoutUP is iterative and unwraps at most one level of
*Certificate: the SSH cert format forbids Certificate.Key from being
another Certificate (parseCert rejects it) but callers can still
construct such a value directly in Go, so a recursive descent would
be driven to unbounded depth by malformed or cyclic input. Any such
pathological *Certificate is returned unchanged.

CertChecker.CheckCert applies skKeyWithoutUP unconditionally to the
certificate's CA key before verifying the CA signature, matching
OpenSSH, which calls sshkey_verify with detailsp==NULL in
sshkey.c:cert_parse and never extracts or enforces UP/UV flags on
CA signatures. The UP bit on a CA signature reflects the CA
operator's presence at cert-issuance time, which has no bearing on
whether the user being authenticated is present now, so enforcing it
here would only break interop with certificates issued by
non-interactive SK CAs without a corresponding security benefit. The
skKeyWithoutUP call is a no-op for non-SK CA keys (the common case).

This change breaks backward compatibility for clients or keys that
generate user-authentication signatures without the User Presence
flag set. Previously those signatures were accepted by the server.
They will now be rejected with "ssh: signature missing required user
presence flag" unless the "no-touch-required" extension is
explicitly granted to the session by the server callbacks, or
carried by the user certificate.

This issue was found during a security audit by NCC Group
Cryptography Services, sponsored by Teleport.

Fixes golang/go#79566
Fixes CVE-2026-39831

Change-Id: I74b6de3bb6a2d7a0f34d7fa36bbbbf06f0b3fc6b
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/781662
Reviewed-by: Neal Patel <nealpatel@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2026-05-21 17:03:20 -07:00
Nicola Murino 9c2cd33e8d ssh: enforce strict limits on DSA key parameters
The parseDSA function previously accepted DSA keys with arbitrary values
for the sub-prime Q and did not validate that group elements G and Y
were within the modulus P.

Malicious actors could provide a key with a massively large Q (e.g.,
millions of bits), leading to excessive CPU consumption during signature
verification.

This change restricts the sub-prime Q to exactly 160 bits, as required
by FIPS 186-2, and ensures that G and Y are strictly less than P.

This issue was found during a security audit by NCC Group Cryptography
Services, sponsored by Teleport.

Fixes golang/go#79565
Fixes CVE-2026-39829

Change-Id: I526118d94684076088d0625178844f64c1303ec8
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/781661
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Neal Patel <nealpatel@google.com>
2026-05-21 17:03:16 -07:00
Nicola Murino 890731877d ssh: reject RSA keys with excessively large moduli
Previously, the RSA key parser accepted keys with arbitrary modulus
sizes. Processing keys with extremely large moduli (e.g., > 8192 bits)
can consume excessive CPU resources during verification, potentially
leading to a Denial of Service (DoS).

This change introduces a limit of 8192 bits for the RSA modulus in
parseRSA, rejecting keys that exceed this size in line with the limit
enforced by crypto/tls.

This issue was found during a security audit by NCC Group Cryptography
Services, sponsored by Teleport.

Fixes golang/go#79565
Fixes CVE-2026-39829

Change-Id: Ibdddad1859a4d9db5c9f052d06c82f29bfc2e5e5
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/781641
Reviewed-by: Neal Patel <nealpatel@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2026-05-21 17:03:13 -07:00
Nicola Murino ffd87b4878 ssh: fix panic when authority callbacks are nil
Previously, if CertChecker.IsHostAuthority or CertChecker.IsUserAuthority
were left unset, calling CheckHostKey or Authenticate would result in a
nil pointer dereference panic.

This change adds checks to ensure these callbacks are defined before
invocation, returning an error instead of panicking.

This issue was found during a security audit by NCC Group Cryptography
Services, sponsored by Teleport.

Fixes golang/go#79563
Fixes CVE-2026-39835

Change-Id: I2bd9c8d76646232e49f6aedc7b5334f3825918be
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/781660
Commit-Queue: Neal Patel <nealpatel@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Neal Patel <nealpatel@google.com>
2026-05-21 17:03:09 -07:00
Nicola Murino 4e7a7384ec ssh: fix deadlock on unexpected global responses
Previously, the mux implementation handled global request responses by
blocking until the response could be sent to the globalResponses channel.
Since this channel has a buffer size of 1, unsolicited responses from a
server (or responses arriving after a timeout) would fill the buffer.
Subsequent unsolicited responses would block handleGlobalPacket, stalling
the entire connection's read loop and causing a denial of service.

This change modifies handleGlobalPacket to use a non-blocking send. If
no goroutine is waiting for a response (or the buffer is full), the
message is dropped. This aligns with OpenSSH behavior, which ignores
unexpected global responses.

Additionally, SendRequest now drains the globalResponses channel after
acquiring the mutex but before sending the request. This ensures that
any stale responses or "spam" buffered just before the lock was acquired
are discarded, preventing race conditions where a legitimate request
might otherwise consume an unrelated response.

This issue was found during a security audit by NCC Group Cryptography
Services, sponsored by Teleport.

Fixes golang/go#79564
Fixes CVE-2026-39830

Change-Id: Ia0c46355203d557eadcd432c10b87c8a044e1089
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/781640
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Neal Patel <nealpatel@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2026-05-21 17:02:53 -07:00
Nicola Murino b25012b37b ssh: enforce nil Permissions when returning PartialSuccessError
In serverAuthenticate, the permissions variable is reset to nil at the
beginning of the authentication loop. If an authentication callback
returns a PartialSuccessError along with non-nil Permissions, those
permissions are currently silently discarded before the next
authentication step.

This change returns an error if a callback returns both a PartialSuccessError
and non-nil Permissions, preventing API misuse where the user might
erroneously expect those permissions to be preserved or merged into the
final session permissions.

This issue was found during a security audit by NCC Group Cryptography
Services, sponsored by Teleport.

Fixes golang/go#79562
Fixes CVE-2026-39828

Change-Id: I632c9e46e2b5e8804ef88081063a3612a2462f9f
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/781621
Reviewed-by: Neal Patel <nealpatel@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2026-05-21 17:00:58 -07:00
Nicola Murino 6c195c8a97 ssh: prevent memory leak when rejecting channels
When a server rejects an incoming channel request via
NewChannel.Reject, the channel is left in the multiplexer's
channel list. Because the channel is never explicitly removed or
closed, its internal buffers and sync primitives remain allocated
for the lifetime of the SSH connection.

A malicious client could exploit this behavior by repeatedly
requesting to open channels that are destined to be rejected,
causing unbounded memory growth and potentially leading to a
Denial of Service (DoS) via resource exhaustion.

This change fixes the leak by calling ch.mux.chanList.remove
within the Reject method, removing the channel from the list and allowing the
garbage collector to reclaim the associated memory immediately.

Fixes golang/go#35127
Fixes CVE-2026-3982

Change-Id: Iaa177f5dfd151812dd404e528a4a1c77527a0e29
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/781320
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Nicholas Husin <nsh@golang.org>
Reviewed-by: Nicholas Husin <husin@google.com>
2026-05-21 11:00:25 -07:00
Neal Patel f717e29698 ssh/knownhosts: respect @revoked CA keys
Fixes CVE-2026-42508
Fixes golang/go#79568

Change-Id: I20f33cba20756b048726ff3464b83871859d3b5c
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/781220
Reviewed-by: Nicholas Husin <husin@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Nicholas Husin <nsh@golang.org>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2026-05-21 10:58:49 -07:00
Neal Patel e7c36ccb47 ssh/agent: prevent panic on pathological ed25519 inputs
parseEd25519Key and parseEd25519Cert cast wire bytes
to ed25519.PrivateKey without checking length; a short
payload panics at priv[32:] in Public().

Fixes CVE-2026-46598
Fixes golang/go#46598

Change-Id: I127bc6a22adff1c4beb4d54533062bebc388de47
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/781360
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Nicholas Husin <nsh@golang.org>
Reviewed-by: Nicholas Husin <husin@google.com>
2026-05-21 10:55:07 -07:00
Nicola 0fb843a472 ssh/agent: reject keys with unsupported confirm constraint
The in-memory keyring supports the "lifetime" constraint but does not
implement the "confirm" constraint. Previously, keyring.Add silently
ignored ConfirmBeforeUse: the key was stored, advertised through List,
and used for signing without any interactive confirmation, potentially
misleading callers into believing this security measure was enforced.

Return an error when ConfirmBeforeUse is set instead of silently
downgrading the caller's security expectations. Implementing real
confirm-before-use in an in-memory library keyring is infeasible (there
is no UI or confirmation callback), so failing closed is the correct
behavior; adding actual confirm support would require an API addition
and is out of scope.

This is a deliberate behavior change: keyring.Add previously accepted
and ignored ConfirmBeforeUse and now returns an error. This change also
updates the keyring doc comments to document the supported constraints.

This issue was found during a security audit by NCC Group Cryptography
Services, sponsored by Teleport.

Fixes CVE-2026-39833
Updates golang/go#47533
Fixes golang/go#79436

Change-Id: I1b3a286f0c1e4a4e08ac37109f7e491692ca90ae
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/778642
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Neal Patel <nealpatel@google.com>
Reviewed-by: Neal Patel <neal@golang.org>
Auto-Submit: Neal Patel <nealpatel@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2026-05-21 10:54:57 -07:00
Nicola e3d1254f1e ssh/agent: don't accept keys with unsupported constraints
The in-memory keyring cannot enforce constraint extensions, so silently
accepting a key that carries them gave callers a false sense of
restriction. Refuse keys with constraint extensions instead: a key
whose constraints cannot be enforced must not be loaded. This behavior
is consistent with OpenSSH.

This is a deliberate behavior change: keyring.Add previously accepted
and ignored ConstraintExtensions and now returns an error.

This issue was found during a security audit by NCC Group Cryptography
Services, sponsored by Teleport.

Fixes CVE-2026-39832
Fixes golang/go#79435

Change-Id: I6ca4f1c29f8edfabb287fe07299641f70896d5fe
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/778641
Auto-Submit: Neal Patel <nealpatel@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Neal Patel <neal@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Neal Patel <nealpatel@google.com>
2026-05-21 10:47:08 -07:00
Nicola a1ce0fee12 ssh/agent: preserve constraint extensions when adding keys
The client Add method only serialized the lifetime and confirm
constraints and silently dropped AddedKey.ConstraintExtensions before
sending the SSH_AGENTC_ADD_IDENTITY request. As a result the remote
agent always received the key with no extension constraints, regardless
of what the caller requested.

Applications that add a key believing custom constraint extensions
(such as restrict-destination-v00@openssh.com) would be enforced
instead loaded a completely unrestricted key into the agent. For
example, an administrator forwarding their agent into an untrusted jump
host and trying to limit the forwarded key with restrict-destination
never had that restriction reach the agent: any user or compromised
process on that host could make the agent sign arbitrary challenges.

Serialize each entry in key.ConstraintExtensions as an
agentConstrainExtension constraint so the constraints reach the agent,
and add a round-trip regression test that verifies the extensions
survive client serialization and server parsing.

This issue was found during a security audit by NCC Group Cryptography
Services, sponsored by Teleport.

Updates CVE-2026-39832
Updates golang/go#79435

Change-Id: I14c5583b106cbf0d282d2ba01e000e0f586f08c7
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/778640
Reviewed-by: Neal Patel <neal@golang.org>
Reviewed-by: Neal Patel <nealpatel@google.com>
Reviewed-by: Keith Randall <khr@google.com>
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2026-05-21 10:43:27 -07:00
Roland Shoemaker a749d17980 chacha20poly1305: remove usages of BYTE instr
We have had VBROADCASTI128 since at least Go 1.11, so no need to use
BYTE instructions.

Change-Id: I297bbc636320ae830f6e8f83eb174efe8251a9a3
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/672838
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
Auto-Submit: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2026-05-18 11:44:40 -07:00
Roland Shoemaker 7ee59707ff chacha20poly1305: drop pre-AVX assembly impl
Updates golang/go#69587

Change-Id: Ic158558f879b8b8ad23155bf887e083169096d19
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/672837
Auto-Submit: Roland Shoemaker <roland@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
2026-05-18 11:44:36 -07:00
Dmitri Shuralyov 44decbfe70 blake2b: merge go125.go into blake2b_test.go
The go1.25 build constraint is guaranteed to always be satisfied because
the go directive is at 1.25.0, so the separated out go125.go file is not
needed. Move the assertion that the *xof type implements the hash.XOF
interface into a _test.go file to let it happen alongside other tests
in this package.

Change-Id: I65c886ede4d574a3168f28689f9529aa56586697
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/775781
Auto-Submit: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: Hyang-Ah Hana Kim <hyangah@gmail.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
2026-05-11 07:38:31 -07:00
Gopher Robot b8a14a8d65 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: Ie3eba6549d69698b6dd089c7e49f7c30198dc2bb
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/775841
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
2026-05-08 11:32:18 -07:00
Daniel McCarney 9d9d507896 x509roots/fallback/bundle: fix bundle test with Go 1.27+
In Go 1.27 we've updated crypto/x509/pkix to avoid hex-encoding
attribute values that are string-typed. However, in TestBundle() we
assert the parsed certificate subject CN matches expected and now the
parsed value differs based on Go version.

This commit introduces some small helpers that on Go 1.25/1.26 replicate
the Go 1.27 behavior, decoding hex-encoded attribute values before
making the comparison.

In this way the test continues to pass without losing any coverage, or
introducing duplicated per-version bundles. In the future when only Go
1.27+ are supported we can revert this extra machinery.

Change-Id: I66bf6439e421169c0f9c750f88116b73ec5188fe
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/775760
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Daniel McCarney <daniel@binaryparadox.net>
2026-05-08 08:10:15 -07:00
repon fd0b90d21f acme: include Problem in OrderError.Error
An ACME Order object can contain an error field when it is invalid.
Previously, OrderError.Error() ignored this field, making it difficult
to diagnose why an order failed. This change includes the problem
details if available.


Change-Id: I461fd02ef02251a2ba1e8cea39b5df8070938117
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/772880
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Sean Liao <sean@liao.dev>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
2026-05-01 10:44:32 -07:00
Filippo Valsorda b9e53593a6 pbkdf2: turn into a wrapper for crypto/pbkdf2
Change-Id: If95f1d771404fe88a8f9bc0a17b5a4d16a6a6964
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/769721
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Carlos Amedee <carlos@golang.org>
2026-04-23 08:20:11 -07:00
Filippo Valsorda cc0e4fc1d4 hkdf: forward Extract to the standard library
Change-Id: I82406eb153c53e7cbf167360e472724a6a6a6964
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/769720
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
2026-04-23 08:20:08 -07:00
Gopher Robot a8e9237a21 x509roots/fallback: update bundle
This is an automated CL which updates the NSS root bundle.

[git-generate]
go generate ./x509roots

Change-Id: I9bad7b49959a336a125bdc3aa340c94292b26899
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/766500
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2026-04-13 10:03:23 -07:00
Gopher Robot 03ca0dcccb go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: Ia33bd1cd73db091960b285c234d2cf2622f30943
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/764501
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2026-04-09 08:33:22 -07:00
Nicola Murino 8400f4a938 ssh: respect signer's algorithm preference in pickSignatureAlgorithm
Previously, pickSignatureAlgorithm constructed the list of candidate
algorithms by iterating over the static list returned by
algorithmsForKeyFormat. This caused the Signer's preference order
to be ignored in favor of the library's default internal order.

This change inverts the filtering logic to iterate over the signer's
supported algorithms first. This ensures that if a MultiAlgorithmSigner
explicitly prefers a specific algorithm (e.g., rsa-sha2-512 over
rsa-sha2-256), that preference is preserved and respected during the
handshake negotiation.

Fixes golang/go#78248

Change-Id: I48a0aac720be7f973963342b82047ce32fc96699
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/746020
Reviewed-by: Lonny Wong <lonnywang.cn@gmail.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Carlos Amedee <carlos@golang.org>
2026-03-23 08:34:51 -07:00
Rob Picard 81c6cb34a8 ssh: swap cbcMinPaddingSize to cbcMinPacketSize to get encLength
The existing code uses cbcMinPaddingSize incorrectly. That value is
also used in the first parameter of the max call, meaning it will
never be used.

Fixes golang/go#78062

Change-Id: I4243ab668168313919df33d78c6965e9eff0e934
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/754780
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
2026-03-20 08:28:06 -07:00
Gopher Robot 982eaa62df go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: Ic40aa8385f00dc3d3e3588a0e2555c8039ae6017
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/754160
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2026-03-11 07:17:49 -07:00
Neal Patel 159944f128 ssh,acme: clean up tautological/impossible nil conditions
Change-Id: I4c6b4b6d8dc1e8a9d2ebfb8d350b7617d3cf7949
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/739780
Auto-Submit: Neal Patel <nealpatel@google.com>
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
2026-03-10 10:37:09 -07:00
Sean Liao a408498e55 acme: only require prompt if server has terms of service
Fixes golang/go#64881

Change-Id: I2b4415e6f987aab258c26c090ac7b1a465aa1697
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/719001
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
2026-02-13 09:12:11 -08:00
Gopher Robot cab0f71854 all: upgrade go directive to at least 1.25.0 [generated]
By now Go 1.26.0 has been released, and Go 1.24 is no longer supported
per the Go Release Policy (see https://go.dev/doc/devel/release#policy).

See go.dev/doc/godebug#go-125 for GODEBUG changes relevant to Go 1.25.

For golang/go#69095.

[git-generate]
(cd . && go get go@1.25.0 && go mod tidy)
(cd x509roots/fallback && go get go@1.25.0 && go mod tidy)

Change-Id: I8df6bf58a117a2f92bb08f787e520aa9446dab46
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/744680
Reviewed-by: Junyang Shao <shaojunyang@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Michael Pratt <mpratt@google.com>
2026-02-11 11:12:56 -08:00
Gopher Robot 2f26647a79 x509roots/fallback: update bundle
This is an automated CL which updates the NSS root bundle.

[git-generate]
go generate ./x509roots

Change-Id: I3665d29edabaef0efb634031b2b7d20d32774eec
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/743540
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2026-02-09 13:49:22 -08:00
Gopher Robot e08b06753d go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I1b283104f6d4557ee12c256bbadfccb3cd5548be
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/743362
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
2026-02-09 08:37:10 -08:00
Juergen Graf 7d0074ccc6 scrypt: fix panic on parameters <= 0
Providing 0 as argument for r or p results in a panic:
panic: runtime error: integer divide by zero

Providing negative values for r or p returns a misleading error:
scrypt: parameters are too large

This change avoids the panic and introduces a new error
that is returned when r or p are <= 0:
scrypt: parameters must be > 0

Change-Id: I68987b27d1eedd66644d2ec9436cba364fc1d46d
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/731780
Reviewed-by: Michael Pratt <mpratt@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Auto-Submit: Roland Shoemaker <roland@golang.org>
2026-01-13 07:44:11 -08:00
58 changed files with 5867 additions and 7560 deletions
-4
View File
@@ -248,10 +248,6 @@ func (m *Manager) TLSConfig() *tls.Config {
// If GetCertificate is used directly, instead of via Manager.TLSConfig, package users will
// also have to add acme.ALPNProto to NextProtos for tls-alpn-01, or use HTTPHandler for http-01.
func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
if m.Prompt == nil {
return nil, errors.New("acme/autocert: Manager.Prompt not set")
}
name := hello.ServerName
if name == "" {
return nil, errors.New("acme/autocert: missing server name")
+1 -1
View File
@@ -201,7 +201,7 @@ func TestGetCertificate(t *testing.T) {
prepare: func(t *testing.T, man *Manager, s *acmetest.CAServer) {
man.Prompt = nil
},
expectError: "Manager.Prompt not set",
expectError: "missing Manager.Prompt",
},
{
name: "trailingDot",
+3 -1
View File
@@ -239,7 +239,8 @@ type discovery struct {
}
type discoveryMeta struct {
ExternalAccountRequired bool `json:"externalAccountRequired,omitempty"`
Terms string `json:"termsOfService,omitempty"`
ExternalAccountRequired bool `json:"externalAccountRequired,omitempty"`
}
type challenge struct {
@@ -281,6 +282,7 @@ func (ca *CAServer) handle(w http.ResponseWriter, r *http.Request) {
NewAccount: ca.serverURL("/new-account"),
NewOrder: ca.serverURL("/new-order"),
Meta: discoveryMeta{
Terms: ca.serverURL("/terms"),
ExternalAccountRequired: ca.eabRequired,
},
}
-3
View File
@@ -180,9 +180,6 @@ func TestRenewFromCacheAlreadyRenewed(t *testing.T) {
// set internal state to an almost expired cert
oldCert := ca.LeafCert(exampleDomain, "ECDSA", now.Add(-2*time.Hour), now.Add(time.Minute))
if err != nil {
t.Fatal(err)
}
oldLeaf, err := validCert(exampleCertKey, oldCert.Certificate, oldCert.PrivateKey.(crypto.Signer), now)
if err != nil {
t.Fatal(err)
+3
View File
@@ -53,6 +53,9 @@ func (c *Client) registerRFC(ctx context.Context, acct *Account, prompt func(tos
Contact: acct.Contact,
}
if c.dir.Terms != "" {
if prompt == nil {
return nil, errors.New("acme: missing Manager.Prompt to accept server's terms of service")
}
req.TermsAgreed = prompt(c.dir.Terms)
}
+5 -1
View File
@@ -167,7 +167,11 @@ type OrderError struct {
}
func (oe *OrderError) Error() string {
return fmt.Sprintf("acme: order %s status: %s", oe.OrderURL, oe.Status)
str := fmt.Sprintf("acme: order %s status: %s", oe.OrderURL, oe.Status)
if oe.Problem != nil {
str += fmt.Sprintf("; problem: %s", oe.Problem)
}
return str
}
// RateLimit reports whether err represents a rate limit error and
+16
View File
@@ -217,3 +217,19 @@ func TestErrorStringerWithSubproblems(t *testing.T) {
t.Errorf("Unexpected error string: wanted %q, got %q", expectedStr, err.Error())
}
}
func TestOrderErrorProblem(t *testing.T) {
oe := &OrderError{
OrderURL: "url",
Status: "invalid",
Problem: &Error{
StatusCode: 400,
ProblemType: "type",
Detail: "detail",
},
}
want := "acme: order url status: invalid; problem: 400 type: detail"
if got := oe.Error(); got != want {
t.Errorf("oe.Error() = %q, want %q", got, want)
}
}
+2
View File
@@ -14,6 +14,8 @@ import (
"testing"
)
var _ hash.XOF = (*xof)(nil)
func fromHex(s string) []byte {
b, err := hex.DecodeString(s)
if err != nil {
-11
View File
@@ -1,11 +0,0 @@
// Copyright 2025 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build go1.25
package blake2b
import "hash"
var _ hash.XOF = (*xof)(nil)
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -20,7 +20,7 @@ func chacha20Poly1305Open(dst []byte, key []uint32, src, ad []byte) bool
func chacha20Poly1305Seal(dst []byte, key []uint32, src, ad []byte)
var (
useAVX2 = cpu.X86.HasAVX2 && cpu.X86.HasBMI2
useAVX2 = cpu.X86.HasSSSE3 && cpu.X86.HasAVX2 && cpu.X86.HasBMI2
)
// setupState writes a ChaCha20 input matrix to state. See
@@ -47,7 +47,7 @@ func setupState(state *[16]uint32, key *[32]byte, nonce []byte) {
}
func (c *chacha20poly1305) seal(dst, nonce, plaintext, additionalData []byte) []byte {
if !cpu.X86.HasSSSE3 {
if !useAVX2 {
return c.sealGeneric(dst, nonce, plaintext, additionalData)
}
@@ -66,7 +66,7 @@ func (c *chacha20poly1305) seal(dst, nonce, plaintext, additionalData []byte) []
}
func (c *chacha20poly1305) open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
if !cpu.X86.HasSSSE3 {
if !useAVX2 {
return c.openGeneric(dst, nonce, ciphertext, additionalData)
}
File diff suppressed because it is too large Load Diff
+5 -5
View File
@@ -1,11 +1,11 @@
module golang.org/x/crypto
go 1.24.0
go 1.25.0
require (
golang.org/x/net v0.48.0 // tagx:ignore
golang.org/x/sys v0.40.0
golang.org/x/term v0.39.0
golang.org/x/net v0.55.0 // tagx:ignore
golang.org/x/sys v0.46.0
golang.org/x/term v0.44.0
)
require golang.org/x/text v0.33.0 // indirect
require golang.org/x/text v0.38.0 // indirect
+8 -8
View File
@@ -1,8 +1,8 @@
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.39.0 h1:RclSuaJf32jOqZz74CkPA9qFuVTX7vhLlpfj/IGWlqY=
golang.org/x/term v0.39.0/go.mod h1:yxzUCTP/U+FzoxfdKmLaA0RV1WgE0VY7hXBwKtY/4ww=
golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE=
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc=
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE=
golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4=
+13 -8
View File
@@ -11,6 +11,7 @@
package hkdf
import (
"crypto/hkdf"
"crypto/hmac"
"errors"
"hash"
@@ -24,15 +25,19 @@ import (
// Expand invocations and different context values. Most common scenarios,
// including the generation of multiple keys, should use New instead.
func Extract(hash func() hash.Hash, secret, salt []byte) []byte {
if salt == nil {
salt = make([]byte, hash().Size())
// Use the stdlib Extract, which disables FIPS 140 enforcement of the HMAC
// key (which in HKDF is the salt). The only possible error is FIPS 140
// enforcement of the hash, which had to panic under this API anyway. We
// don't use the stdlib Expand, because it switched to returning a []byte
// instead of an io.Reader, and Expand uses the HMAC key as a key.
out, err := hkdf.Extract(hash, secret, salt)
if err != nil {
panic(err)
}
extractor := hmac.New(hash, salt)
extractor.Write(secret)
return extractor.Sum(nil)
return out
}
type hkdf struct {
type hkdfReader struct {
expander hash.Hash
size int
@@ -43,7 +48,7 @@ type hkdf struct {
buf []byte
}
func (f *hkdf) Read(p []byte) (int, error) {
func (f *hkdfReader) Read(p []byte) (int, error) {
// Check whether enough data can be generated
need := len(p)
remains := len(f.buf) + int(255-f.counter+1)*f.size
@@ -84,7 +89,7 @@ func (f *hkdf) Read(p []byte) (int, error) {
// 3.3. Most common scenarios will want to use New instead.
func Expand(hash func() hash.Hash, pseudorandomKey, info []byte) io.Reader {
expander := hmac.New(hash, pseudorandomKey)
return &hkdf{expander, expander.Size(), info, 1, nil, nil}
return &hkdfReader{expander, expander.Size(), info, 1, nil, nil}
}
// New returns a Reader, from which keys can be read, using the given hash,
+13 -60
View File
@@ -2,24 +2,17 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
Package pbkdf2 implements the key derivation function PBKDF2 as defined in RFC
2898 / PKCS #5 v2.0.
A key derivation function is useful when encrypting data based on a password
or any other not-fully-random data. It uses a pseudorandom function to derive
a secure encryption key based on the password.
While v2.0 of the standard defines only one pseudorandom function to use,
HMAC-SHA1, the drafted v2.1 specification allows use of all five FIPS Approved
Hash Functions SHA-1, SHA-224, SHA-256, SHA-384 and SHA-512 for HMAC. To
choose, you can pass the `New` functions from the different SHA packages to
pbkdf2.Key.
*/
// Package pbkdf2 implements the key derivation function PBKDF2 as defined in
// RFC 8018 (PKCS #5 v2.1).
//
// This package is a wrapper for the PBKDF2 implementation in the
// [crypto/pbkdf2] package. It is [frozen] and is not accepting new features.
//
// [frozen]: https://go.dev/wiki/Frozen
package pbkdf2
import (
"crypto/hmac"
"crypto/pbkdf2"
"hash"
)
@@ -27,51 +20,11 @@ import (
// []byte of length keylen that can be used as cryptographic key. The key is
// derived based on the method described as PBKDF2 with the HMAC variant using
// the supplied hash function.
//
// For example, to use a HMAC-SHA-1 based PBKDF2 key derivation function, you
// can get a derived key for e.g. AES-256 (which needs a 32-byte key) by
// doing:
//
// dk := pbkdf2.Key([]byte("some password"), salt, 4096, 32, sha1.New)
//
// Remember to get a good random salt. At least 8 bytes is recommended by the
// RFC.
//
// Using a higher iteration count will increase the cost of an exhaustive
// search but will also make derivation proportionally slower.
func Key(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte {
prf := hmac.New(h, password)
hashLen := prf.Size()
numBlocks := (keyLen + hashLen - 1) / hashLen
var buf [4]byte
dk := make([]byte, 0, numBlocks*hashLen)
U := make([]byte, hashLen)
for block := 1; block <= numBlocks; block++ {
// N.B.: || means concatenation, ^ means XOR
// for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter
// U_1 = PRF(password, salt || uint(i))
prf.Reset()
prf.Write(salt)
buf[0] = byte(block >> 24)
buf[1] = byte(block >> 16)
buf[2] = byte(block >> 8)
buf[3] = byte(block)
prf.Write(buf[:4])
dk = prf.Sum(dk)
T := dk[len(dk)-hashLen:]
copy(U, T)
// U_n = PRF(password, U_(n-1))
for n := 2; n <= iter; n++ {
prf.Reset()
prf.Write(U)
U = U[:0]
U = prf.Sum(U)
for x := range U {
T[x] ^= U[x]
}
}
out, err := pbkdf2.Key(h, string(password), salt, iter, keyLen)
if err != nil {
// FIPS 140 enforcement, or an invalid key length.
panic(err)
}
return dk[:keyLen]
return out
}
+4
View File
@@ -80,6 +80,10 @@ func pbDecrypterFor(algorithm pkix.AlgorithmIdentifier, password []byte) (cipher
return nil, 0, err
}
if params.Iterations < 0 || params.Iterations > maxIterations {
return nil, 0, NotImplementedError("iteration count is invalid or too high")
}
key := cipherType.deriveKey(params.Salt, password, params.Iterations)
iv := cipherType.deriveIV(params.Salt, password, params.Iterations)
+40
View File
@@ -13,6 +13,46 @@ import (
var sha1WithTripleDES = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 1, 3})
func TestPbDecrypterForIterationLimit(t *testing.T) {
pass, _ := bmpString("Sesame open")
tests := []struct {
name string
iterations int
wantErr bool
}{
{"at limit", maxIterations, false},
{"over limit", maxIterations + 1, true},
{"negative", -1, true},
{"max int", 1<<31 - 1, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
params, _ := asn1.Marshal(pbeParams{
Salt: []byte{1, 2, 3, 4, 5, 6, 7, 8},
Iterations: tt.iterations,
})
alg := pkix.AlgorithmIdentifier{
Algorithm: sha1WithTripleDES,
Parameters: asn1.RawValue{
FullBytes: params,
},
}
_, _, err := pbDecrypterFor(alg, pass)
if tt.wantErr {
if _, ok := err.(NotImplementedError); !ok {
t.Errorf("iterations=%d: got %v, want NotImplementedError", tt.iterations, err)
}
} else {
if err != nil {
t.Errorf("iterations=%d: unexpected error: %v", tt.iterations, err)
}
}
})
}
}
func TestPbDecrypterFor(t *testing.T) {
params, _ := asn1.Marshal(pbeParams{
Salt: []byte{1, 2, 3, 4, 5, 6, 7, 8},
+8
View File
@@ -27,11 +27,19 @@ var (
oidSHA1 = asn1.ObjectIdentifier([]int{1, 3, 14, 3, 2, 26})
)
// maxIterations is a safety limit to prevent CPU exhaustion from
// crafted PKCS#12 files with unreasonable iteration counts.
const maxIterations = 1 << 20 // ~1 million
func verifyMac(macData *macData, message, password []byte) error {
if !macData.Mac.Algorithm.Algorithm.Equal(oidSHA1) {
return NotImplementedError("unknown digest algorithm: " + macData.Mac.Algorithm.Algorithm.String())
}
if macData.Iterations < 0 || macData.Iterations > maxIterations {
return NotImplementedError("iteration count is invalid or too high")
}
key := pbkdf(sha1Sum, 20, 64, macData.MacSalt, password, macData.Iterations, 3, 20)
mac := hmac.New(sha1.New, key)
+42
View File
@@ -5,10 +5,52 @@
package pkcs12
import (
"crypto/x509/pkix"
"encoding/asn1"
"testing"
)
func TestVerifyMacIterationLimit(t *testing.T) {
password, _ := bmpString("Sesame open")
message := []byte{11, 12, 13, 14, 15}
tests := []struct {
name string
iterations int
wantErr bool
}{
{"at limit", maxIterations, false},
{"over limit", maxIterations + 1, true},
{"negative", -1, true},
{"max int", 1<<31 - 1, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
td := macData{
Mac: digestInfo{
Algorithm: pkix.AlgorithmIdentifier{
Algorithm: oidSHA1,
},
Digest: nil, // will fail MAC check, but iteration check comes first
},
MacSalt: []byte{1, 2, 3, 4, 5, 6, 7, 8},
Iterations: tt.iterations,
}
err := verifyMac(&td, message, password)
if tt.wantErr {
if _, ok := err.(NotImplementedError); !ok {
t.Errorf("iterations=%d: got %v, want NotImplementedError", tt.iterations, err)
}
} else {
if _, ok := err.(NotImplementedError); ok {
t.Errorf("iterations=%d: got unexpected NotImplementedError", tt.iterations)
}
}
})
}
}
func TestVerifyMac(t *testing.T) {
td := macData{
Mac: digestInfo{
+3
View File
@@ -196,6 +196,9 @@ func Key(password, salt []byte, N, r, p, keyLen int) ([]byte, error) {
if N <= 1 || N&(N-1) != 0 {
return nil, errors.New("scrypt: N must be > 1 and a power of 2")
}
if r <= 0 || p <= 0 {
return nil, errors.New("scrypt: parameters must be > 0")
}
if uint64(r)*uint64(p) >= 1<<30 || r > maxInt/128/p || r > maxInt/256 || N > maxInt/128/r {
return nil, errors.New("scrypt: parameters are too large")
}
+4
View File
@@ -133,6 +133,10 @@ var bad = []testVector{
{"p", "s", 1, 1, 1, nil}, // N == 1
{"p", "s", 7, 8, 1, nil}, // N is not power of 2
{"p", "s", 16, maxInt / 2, maxInt / 2, nil}, // p * r too large
{"p", "s", 2, 0, 1, nil}, // r too small
{"p", "s", 2, 1, 0, nil}, // p too small
{"p", "s", 2, -1, 1, nil}, // r is negative
{"p", "s", 2, 1, -1, nil}, // p is negative
}
func TestKey(t *testing.T) {
+233 -3
View File
@@ -26,6 +26,7 @@ import (
"io"
"math/big"
"sync"
"sync/atomic"
"golang.org/x/crypto/ssh"
)
@@ -307,17 +308,50 @@ func parseKey(in []byte) (out *Key, rest []byte, err error) {
}, record.Rest, nil
}
// pipelineMaxInFlight is the maximum number of outstanding requests the
// client will pipeline to the agent before applying backpressure.
const pipelineMaxInFlight = 32
// client is a client for an ssh-agent process.
//
// Exactly one of pipeline / (mu, conn) is set, chosen by NewClient
// based on whether the underlying transport implements io.Closer.
type client struct {
// conn is typically a *net.UnixConn
// pipeline, if non-nil, dispatches requests over a pipelined
// connection: requests are written as soon as the wire is
// available and responses are routed back to per-call reply
// channels in FIFO order by a background reader goroutine.
pipeline *pipeline
// mu and conn are used in fully-serialized mode, when the
// transport does not implement io.Closer. Each call takes mu,
// writes its request, reads the matching response, and releases
// mu before returning. There is no background goroutine.
mu sync.Mutex
conn io.ReadWriter
// mu is used to prevent concurrent access to the agent
mu sync.Mutex
}
// NewClient returns an Agent that talks to an ssh-agent process over
// the given connection.
//
// If rw also implements io.Closer (like *net.UnixConn and ssh.Channel
// do), the returned client pipelines concurrent requests over the
// connection: callers can issue Sign and other operations from
// multiple goroutines and they will be written to the agent as soon
// as the wire is available, rather than waiting for the previous
// responses. The ssh-agent protocol still requires responses to be
// returned in request order, so a slow request delays subsequent
// responses on the same connection (head-of-line blocking).
//
// Pipelining requires io.Closer because, on a Write error, the
// background reader goroutine must be unblocked by closing the
// underlying connection. When rw does not implement io.Closer
// this is not possible, so NewClient falls back to fully
// serializing each request: a single in-flight call at a time.
func NewClient(rw io.ReadWriter) ExtendedAgent {
if rwc, ok := rw.(io.ReadWriteCloser); ok {
return &client{pipeline: newPipeline(rwc)}
}
return &client{conn: rw}
}
@@ -340,6 +374,16 @@ func (c *client) call(req []byte) (reply interface{}, err error) {
// bytes of the response are returned; no unmarshalling is
// performed on the response.
func (c *client) callRaw(req []byte) (reply []byte, err error) {
if c.pipeline != nil {
return c.pipeline.call(req)
}
return c.serialCall(req)
}
// serialCall implements the fully-serialized request/response path
// used when the transport is not an io.Closer. It writes req under mu
// and reads the matching response before returning.
func (c *client) serialCall(req []byte) (reply []byte, err error) {
c.mu.Lock()
defer c.mu.Unlock()
@@ -577,6 +621,9 @@ func (c *client) insertKey(s interface{}, comment string, constraints []byte) er
Constraints: constraints,
})
case ed25519.PrivateKey:
if len(k) != ed25519.PrivateKeySize {
return fmt.Errorf("agent: bad ED25519 key size: %d", len(k))
}
req = ssh.Marshal(ed25519KeyMsg{
Type: ssh.KeyAlgoED25519,
Pub: []byte(k)[32:],
@@ -588,6 +635,9 @@ func (c *client) insertKey(s interface{}, comment string, constraints []byte) er
// general idiom is to pass ed25519.PrivateKey by value, not by pointer.
// We still support the pointer variant for backwards compatibility.
case *ed25519.PrivateKey:
if len(*k) != ed25519.PrivateKeySize {
return fmt.Errorf("agent: bad ED25519 key size: %d", len(*k))
}
req = ssh.Marshal(ed25519KeyMsg{
Type: ssh.KeyAlgoED25519,
Pub: []byte(*k)[32:],
@@ -663,6 +713,13 @@ func (c *client) Add(key AddedKey) error {
constraints = append(constraints, agentConstrainConfirm)
}
for _, ext := range key.ConstraintExtensions {
constraints = append(constraints, ssh.Marshal(constrainExtensionAgentMsg{
ExtensionName: ext.ExtensionName,
ExtensionDetails: ext.ExtensionDetails,
})...)
}
cert := key.Certificate
if cert == nil {
return c.insertKey(key.PrivateKey, key.Comment, constraints)
@@ -705,6 +762,9 @@ func (c *client) insertCert(s interface{}, cert *ssh.Certificate, comment string
Constraints: constraints,
})
case ed25519.PrivateKey:
if len(k) != ed25519.PrivateKeySize {
return fmt.Errorf("agent: bad ED25519 key size: %d", len(k))
}
req = ssh.Marshal(ed25519CertMsg{
Type: cert.Type(),
CertBytes: cert.Marshal(),
@@ -717,6 +777,9 @@ func (c *client) insertCert(s interface{}, cert *ssh.Certificate, comment string
// general idiom is to pass ed25519.PrivateKey by value, not by pointer.
// We still support the pointer variant for backwards compatibility.
case *ed25519.PrivateKey:
if len(*k) != ed25519.PrivateKeySize {
return fmt.Errorf("agent: bad ED25519 key size: %d", len(*k))
}
req = ssh.Marshal(ed25519CertMsg{
Type: cert.Type(),
CertBytes: cert.Marshal(),
@@ -854,3 +917,170 @@ func (c *client) Extension(extensionType string, contents []byte) ([]byte, error
return buf, nil
}
// pipelineResult carries either a raw agent reply or an error back to a
// caller waiting on the response channel.
type pipelineResult struct {
reply []byte
err error
}
// pipeline implements request pipelining over a single agent connection.
//
// Writers serialize on writeMu to both register a reply channel in the
// pending FIFO queue and write the request bytes on the wire; the two
// must be atomic so the queue order matches the wire order. A single
// reader goroutine decodes responses from the connection and dispatches
// each one to the channel at the head of the queue.
//
// pending is a chan-of-chan acting as a FIFO queue with a fixed
// capacity of pipelineMaxInFlight. The outer channel provides ordering
// (reads happen in send order) and natural backpressure (a full queue
// blocks new writers). Each inner channel is buffered with capacity
// one and is sent to exactly once: either by the reader goroutine
// with the agent reply, or by shutdown with the terminal error during
// drain. The cap-one buffer makes the producer's send non-blocking,
// so the reader and shutdown never have to wait for the caller to be
// scheduled on the receive.
//
// When the reader goroutine exits (on read error or protocol
// violation), it closes exitCh to wake any writer blocked on the
// pending queue, then serializes with any in-flight writer to close
// the pending channel, and finally drains the remaining entries
// delivering the terminal error to each waiting caller. The
// pipeline relies on conn implementing io.Closer so a writer that
// hits a Write error can close the connection to unblock the reader
// goroutine; NewClient is responsible for only constructing a
// pipeline when this guarantee holds.
type pipeline struct {
conn io.ReadWriteCloser
writeMu sync.Mutex
// pending is the FIFO queue of reply channels with capacity
// pipelineMaxInFlight. See type-level documentation.
pending chan chan pipelineResult
exitCh chan struct{}
// err carries the terminal error to callers blocked on a closed
// pipeline. It is stored exactly once by the reader goroutine
// before exitCh is closed; every read happens after observing
// exitCh closed, so the load synchronises through the close and
// is guaranteed to return the stored value (never nil).
err atomic.Pointer[error]
}
func newPipeline(conn io.ReadWriteCloser) *pipeline {
p := &pipeline{
conn: conn,
pending: make(chan chan pipelineResult, pipelineMaxInFlight),
exitCh: make(chan struct{}),
}
go p.readLoop()
return p
}
// readLoop decodes responses from conn and dispatches them in FIFO order
// to reply channels in pending. On any failure it invokes shutdown.
func (p *pipeline) readLoop() {
var finalErr error
for {
var sizeBuf [4]byte
if _, err := io.ReadFull(p.conn, sizeBuf[:]); err != nil {
finalErr = err
break
}
respSize := binary.BigEndian.Uint32(sizeBuf[:])
if respSize > maxAgentResponseBytes {
finalErr = errors.New("response too large")
break
}
buf := make([]byte, respSize)
if _, err := io.ReadFull(p.conn, buf); err != nil {
finalErr = err
break
}
// Successful writes always enqueue before sending bytes, so
// pending has a waiting channel for this response.
ch := <-p.pending
// The reply channel is buffered with capacity 1 and is only
// ever written to once, so this send cannot block.
ch <- pipelineResult{reply: buf}
}
p.shutdown(clientErr(finalErr))
}
// shutdown is called exactly once, from readLoop, when the reader is
// terminating. It unblocks pending writers and fails all in-flight
// requests with finalErr.
func (p *pipeline) shutdown(finalErr error) {
// Publish the terminal error before closing exitCh so any
// writer that subsequently observes exitCh closed sees err.
p.err.Store(&finalErr)
// Wake any writer blocked waiting for a slot in the pending queue.
close(p.exitCh)
// Wait for any writer currently inside its critical section to
// complete. After this lock, no new writer can reach the send on
// pending: they will observe exitCh closed in the select and bail
// out before attempting the send.
p.writeMu.Lock()
close(p.pending)
p.writeMu.Unlock()
// Drain entries that were enqueued but never answered, delivering
// the terminal error to their waiting callers. The reply channels
// are buffered (cap 1) and written to exactly once, so these sends
// cannot block.
for ch := range p.pending {
ch <- pipelineResult{err: finalErr}
}
}
// call sends req to the agent and returns the matching raw response.
func (p *pipeline) call(req []byte) ([]byte, error) {
replyCh := make(chan pipelineResult, 1)
p.writeMu.Lock()
// Priority check: if the reader has already finished shutdown,
// pending is closed and sending to it would panic. Bail out now.
// Once we pass this check while holding writeMu, shutdown cannot
// complete close(pending) until we release writeMu, so the send
// below is safe against concurrent closure.
select {
case <-p.exitCh:
p.writeMu.Unlock()
return nil, *p.err.Load()
default:
}
// Enqueue the reply channel before writing the request, so FIFO
// order on the wire matches FIFO order in the pending queue. The
// exitCh arm handles the case where the reader errors while we
// block on a full queue.
select {
case p.pending <- replyCh:
case <-p.exitCh:
p.writeMu.Unlock()
return nil, *p.err.Load()
}
msg := make([]byte, 4+len(req))
binary.BigEndian.PutUint32(msg, uint32(len(req)))
copy(msg[4:], req)
_, werr := p.conn.Write(msg)
p.writeMu.Unlock()
if werr != nil {
// The connection is in an undefined state. Close it so the
// reader unblocks promptly and triggers shutdown for every
// other in-flight caller. NewClient guarantees conn is a
// real io.Closer when the pipeline is in use.
p.conn.Close()
return nil, clientErr(werr)
}
res := <-replyCh
return res.reply, res.err
}
+649
View File
@@ -0,0 +1,649 @@
// Copyright 2026 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package agent
import (
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestPipelineParallelSigns(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
keyring := NewKeyring()
if err := keyring.Add(AddedKey{PrivateKey: testPrivateKeys["rsa"]}); err != nil {
t.Fatal(err)
}
go ServeAgent(keyring, c2)
client := NewClient(c1)
pubKey := testPublicKeys["rsa"]
const N = 64
var wg sync.WaitGroup
errCh := make(chan error, N)
for i := range N {
wg.Go(func() {
data := []byte{byte(i), byte(i >> 8)}
sig, err := client.Sign(pubKey, data)
if err != nil {
errCh <- err
return
}
if err := pubKey.Verify(data, sig); err != nil {
errCh <- err
}
})
}
wg.Wait()
close(errCh)
for err := range errCh {
t.Error(err)
}
}
func TestPipelineBackpressure(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
const total = pipelineMaxInFlight + 8
// Fake agent: the reader drains requests from the wire independently
// of response production, so the write path is never self-blocked.
// The responder only writes a canned success reply once unblocked
// via gate.
var reqsRead int64
gate := make(chan struct{}, total)
pending := make(chan struct{}, total+pipelineMaxInFlight)
readerDone := make(chan struct{})
responderDone := make(chan struct{})
go func() {
defer close(readerDone)
defer close(pending)
for {
var sizeBuf [4]byte
if _, err := io.ReadFull(c2, sizeBuf[:]); err != nil {
return
}
size := binary.BigEndian.Uint32(sizeBuf[:])
req := make([]byte, size)
if _, err := io.ReadFull(c2, req); err != nil {
return
}
atomic.AddInt64(&reqsRead, 1)
pending <- struct{}{}
}
}()
go func() {
defer close(responderDone)
for range pending {
<-gate
var out [5]byte
binary.BigEndian.PutUint32(out[:4], 1)
out[4] = agentSuccess
if _, err := c2.Write(out[:]); err != nil {
return
}
}
}()
defer func() {
c1.Close()
c2.Close()
<-readerDone
<-responderDone
}()
client := NewClient(c1)
var wg sync.WaitGroup
errs := make(chan error, total)
for range total {
wg.Go(func() {
// RemoveAll maps to a simpleCall expecting agentSuccess.
if err := client.RemoveAll(); err != nil {
errs <- err
}
})
}
// Wait for the client to fill the pipeline.
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
if atomic.LoadInt64(&reqsRead) >= pipelineMaxInFlight {
break
}
time.Sleep(5 * time.Millisecond)
}
if got := atomic.LoadInt64(&reqsRead); got != pipelineMaxInFlight {
t.Errorf("requests in flight before any response: got %d, want %d", got, pipelineMaxInFlight)
}
// Release all responses; every caller should eventually complete.
for range total {
gate <- struct{}{}
}
wg.Wait()
close(errs)
for err := range errs {
t.Error(err)
}
if got := atomic.LoadInt64(&reqsRead); got != total {
t.Errorf("total requests received: got %d, want %d", got, total)
}
}
func TestPipelineConnCloseFailsInFlight(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
// Server that reads requests but never replies, so all calls are
// parked waiting for responses.
serverExit := make(chan struct{})
go func() {
defer close(serverExit)
buf := make([]byte, 4096)
for {
if _, err := c2.Read(buf); err != nil {
return
}
}
}()
client := NewClient(c1)
const N = 8
var wg sync.WaitGroup
errs := make(chan error, N)
for range N {
wg.Go(func() {
errs <- client.RemoveAll()
})
}
// Give callers time to enter the pipeline, then tear down the conn.
time.Sleep(50 * time.Millisecond)
c1.Close()
c2.Close()
// All callers must return promptly with an error.
doneCh := make(chan struct{})
go func() {
wg.Wait()
close(doneCh)
}()
select {
case <-doneCh:
case <-time.After(5 * time.Second):
t.Fatal("pipelined callers did not complete after conn close")
}
close(errs)
for err := range errs {
if err == nil {
t.Error("expected error after conn close, got nil")
}
}
// Subsequent calls also fail fast rather than hanging.
errCh := make(chan error, 1)
go func() { errCh <- client.RemoveAll() }()
select {
case err := <-errCh:
if err == nil {
t.Error("expected error on post-close call, got nil")
}
case <-time.After(2 * time.Second):
t.Fatal("post-close call hung")
}
<-serverExit
}
// readWriter exposes only io.Reader and io.Writer, hiding any Close
// method on the wrapped value so NewClient cannot take the pipelined
// path.
type readWriter struct {
io.Reader
io.Writer
}
func TestNewClientSerialFallback(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
keyring := NewKeyring()
if err := keyring.Add(AddedKey{PrivateKey: testPrivateKeys["rsa"]}); err != nil {
t.Fatal(err)
}
go ServeAgent(keyring, c2)
rw := readWriter{Reader: c1, Writer: c1}
ag := NewClient(rw)
ci, ok := ag.(*client)
if !ok {
t.Fatalf("NewClient: got %T, want *client", ag)
}
if ci.pipeline != nil {
t.Error("NewClient with non-Closer rw: pipeline must be nil")
}
if ci.conn == nil {
t.Error("NewClient with non-Closer rw: conn must be set")
}
// The serialized path correctly handles a request/response cycle.
keys, err := ag.List()
if err != nil {
t.Fatalf("List: %v", err)
}
if len(keys) != 1 {
t.Errorf("List: got %d keys, want 1", len(keys))
}
}
func TestSerialFallbackParallelSigns(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
keyring := NewKeyring()
if err := keyring.Add(AddedKey{PrivateKey: testPrivateKeys["rsa"]}); err != nil {
t.Fatal(err)
}
go ServeAgent(keyring, c2)
rw := readWriter{Reader: c1, Writer: c1}
ag := NewClient(rw)
if ci, ok := ag.(*client); !ok {
t.Fatalf("NewClient: got %T, want *client", ag)
} else if ci.pipeline != nil {
t.Fatal("pipeline must be nil for non-Closer rw")
}
pubKey := testPublicKeys["rsa"]
const N = 64
var wg sync.WaitGroup
errCh := make(chan error, N)
for i := range N {
wg.Go(func() {
data := []byte{byte(i), byte(i >> 8)}
sig, err := ag.Sign(pubKey, data)
if err != nil {
errCh <- err
return
}
if err := pubKey.Verify(data, sig); err != nil {
errCh <- err
}
})
}
wg.Wait()
close(errCh)
for err := range errCh {
t.Error(err)
}
}
// writeFailConn wraps a net.Conn and forces Write to return an error when
// the fail flag is set. Close delegates to the underlying conn so the test
// can observe whether the pipeline closed it.
type writeFailConn struct {
net.Conn
fail atomic.Bool
}
func (c *writeFailConn) Write(p []byte) (int, error) {
if c.fail.Load() {
return 0, errors.New("synthetic write failure")
}
return c.Conn.Write(p)
}
func TestPipelineWriteErrorClosesConn(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c2.Close()
// Peer that reads and discards, exiting when the conn closes.
serverExit := make(chan struct{})
go func() {
defer close(serverExit)
io.Copy(io.Discard, c2)
}()
wrapper := &writeFailConn{Conn: c1}
wrapper.fail.Store(true)
client := NewClient(wrapper)
errCh := make(chan error, 1)
go func() { errCh <- client.RemoveAll() }()
select {
case err := <-errCh:
if err == nil {
t.Fatal("expected error on forced write failure, got nil")
}
// The caller whose Write failed must receive the actual
// write error, not the reader's "closed connection" error
// from the post-shutdown drain.
if !strings.Contains(err.Error(), "synthetic write failure") {
t.Errorf("got %q, want error containing %q", err, "synthetic write failure")
}
case <-time.After(2 * time.Second):
t.Fatal("RemoveAll hung after write failure")
}
// The pipeline must have closed the underlying conn, so the peer
// goroutine returns from its Read.
select {
case <-serverExit:
case <-time.After(2 * time.Second):
t.Fatal("connection was not closed after write failure")
}
// After shutdown, subsequent calls must also fail promptly.
errCh2 := make(chan error, 1)
go func() { errCh2 <- client.RemoveAll() }()
select {
case err := <-errCh2:
if err == nil {
t.Error("expected error on post-shutdown call, got nil")
}
case <-time.After(2 * time.Second):
t.Fatal("post-shutdown call hung")
}
}
func TestPipelineResponseTooLarge(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
// Server: read the request, then reply with a size header that
// exceeds maxAgentResponseBytes. The size check fires before the
// body is read, so no body needs to follow.
serverDone := make(chan struct{})
go func() {
defer close(serverDone)
var sizeBuf [4]byte
if _, err := io.ReadFull(c2, sizeBuf[:]); err != nil {
return
}
size := binary.BigEndian.Uint32(sizeBuf[:])
if _, err := io.CopyN(io.Discard, c2, int64(size)); err != nil {
return
}
var out [4]byte
binary.BigEndian.PutUint32(out[:], maxAgentResponseBytes+1)
c2.Write(out[:])
}()
client := NewClient(c1)
errCh := make(chan error, 1)
go func() { errCh <- client.RemoveAll() }()
select {
case err := <-errCh:
if err == nil {
t.Fatal("expected error, got nil")
}
if !strings.Contains(err.Error(), "response too large") {
t.Errorf("got %q, want error containing %q", err, "response too large")
}
case <-time.After(2 * time.Second):
t.Fatal("call hung")
}
// Subsequent calls must also fail: the pipeline is shut down.
errCh2 := make(chan error, 1)
go func() { errCh2 <- client.RemoveAll() }()
select {
case err := <-errCh2:
if err == nil {
t.Error("expected error on post-shutdown call, got nil")
}
case <-time.After(2 * time.Second):
t.Fatal("post-shutdown call hung")
}
<-serverDone
}
func TestPipelineShutdownWithBlockedWriter(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
// Server drains requests off the wire so writes never block on
// backpressure from the transport, but never replies. The reader
// goroutine therefore stays parked on Read, never dequeues from
// pending, and the queue fills up.
var reqsRead int64
serverExit := make(chan struct{})
go func() {
defer close(serverExit)
for {
var sizeBuf [4]byte
if _, err := io.ReadFull(c2, sizeBuf[:]); err != nil {
return
}
size := binary.BigEndian.Uint32(sizeBuf[:])
if _, err := io.CopyN(io.Discard, c2, int64(size)); err != nil {
return
}
atomic.AddInt64(&reqsRead, 1)
}
}()
client := NewClient(c1)
const total = pipelineMaxInFlight + 4
var wg sync.WaitGroup
errs := make(chan error, total)
for range total {
wg.Go(func() {
errs <- client.RemoveAll()
})
}
// Wait for the queue to fill: once pipelineMaxInFlight requests
// are on the wire, pending is at capacity and the +1 writer is
// blocked in the second-select arm; the rest are queued behind
// writeMu.
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
if atomic.LoadInt64(&reqsRead) >= pipelineMaxInFlight {
break
}
time.Sleep(5 * time.Millisecond)
}
if got := atomic.LoadInt64(&reqsRead); got < pipelineMaxInFlight {
t.Fatalf("requests on wire: got %d, want >= %d", got, pipelineMaxInFlight)
}
// Give the +1 writer a moment to actually park in the second
// select before we trigger shutdown.
time.Sleep(50 * time.Millisecond)
// Trigger shutdown: closing the server side makes the client's
// reader hit EOF, which calls shutdown(...).
c2.Close()
doneCh := make(chan struct{})
go func() {
wg.Wait()
close(doneCh)
}()
select {
case <-doneCh:
case <-time.After(5 * time.Second):
t.Fatal("blocked callers did not complete after shutdown")
}
close(errs)
for err := range errs {
if err == nil {
t.Error("expected error after shutdown, got nil")
}
}
<-serverExit
}
// multiDeviceAgent simulates an ssh-agent backed by numDevices signing
// devices, each of which takes latency to process a request. Incoming
// requests are round-robin dispatched to devices, and responses are
// serialized back to the wire in request order as the protocol requires.
//
// The simulation does not emit a semantically meaningful reply; it just
// writes a 1-byte SSH_AGENT_SUCCESS after the simulated latency has
// elapsed. This is enough to exercise callRaw/simpleCall (RemoveAll).
func multiDeviceAgent(t testing.TB, conn io.ReadWriteCloser, numDevices int, latency time.Duration) (done <-chan struct{}) {
t.Helper()
type job struct {
ready chan struct{}
}
devices := make([]chan job, numDevices)
var devicesWG sync.WaitGroup
for i := range numDevices {
devices[i] = make(chan job, 1024)
ch := devices[i]
devicesWG.Go(func() {
for j := range ch {
time.Sleep(latency)
close(j.ready)
}
})
}
// Order-preserving responder: responses are written in the same
// order the requests were read, regardless of which device finished
// first.
orderCh := make(chan chan struct{}, 1024)
responderDone := make(chan struct{})
go func() {
defer close(responderDone)
for ready := range orderCh {
<-ready
var out [5]byte
binary.BigEndian.PutUint32(out[:4], 1)
out[4] = agentSuccess
if _, err := conn.Write(out[:]); err != nil {
return
}
}
}()
finished := make(chan struct{})
go func() {
defer close(finished)
defer func() {
close(orderCh)
<-responderDone
for _, d := range devices {
close(d)
}
devicesWG.Wait()
}()
next := 0
for {
var sizeBuf [4]byte
if _, err := io.ReadFull(conn, sizeBuf[:]); err != nil {
return
}
size := binary.BigEndian.Uint32(sizeBuf[:])
if _, err := io.CopyN(io.Discard, conn, int64(size)); err != nil {
return
}
ready := make(chan struct{})
devices[next%numDevices] <- job{ready: ready}
next++
orderCh <- ready
}
}()
return finished
}
// BenchmarkPipelineMultiDevice measures throughput of the pipelined
// agent client against a simulated multi-device agent, varying the
// number of backend devices.
//
// Setup: each simulated signing device takes 2ms per request. The
// protocol serializes responses in request order, but pipelining lets
// the client keep multiple devices busy concurrently; throughput
// should scale roughly linearly with numDevices up to the pipeline
// depth (pipelineMaxInFlight).
//
// Run with: go test -benchmem -bench BenchmarkPipelineMultiDevice -benchtime=2s ./ssh/agent/
func BenchmarkPipelineMultiDevice(b *testing.B) {
const (
deviceLatency = 2 * time.Millisecond
parallelism = 32
)
for _, numDevices := range []int{1, 2, 4, 8, 16} {
b.Run(fmt.Sprintf("Devices=%d", numDevices), func(b *testing.B) {
c1, c2, err := netPipe()
if err != nil {
b.Fatalf("netPipe: %v", err)
}
serverDone := multiDeviceAgent(b, c2, numDevices, deviceLatency)
client := NewClient(c1)
b.ResetTimer()
b.SetParallelism(parallelism)
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
if err := client.RemoveAll(); err != nil {
b.Fatal(err)
}
}
})
b.StopTimer()
c1.Close()
c2.Close()
<-serverDone
})
}
}
+94
View File
@@ -6,6 +6,7 @@ package agent
import (
"bytes"
"crypto/ed25519"
"crypto/rand"
"encoding/binary"
"errors"
@@ -594,3 +595,96 @@ func TestAgentExtensions(t *testing.T) {
t.Fatal("should have gotten agent extension failure")
}
}
// capturingAgent records the AddedKey observed on the server side of the
// agent protocol. It forwards to a keyring with constraint fields stripped,
// so the keyring's own rejection of unsupported constraints does not
// interfere with what this test is measuring: the client-side wire
// serialization of ConstraintExtensions.
type capturingAgent struct {
Agent
lastAdd AddedKey
}
func newCapturingAgent() *capturingAgent {
return &capturingAgent{Agent: NewKeyring()}
}
func (a *capturingAgent) Add(key AddedKey) error {
a.lastAdd = key
stripped := key
stripped.ConstraintExtensions = nil
stripped.ConfirmBeforeUse = false
return a.Agent.Add(stripped)
}
// TestAddConstraintExtensionsWireFormat verifies that client.Add serializes
// ConstraintExtensions into the SSH_AGENTC_ADD_IDENTITY payload and the
// server deserializes them back into the AddedKey delivered to the backend.
// Regressions in the client marshal loop (missing, swapped fields, wrong
// framing) would be invisible to a keyring-based rejection test, which
// signals only "extensions were present", not "the right ones arrived".
func TestAddConstraintExtensionsWireFormat(t *testing.T) {
capturing := newCapturingAgent()
client, cleanup := startAgent(t, capturing)
defer cleanup()
constraints := []ConstraintExtension{
{ExtensionName: "ext-one@example.com", ExtensionDetails: []byte("details-one")},
{ExtensionName: "ext-two@example.com", ExtensionDetails: []byte("\x00\x01\x02\xff")},
}
if err := client.Add(AddedKey{
PrivateKey: testPrivateKeys["rsa"],
Comment: "wire-format-test",
ConstraintExtensions: constraints,
}); err != nil {
t.Fatalf("client.Add: %v", err)
}
got := capturing.lastAdd.ConstraintExtensions
if len(got) != len(constraints) {
t.Fatalf("server received %d extensions, want %d", len(got), len(constraints))
}
for i, want := range constraints {
if got[i].ExtensionName != want.ExtensionName {
t.Errorf("extension[%d] name: got %q, want %q", i, got[i].ExtensionName, want.ExtensionName)
}
if !bytes.Equal(got[i].ExtensionDetails, want.ExtensionDetails) {
t.Errorf("extension[%d] details: got %x, want %x", i, got[i].ExtensionDetails, want.ExtensionDetails)
}
}
}
func TestAddRejectsShortEd25519Key(t *testing.T) {
short := ed25519.PrivateKey(make([]byte, 16))
// insertCert reaches its ed25519 branch only when AddedKey.Certificate
// is non-nil. The length check returns before cert.Type/Marshal run, so
// an empty certificate is sufficient to drive the path.
emptyCert := &ssh.Certificate{}
cases := []struct {
name string
add AddedKey
}{
{"insertKey value", AddedKey{PrivateKey: short}},
{"insertKey pointer", AddedKey{PrivateKey: &short}},
{"insertCert value", AddedKey{PrivateKey: short, Certificate: emptyCert}},
{"insertCert pointer", AddedKey{PrivateKey: &short, Certificate: emptyCert}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
client, cleanup := startKeyringAgent(t)
defer cleanup()
err := client.Add(tc.add)
if err == nil {
t.Fatal("Add accepted ed25519 key shorter than 64 bytes")
}
if !strings.Contains(err.Error(), "bad ED25519 key size") {
t.Errorf("got error %q, want substring %q", err.Error(), "bad ED25519 key size")
}
})
}
}
+18 -5
View File
@@ -32,8 +32,10 @@ type keyring struct {
var errLocked = errors.New("agent: locked")
// NewKeyring returns an Agent that holds keys in memory. It is safe
// for concurrent use by multiple goroutines.
// NewKeyring returns an Agent that holds keys in memory. It is safe for
// concurrent use by multiple goroutines.
//
// The returned Agent only supports the "lifetime" constraint.
func NewKeyring() Agent {
return &keyring{}
}
@@ -143,15 +145,26 @@ func (r *keyring) List() ([]*Key, error) {
return ids, nil
}
// Insert adds a private key to the keyring. If a certificate
// is given, that certificate is added as public key. Note that
// any constraints given are ignored.
// Add adds a private key to the keyring. If a certificate is given, that
// certificate is added as public key.
//
// Add returns an error if key contains ConstraintExtensions or
// ConfirmBeforeUse.
func (r *keyring) Add(key AddedKey) error {
r.mu.Lock()
defer r.mu.Unlock()
if r.locked {
return errLocked
}
if key.ConfirmBeforeUse {
return errors.New("agent: confirm before use constraint is not supported")
}
if len(key.ConstraintExtensions) > 0 {
return errors.New("agent: constraint extensions are present but not supported")
}
signer, err := ssh.NewSignerFromKey(key.PrivateKey)
if err != nil {
+39
View File
@@ -120,3 +120,42 @@ func TestAddDuplicateKey(t *testing.T) {
t.Fatal("key with the updated comment not found")
}
}
func TestAddKeyWithConstraints(t *testing.T) {
// Verifies the keyring refuses keys carrying constraint extensions it
// cannot enforce.
agent, cleanup := startKeyringAgent(t)
defer cleanup()
constraints := []ConstraintExtension{
{
ExtensionName: "extension1",
ExtensionDetails: []byte("details1"),
},
}
key := testPrivateKeys["rsa"]
err := agent.Add(AddedKey{
PrivateKey: key,
ConstraintExtensions: constraints,
})
if err == nil {
t.Fatal("adding a key with unsupported constraints succeeded")
}
}
func TestAddKeyWithConfirmBeforeUse(t *testing.T) {
agent, cleanup := startKeyringAgent(t)
defer cleanup()
key := testPrivateKeys["rsa"]
err := agent.Add(AddedKey{
PrivateKey: key,
ConfirmBeforeUse: true,
})
if err == nil {
t.Fatal("adding a key with confirm before use constraint succeeded")
}
}
+33 -5
View File
@@ -36,7 +36,7 @@ func (s *server) processRequestBytes(reqData []byte) []byte {
return []byte{agentFailure}
}
if err == nil && rep == nil {
if rep == nil {
return []byte{agentSuccess}
}
@@ -240,13 +240,35 @@ func setConstraints(key *AddedKey, constraintBytes []byte) error {
return nil
}
// checkRSAKeyParams enforces the same bounds as parseRSA in the ssh
// package, and additionally caps the prime factors. Without this,
// the rsa.PrivateKey built from an Add request would call Precompute()
// on arbitrary inputs; the CRT coefficient recomputation is cubic in
// |p| and can consume excessive CPU on oversized keys.
func checkRSAKeyParams(N, E, P, Q *big.Int) error {
if N.BitLen() > 8192 {
return errors.New("agent: RSA modulus too large")
}
if P.BitLen() > 4096 || Q.BitLen() > 4096 {
return errors.New("agent: RSA prime too large")
}
if E.BitLen() > 24 {
return errors.New("agent: RSA public exponent too large")
}
e := E.Int64()
if e < 3 || e&1 == 0 {
return errors.New("agent: incorrect RSA public exponent")
}
return nil
}
func parseRSAKey(req []byte) (*AddedKey, error) {
var k rsaKeyMsg
if err := ssh.Unmarshal(req, &k); err != nil {
return nil, err
}
if k.E.BitLen() > 30 {
return nil, errors.New("agent: RSA public exponent too large")
if err := checkRSAKeyParams(k.N, k.E, k.P, k.Q); err != nil {
return nil, err
}
priv := &rsa.PrivateKey{
PublicKey: rsa.PublicKey{
@@ -270,6 +292,9 @@ func parseEd25519Key(req []byte) (*AddedKey, error) {
if err := ssh.Unmarshal(req, &k); err != nil {
return nil, err
}
if len(k.Priv) != ed25519.PrivateKeySize {
return nil, fmt.Errorf("agent: bad ED25519 key size: %d", len(k.Priv))
}
priv := ed25519.PrivateKey(k.Priv)
addedKey := &AddedKey{PrivateKey: &priv, Comment: k.Comments}
@@ -336,6 +361,9 @@ func parseEd25519Cert(req []byte) (*AddedKey, error) {
if err != nil {
return nil, err
}
if len(k.Priv) != ed25519.PrivateKeySize {
return nil, fmt.Errorf("agent: bad ED25519 key size: %d", len(k.Priv))
}
priv := ed25519.PrivateKey(k.Priv)
cert, ok := pubKey.(*ssh.Certificate)
if !ok {
@@ -393,8 +421,8 @@ func parseRSACert(req []byte) (*AddedKey, error) {
return nil, fmt.Errorf("agent: Unmarshal failed to parse public key: %v", err)
}
if rsaPub.E.BitLen() > 30 {
return nil, errors.New("agent: RSA public exponent too large")
if err := checkRSAKeyParams(rsaPub.N, rsaPub.E, k.P, k.Q); err != nil {
return nil, err
}
priv := rsa.PrivateKey{
+32
View File
@@ -271,3 +271,35 @@ func TestParseConstraints(t *testing.T) {
t.Errorf("unexpected error: %v", err)
}
}
func TestParseEd25519KeyShortPanic(t *testing.T) {
msg := ssh.Marshal(ed25519KeyMsg{
Type: ssh.KeyAlgoED25519,
Pub: []byte{1, 2, 3},
Priv: []byte{1, 2, 3, 4, 5},
})
a, b, err := netPipe()
if err != nil {
t.Fatal(err)
}
defer a.Close()
defer b.Close()
done := make(chan error, 1)
go func() { done <- ServeAgent(NewKeyring(), a) }()
c := NewClient(b)
_, err = c.(*client).call(msg)
if err != nil {
t.Fatal(err)
}
keys, err := c.List()
if err != nil {
t.Fatalf("agent died: %v", err)
}
if len(keys) != 0 {
t.Error("short ed25519 key was accepted into keyring")
}
}
+17 -1
View File
@@ -348,6 +348,9 @@ func (c *CertChecker) CheckHostKey(addr string, remote net.Addr, key PublicKey)
if cert.CertType != HostCert {
return fmt.Errorf("ssh: certificate presented as a host key has type %d", cert.CertType)
}
if c.IsHostAuthority == nil {
return errors.New("ssh: cannot verify certificate, IsHostAuthority not set")
}
if !c.IsHostAuthority(cert.SignatureKey, addr) {
return fmt.Errorf("ssh: no authorities for hostname: %v", addr)
}
@@ -375,6 +378,9 @@ func (c *CertChecker) Authenticate(conn ConnMetadata, pubKey PublicKey) (*Permis
if cert.CertType != UserCert {
return nil, fmt.Errorf("ssh: cert has type %d", cert.CertType)
}
if c.IsUserAuthority == nil {
return nil, errors.New("ssh: cannot verify certificate, IsUserAuthority not set")
}
if !c.IsUserAuthority(cert.SignatureKey) {
return nil, fmt.Errorf("ssh: certificate signed by unrecognized authority")
}
@@ -438,7 +444,17 @@ func (c *CertChecker) CheckCert(principal string, cert *Certificate) error {
if before := int64(cert.ValidBefore); cert.ValidBefore != uint64(CertTimeInfinity) && (unixNow >= before || before < 0) {
return fmt.Errorf("ssh: cert has expired")
}
if err := cert.SignatureKey.Verify(cert.bytesForSigning(), cert.Signature); err != nil {
// Match OpenSSH: the SK user-presence flag is never enforced on a
// certificate's CA signature. OpenSSH calls sshkey_verify with
// detailsp==NULL in sshkey.c:cert_parse, so the UP/UV flags are
// not even extracted. The UP bit on a CA signature reflects the
// CA operator's presence at signing time, which has no bearing on
// whether the user being authenticated is present now; enforcing
// it here would only break interop with certificates issued by
// non-interactive SK CAs. skKeyWithoutUP is a no-op for non-SK
// keys (the common case).
caKey := skKeyWithoutUP(cert.SignatureKey)
if err := caKey.Verify(cert.bytesForSigning(), cert.Signature); err != nil {
return fmt.Errorf("ssh: certificate signature does not verify")
}
+99 -4
View File
@@ -9,8 +9,10 @@ import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"fmt"
"io"
"math/big"
"net"
"reflect"
"testing"
@@ -128,6 +130,103 @@ func TestValidateCert(t *testing.T) {
}
}
// signSKCert builds an SK-ECDSA signature over cert.bytesForSigning()
// using caKey as the simulated hardware token. The SK signing flags
// byte (UP bit and others) is caller-controlled so tests can exercise
// the user-presence enforcement paths. caApp is the SK application
// string (typically "ssh:").
func signSKCert(t *testing.T, cert *Certificate, caKey *ecdsa.PrivateKey, caApp string, flags byte) {
t.Helper()
cert.SignatureKey = &skECDSAPublicKey{
application: caApp,
PublicKey: caKey.PublicKey,
}
cert.Nonce = make([]byte, 32)
if _, err := rand.Read(cert.Nonce); err != nil {
t.Fatal(err)
}
h := sha256.New()
h.Write([]byte(caApp))
appDigest := h.Sum(nil)
h.Reset()
h.Write(cert.bytesForSigning())
dataDigest := h.Sum(nil)
var counter uint32 = 1
blob := struct {
ApplicationDigest []byte `ssh:"rest"`
Flags byte
Counter uint32
MessageDigest []byte `ssh:"rest"`
}{appDigest, flags, counter, dataDigest}
h.Reset()
h.Write(Marshal(blob))
digest := h.Sum(nil)
r, s, err := ecdsa.Sign(rand.Reader, caKey, digest)
if err != nil {
t.Fatal(err)
}
cert.Signature = &Signature{
Format: KeyAlgoSKECDSA256,
Blob: Marshal(struct{ R, S *big.Int }{r, s}),
Rest: Marshal(struct {
Flags byte
Counter uint32
}{flags, counter}),
}
}
// TestCheckCertSKAuthorityNoUPRequired pins the OpenSSH-parity
// behavior of CertChecker.CheckCert for SK CA signatures: a
// certificate signed by an SK CA that produced a UP=0 signature is
// accepted, because the UP bit on a CA signature has no bearing on
// the current user authentication (see sshkey.c:cert_parse, which
// passes detailsp==NULL to sshkey_verify). Without this, certs issued
// by non-interactive SK CAs would fail to verify.
func TestCheckCertSKAuthorityNoUPRequired(t *testing.T) {
caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
userKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
userPub, err := NewPublicKey(&userKey.PublicKey)
if err != nil {
t.Fatal(err)
}
mkCert := func(flags byte) *Certificate {
c := &Certificate{
CertType: UserCert,
Key: userPub,
ValidBefore: CertTimeInfinity,
ValidPrincipals: []string{"user"},
}
signSKCert(t, c, caKey, "ssh:", flags)
return c
}
checker := CertChecker{
IsUserAuthority: func(k PublicKey) bool {
caSK := &skECDSAPublicKey{application: "ssh:", PublicKey: caKey.PublicKey}
return bytes.Equal(k.Marshal(), caSK.Marshal())
},
}
// Both UP=0 and UP=1 CA signatures verify: UP is not enforced
// here, matching OpenSSH.
if err := checker.CheckCert("user", mkCert(0)); err != nil {
t.Errorf("UP=0 CA signature must verify (OpenSSH parity): %v", err)
}
if err := checker.CheckCert("user", mkCert(flagUserPresence)); err != nil {
t.Errorf("UP=1 CA signature must verify: %v", err)
}
}
func TestValidateCertTime(t *testing.T) {
cert := Certificate{
ValidPrincipals: []string{"user"},
@@ -330,10 +429,6 @@ func TestCertTypes(t *testing.T) {
go NewServerConn(c1, conf)
priv := m.signer
if err != nil {
t.Fatalf("error generating ssh pubkey: %v", err)
}
cert := &Certificate{
CertType: UserCert,
Key: priv.PublicKey(),
+62 -6
View File
@@ -11,6 +11,7 @@ import (
"io"
"log"
"sync"
"sync/atomic"
)
const (
@@ -131,11 +132,17 @@ func (r RejectionReason) String() string {
return fmt.Sprintf("unknown reason %d", int(r))
}
func min(a uint32, b int) uint32 {
if a < uint32(b) {
return a
// minPayloadSize returns min(limit, length) clamped to a uint32. It is used
// to compute the size of the next channel data packet from the remaining
// payload. The comparison is done in int64 because length is an int — on
// 64-bit systems len(data) can exceed 2^32, and a direct uint32(length)
// cast would silently truncate to 0 at every multiple of 2^32, causing
// WriteExtended's loop to spin without making progress.
func minPayloadSize(limit uint32, length int) uint32 {
if int64(length) > int64(limit) {
return limit
}
return uint32(b)
return uint32(length)
}
type channelDirection uint8
@@ -177,6 +184,12 @@ type channel struct {
// with WantReply=true outstanding. This lock is held by a
// goroutine that has such an outgoing request pending.
sentRequestMu sync.Mutex
// sentRequestPending is set to true while a SendRequest call with
// WantReply=true is in flight. handlePacket uses it as a gate: responses
// arriving while no request is pending are dropped to prevent a
// misbehaving peer from stalling the mux read loop by filling ch.msg
// with unsolicited channelRequestSuccess/Failure messages.
sentRequestPending atomic.Bool
incomingRequests chan *Request
@@ -251,7 +264,7 @@ func (ch *channel) WriteExtended(data []byte, extendedCode uint32) (n int, err e
ch.writeMu.Unlock()
for len(data) > 0 {
space := min(ch.maxRemotePayload, len(data))
space := minPayloadSize(ch.maxRemotePayload, len(data))
if space, err = ch.remoteWin.reserve(space); err != nil {
return n, err
}
@@ -460,6 +473,18 @@ func (ch *channel) handlePacket(packet []byte) error {
}
ch.incomingRequests <- &req
case *channelRequestSuccessMsg, *channelRequestFailureMsg:
// Drop responses that arrive when no SendRequest is waiting, to
// prevent a malicious peer from filling ch.msg and stalling the
// mux read loop. The non-blocking send additionally protects the
// loop if a well-behaved caller is slow to read.
if !ch.sentRequestPending.Load() {
return nil
}
select {
case ch.msg <- msg:
default:
}
default:
ch.msg <- msg
}
@@ -530,7 +555,17 @@ func (ch *channel) Reject(reason RejectionReason, message string) error {
Language: "en",
}
ch.decided = true
return ch.sendMessage(reject)
err := ch.sendMessage(reject)
// Remove the channel from the mux to prevent memory leaks.
// Do not call ch.close() here: no goroutine holds a reference to a
// rejected channel's internal channels (msg, incomingRequests), so
// removing it from chanList is sufficient for GC. Calling close()
// would race with the mux loop goroutine (handlePacket or dropAll),
// causing a panic from closing an already-closed channel.
ch.mux.chanList.remove(ch.localId)
return err
}
func (ch *channel) Read(data []byte) (int, error) {
@@ -586,6 +621,27 @@ func (ch *channel) SendRequest(name string, wantReply bool, payload []byte) (boo
if wantReply {
ch.sentRequestMu.Lock()
defer ch.sentRequestMu.Unlock()
// Open the gate so that responses arriving while this request is in
// flight are allowed to reach ch.msg. Responses arriving while no
// request is pending are dropped by handlePacket.
ch.sentRequestPending.Store(true)
defer ch.sentRequestPending.Store(false)
// Drain any spurious responses that may have been buffered. This
// prevents a previously buffered unexpected response from being
// consumed instead of the actual response for this request.
drain:
for {
select {
case _, ok := <-ch.msg:
if !ok {
break drain
}
default:
break drain
}
}
}
msg := channelRequestMsg{
+140
View File
@@ -0,0 +1,140 @@
// Copyright 2025 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ssh
import (
"math/bits"
"testing"
"time"
"unsafe"
)
func TestMinPayloadSize(t *testing.T) {
// 4 GiB (2^32). Declared as a var (not a const) so that int(bigPayload)
// is a runtime conversion: a constant conversion would fail to compile
// on 32-bit platforms with "constant 4294967296 overflows int". On
// 32-bit the value truncates to 0 at runtime, but the is64Bit cases
// that reference it are skipped by the runtime check below.
var bigPayload int64 = 1 << 32
tests := []struct {
name string
maxPayload uint32
dataLen int
want uint32
is64Bit bool // Flag to run only on 64-bit architectures
}{
{
name: "Normal Case - Data fits in payload",
maxPayload: 32768,
dataLen: 1000,
want: 1000,
},
{
name: "Normal Case - Data larger than payload",
maxPayload: 32768,
dataLen: 50000,
want: 32768,
},
{
name: "Boundary Case - Data zero",
maxPayload: 32768,
dataLen: 0,
want: 0,
},
{
name: "Overflow Case - Data is exactly 4GB (1<<32)",
maxPayload: 32768,
dataLen: int(bigPayload),
want: 32768,
is64Bit: true,
},
{
name: "Overflow Case - Data is 4GB + small amount",
maxPayload: 32768,
dataLen: int(bigPayload + 100),
want: 32768,
is64Bit: true,
},
}
is64Bit := bits.UintSize == 64
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.is64Bit && !is64Bit {
t.Skip("Skipping test requiring 64-bit int")
}
got := minPayloadSize(tt.maxPayload, tt.dataLen)
if got != tt.want {
t.Errorf("minPayloadSize(%d, %d) = %d; want %d", tt.maxPayload, tt.dataLen, got, tt.want)
}
})
}
}
// TestWriteExtendedNoInfiniteLoopOnLargeWrite is an end-to-end regression
// test for the integer-overflow bug in WriteExtended. Before the fix, a
// write whose len(data) was a multiple of 2^32 caused minPayloadSize to
// return 0; WriteExtended then spun forever, reserving 0 bytes per
// iteration and never advancing the data slice.
//
// We exercise the real WriteExtended path with a slice whose declared
// length is exactly 2^32. Allocating 4 GiB is unnecessary: each iteration
// only reads up to maxRemotePayload bytes from the head of the slice, and
// the loop blocks in remoteWin.reserve() once the channel window is
// exhausted — before the slice base advances past the underlying buffer.
//
// With the fix, the loop blocks in reserve(); we detect that via
// waitWriterBlocked(), then close the window to let WriteExtended return.
// With the bug, the loop never blocks and the test times out.
//
//go:nocheckptr
func TestWriteExtendedNoInfiniteLoopOnLargeWrite(t *testing.T) {
if bits.UintSize < 64 {
t.Skip("test requires 64-bit int to construct a slice with len >= 2^32")
}
reader, writer, mux := channelPair(t)
defer reader.Close()
defer writer.Close()
defer mux.Close()
// Sized to hold the full pre-update remote window so that no iteration
// reads past the backing buffer before reserve() blocks.
backing := make([]byte, channelWindowSize)
var bigLen int64 = 1 << 32
bigSlice := unsafe.Slice(&backing[0], int(bigLen))
done := make(chan int, 1)
go func() {
n, _ := writer.Write(bigSlice)
done <- n
}()
blocked := make(chan struct{})
go func() {
writer.remoteWin.waitWriterBlocked()
close(blocked)
}()
select {
case <-blocked:
// Good — the loop made progress and is now blocked in reserve().
// Close the window to let WriteExtended return.
writer.remoteWin.close()
case <-time.After(2 * time.Second):
t.Fatal("WriteExtended did not block in reserve within 2s — minPayloadSize likely returned 0 (integer overflow regression)")
}
select {
case n := <-done:
if n == 0 {
t.Fatalf("WriteExtended returned n=0; expected progress")
}
case <-time.After(2 * time.Second):
t.Fatal("WriteExtended did not return after closing the window")
}
}
+2 -2
View File
@@ -407,7 +407,7 @@ func (c *gcmCipher) readCipherPacket(seqNum uint32, r io.Reader) ([]byte, error)
return nil, fmt.Errorf("ssh: illegal padding %d", padding)
}
if int(padding+1) >= len(plain) {
if int(padding)+1 >= len(plain) {
return nil, fmt.Errorf("ssh: padding %d too large", padding)
}
plain = plain[1 : length-uint32(padding)]
@@ -586,7 +586,7 @@ func (c *cbcCipher) writeCipherPacket(seqNum uint32, w io.Writer, rand io.Reader
// Length of encrypted portion of the packet (header, payload, padding).
// Enforce minimum padding and packet size.
encLength := maxUInt32(prefixLen+len(packet)+cbcMinPaddingSize, cbcMinPaddingSize)
encLength := maxUInt32(prefixLen+len(packet)+cbcMinPaddingSize, cbcMinPacketSize)
// Enforce block size.
encLength = (encLength + effectiveBlockSize - 1) / effectiveBlockSize * effectiveBlockSize
+85
View File
@@ -88,6 +88,32 @@ func NewClientConn(c net.Conn, addr string, config *ClientConfig) (Conn, <-chan
return conn, conn.mux.incomingChannels, conn.mux.incomingRequests, nil
}
// NewControlClientConn establishes an SSH connection over an OpenSSH
// ControlMaster socket c in proxy mode.
//
// Note that this package only implements the client side of the multiplexing
// protocol. The provided net.Conn must be a local, secure connection (such as a
// Unix domain socket) connected to an already-running OpenSSH process acting as
// the ControlMaster.
//
// WARNING: Because proxy mode bypasses the standard cryptographic handshake
// passing a standard network connection (e.g., TCP) will result in plaintext
// data leakage.
//
// The Request and NewChannel channels must be serviced or the connection
// will hang.
func NewControlClientConn(c net.Conn) (Conn, <-chan NewChannel, <-chan *Request, error) {
conn := &connection{
sshConn: sshConn{conn: c},
}
var err error
if conn.transport, err = handshakeControlProxy(c); err != nil {
return nil, nil, nil, fmt.Errorf("ssh: control proxy handshake failed: %w", err)
}
conn.mux = newMux(conn.transport)
return conn, conn.mux.incomingChannels, conn.mux.incomingRequests, nil
}
// clientHandshake performs the client side key exchange. See RFC 4253 Section
// 7.
func (c *connection) clientHandshake(dialAddress string, config *ClientConfig) error {
@@ -197,6 +223,59 @@ type HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error
// the server. A BannerCallback receives the message sent by the remote server.
type BannerCallback func(message string) error
// ClientAuthContext contains information about the current state of the
// authentication process, passed to [ClientAuthCallback].
type ClientAuthContext struct {
// Metadata contains the connection metadata.
Metadata ConnMetadata
// Algorithms contains the negotiated algorithms.
Algorithms NegotiatedAlgorithms
// AllowedMethods lists the authentication methods currently accepted
// by the server. These are the protocol-level names defined in RFC 4252
// such as "publickey", "password".
AllowedMethods []string
// PartialSuccessMethods lists the authentication methods that have already
// succeeded, indicating a multi-step authentication flow. This list
// represents the exact sequence of partial successes and may contain
// duplicates if the same method succeeded multiple times.
PartialSuccessMethods []string
// TriedMethods lists the methods that have already been attempted and
// failed during this session. This list represents the exact sequence of
// failures and may contain duplicates. This allows the callback to also
// track the number of failed attempts for a specific method.
TriedMethods []string
}
// ClientAuthCallback is a hook invoked before each authentication attempt. It
// allows the client to dynamically select an authentication method based on the
// current context, server capabilities, or previous failures.
//
// The callback is invoked after the initial "none" authentication method, once
// the server's supported authentication methods are known.
//
// Return values:
// - (AuthMethod, nil): The client will attempt this specific method next.
// The returned method does NOT need to be present in [ClientConfig.Auth].
// This allows for dynamic authentication strategies (e.g., prompting
// for a password only if public key auth fails). Callers should inspect
// [ClientAuthContext.TriedMethods] to avoid repeatedly returning the
// same failing method.
// - (nil, nil): The client selects from [ClientConfig.Auth] the first
// instance of a method that has not been tried yet, or aborts if none
// are left. If authentication is not successful, the callback is invoked
// again before the following attempt.
// - (nil, error): The authentication process is aborted immediately,
// causing the ongoing SSH handshake to fail with the provided error.
//
// To bound resource use, the client caps the total number of authentication
// attempts (failures and partial successes combined) at 64. If the cap is
// exceeded the handshake aborts with an error.
type ClientAuthCallback func(ctx *ClientAuthContext) (AuthMethod, error)
// A ClientConfig structure is used to configure a Client. It must not be
// modified after having been passed to an SSH function.
type ClientConfig struct {
@@ -210,6 +289,9 @@ type ClientConfig struct {
// Auth contains possible authentication methods to use with the
// server. Only the first instance of a particular RFC 4252 method will
// be used during authentication.
//
// If AuthCallback is set, these AuthMethod are only used if the
// callback returns nil.
Auth []AuthMethod
// HostKeyCallback is called during the cryptographic
@@ -240,6 +322,9 @@ type ClientConfig struct {
//
// A Timeout of zero means no timeout.
Timeout time.Duration
// AuthCallback, if non-nil, is invoked before each authentication attempt.
AuthCallback ClientAuthCallback
}
// InsecureIgnoreHostKey returns a function that can be used for
+57 -17
View File
@@ -21,6 +21,12 @@ const (
authSuccess
)
// maxAuthClientTried bounds the total number of authentication attempts
// (failures and partial successes combined) the client makes before
// aborting the loop, to prevent unbounded growth when an AuthCallback
// keeps supplying methods.
const maxAuthClientTried = 64
// clientAuthenticate authenticates with the remote server. See RFC 4252.
func (c *connection) clientAuthenticate(config *ClientConfig) error {
// initiate user auth session
@@ -67,32 +73,62 @@ func (c *connection) clientAuthenticate(config *ClientConfig) error {
// then any untried methods suggested by the server.
var tried []string
var lastMethods []string
var partialSuccess []string
sessionID := c.transport.getSessionID()
for auth := AuthMethod(new(noneAuth)); auth != nil; {
ok, methods, err := auth.auth(sessionID, config.User, c.transport, config.Rand, extensions)
if err != nil {
// On disconnect, return error immediately
if _, ok := err.(*disconnectMsg); ok {
if _, isDisconnect := err.(*disconnectMsg); isDisconnect {
return err
}
// We return the error later if there is no other method left to
// try.
// We return the error later if there is no other method
// left to try.
ok = authFailure
}
if ok == authSuccess {
// success
switch ok {
case authSuccess:
return nil
} else if ok == authFailure {
if m := auth.method(); !slices.Contains(tried, m) {
tried = append(tried, m)
}
case authPartialSuccess:
partialSuccess = append(partialSuccess, auth.method())
case authFailure:
tried = append(tried, auth.method())
}
if len(partialSuccess)+len(tried) > maxAuthClientTried {
return fmt.Errorf("ssh: too many authentication attempts (%d), aborting",
len(partialSuccess)+len(tried))
}
if methods == nil {
methods = lastMethods
}
lastMethods = methods
// If AuthCallback is set it takes precedence: it picks the next
// AuthMethod dynamically. The returned method need not be in
// config.Auth. If the callback returns (nil, nil) we fall back to
// selecting the next untried method from config.Auth below; on
// (nil, error) the handshake aborts.
if config.AuthCallback != nil {
ctx := &ClientAuthContext{
Metadata: c,
Algorithms: c.Algorithms(),
AllowedMethods: slices.Clone(methods),
PartialSuccessMethods: slices.Clone(partialSuccess),
TriedMethods: slices.Clone(tried),
}
altAuth, cbErr := config.AuthCallback(ctx)
if cbErr != nil {
return cbErr
}
if altAuth != nil {
auth = altAuth
continue
}
}
auth = nil
findNext:
@@ -274,10 +310,14 @@ func pickSignatureAlgorithm(signer Signer, extensions map[string][]byte) (MultiA
}
// Filter algorithms based on those supported by MultiAlgorithmSigner.
// Iterate over the signer's algorithms first to preserve its preference order.
supportedKeyAlgos := algorithmsForKeyFormat(keyFormat)
var keyAlgos []string
for _, algo := range algorithmsForKeyFormat(keyFormat) {
if slices.Contains(as.Algorithms(), underlyingAlgo(algo)) {
keyAlgos = append(keyAlgos, algo)
for _, signerAlgo := range as.Algorithms() {
if idx := slices.IndexFunc(supportedKeyAlgos, func(algo string) bool {
return underlyingAlgo(algo) == signerAlgo
}); idx >= 0 {
keyAlgos = append(keyAlgos, supportedKeyAlgos[idx])
}
}
@@ -373,11 +413,11 @@ func (cb publicKeyCallback) auth(session []byte, user string, c packetConn, rand
return authFailure, nil, err
}
// If authentication succeeds or the list of available methods does not
// contain the "publickey" method, do not attempt to authenticate with any
// other keys. According to RFC 4252 Section 7, the latter can occur when
// additional authentication methods are required.
if success == authSuccess || !slices.Contains(methods, cb.method()) {
// If authentication succeeds or partially succeeds, return immediately
// so the caller can select the next auth method. According to RFC 4252
// Section 7, if the server no longer lists "publickey" among its
// allowed methods, do not attempt to authenticate with any other keys.
if success == authSuccess || success == authPartialSuccess || !slices.Contains(methods, cb.method()) {
return success, methods, err
}
}
+797
View File
@@ -169,6 +169,689 @@ func TestClientAuthThirdKey(t *testing.T) {
}
}
// partialSuccessPublicKeyAndKbdInteractiveServer returns a server config
// where the rsa key gets partial success and the server offers both publickey
// and keyboard-interactive as next methods. The VerifiedPublicKeyCallback
// tracks state so that the same key only triggers partial success once,
// avoiding an impossible auth loop.
func partialSuccessPublicKeyAndKbdInteractiveServer() *ServerConfig {
rsaDone := false
serverConf := &ServerConfig{
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
return nil, nil
}
return nil, errors.New("invalid credentials")
},
VerifiedPublicKeyCallback: func(conn ConnMetadata, key PublicKey, permissions *Permissions, signatureAlgorithm string) (*Permissions, error) {
if !rsaDone && bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
rsaDone = true
return nil, &PartialSuccessError{
Next: ServerAuthCallbacks{
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
return nil, nil
}
return nil, errors.New("invalid credentials")
},
KeyboardInteractiveCallback: func(conn ConnMetadata, client KeyboardInteractiveChallenge) (*Permissions, error) {
answers, err := client("", "", []string{"token: "}, []bool{true})
if err != nil {
return nil, err
}
if len(answers) == 1 && answers[0] == "correct-token" {
return nil, nil
}
return nil, errors.New("invalid token")
},
},
}
}
return nil, errors.New("invalid credentials")
},
}
serverConf.AddHostKey(testSigners["rsa"])
return serverConf
}
// partialSuccessMultiKeyServer returns a server config that requires two
// public keys in sequence: the first key (rsa) triggers partial success
// requiring a second key (ecdsa) to complete authentication.
func partialSuccessMultiKeyServer() *ServerConfig {
firstKeyDone := false
serverConf := &ServerConfig{
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
return nil, nil
}
if bytes.Equal(key.Marshal(), testPublicKeys["ecdsa"].Marshal()) {
return nil, nil
}
return nil, errors.New("invalid credentials")
},
VerifiedPublicKeyCallback: func(conn ConnMetadata, key PublicKey, permissions *Permissions, signatureAlgorithm string) (*Permissions, error) {
if !firstKeyDone && bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
firstKeyDone = true
return nil, &PartialSuccessError{
Next: ServerAuthCallbacks{
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
if bytes.Equal(key.Marshal(), testPublicKeys["ecdsa"].Marshal()) {
return nil, nil
}
return nil, errors.New("invalid credentials")
},
},
}
}
if firstKeyDone && bytes.Equal(key.Marshal(), testPublicKeys["ecdsa"].Marshal()) {
return nil, nil
}
return nil, errors.New("invalid credentials")
},
}
serverConf.AddHostKey(testSigners["rsa"])
return serverConf
}
func TestStaticMultiKeyPartialSuccess(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
clientConf := &ClientConfig{
User: "user",
Auth: []AuthMethod{
PublicKeys(testSigners["rsa"], testSigners["ecdsa"]),
},
HostKeyCallback: InsecureIgnoreHostKey(),
}
go NewServerConn(c1, partialSuccessMultiKeyServer())
_, _, _, err = NewClientConn(c2, "", clientConf)
if err != nil {
t.Fatalf("client login error: %s", err)
}
}
func TestStaticPartialSuccess(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
clientConf := &ClientConfig{
User: "user",
Auth: []AuthMethod{
PublicKeys(testSigners["rsa"]),
KeyboardInteractive(func(name, instruction string, questions []string, echos []bool) ([]string, error) {
return []string{"correct-token"}, nil
}),
},
HostKeyCallback: InsecureIgnoreHostKey(),
}
go NewServerConn(c1, partialSuccessPublicKeyAndKbdInteractiveServer())
_, _, _, err = NewClientConn(c2, "", clientConf)
if err != nil {
t.Fatalf("client login error: %s", err)
}
}
// partialSuccessKeyAThenKeyBServer returns a server config where keyA (rsa)
// gets partial success and the server offers BOTH publickey and
// keyboard-interactive. keyB (ecdsa) then completes auth successfully.
func partialSuccessKeyAThenKeyBServer() *ServerConfig {
keyADone := false
serverConf := &ServerConfig{
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
return nil, nil
}
if bytes.Equal(key.Marshal(), testPublicKeys["ecdsa"].Marshal()) {
return nil, nil
}
return nil, errors.New("invalid credentials")
},
VerifiedPublicKeyCallback: func(conn ConnMetadata, key PublicKey, permissions *Permissions, signatureAlgorithm string) (*Permissions, error) {
if !keyADone && bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
keyADone = true
return nil, &PartialSuccessError{
Next: ServerAuthCallbacks{
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
if bytes.Equal(key.Marshal(), testPublicKeys["ecdsa"].Marshal()) {
return nil, nil
}
return nil, errors.New("invalid credentials")
},
KeyboardInteractiveCallback: func(conn ConnMetadata, client KeyboardInteractiveChallenge) (*Permissions, error) {
answers, err := client("", "", []string{"token: "}, []bool{true})
if err != nil {
return nil, err
}
if len(answers) == 1 && answers[0] == "correct-token" {
return nil, nil
}
return nil, errors.New("invalid token")
},
},
}
}
if keyADone && bytes.Equal(key.Marshal(), testPublicKeys["ecdsa"].Marshal()) {
return nil, nil
}
return nil, errors.New("invalid credentials")
},
}
serverConf.AddHostKey(testSigners["rsa"])
return serverConf
}
func TestStaticPartialSuccessKeyAThenKeyB(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
clientConf := &ClientConfig{
User: "user",
Auth: []AuthMethod{
PublicKeys(testSigners["rsa"], testSigners["ecdsa"]),
},
HostKeyCallback: InsecureIgnoreHostKey(),
}
go NewServerConn(c1, partialSuccessKeyAThenKeyBServer())
_, _, _, err = NewClientConn(c2, "", clientConf)
if err != nil {
t.Fatalf("client login error: %s", err)
}
}
// partialSuccessMultiKeyThenKbdInteractiveServer returns a server config
// that strictly requires keyA (rsa) AND keyB (ecdsa) as public keys before
// allowing keyboard-interactive. After keyA, ONLY publickey is offered
// (for keyB). After keyB, ONLY keyboard-interactive is offered.
func partialSuccessMultiKeyThenKbdInteractiveServer() *ServerConfig {
serverConf := &ServerConfig{
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
return nil, &PartialSuccessError{
Next: ServerAuthCallbacks{
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
if bytes.Equal(key.Marshal(), testPublicKeys["ecdsa"].Marshal()) {
return nil, &PartialSuccessError{
Next: ServerAuthCallbacks{
KeyboardInteractiveCallback: func(conn ConnMetadata, client KeyboardInteractiveChallenge) (*Permissions, error) {
answers, err := client("", "", []string{"token: "}, []bool{true})
if err != nil {
return nil, err
}
if len(answers) == 1 && answers[0] == "correct-token" {
return nil, nil
}
return nil, errors.New("invalid token")
},
},
}
}
return nil, errors.New("invalid credentials")
},
},
}
}
return nil, errors.New("invalid credentials")
},
}
serverConf.AddHostKey(testSigners["rsa"])
return serverConf
}
func TestStaticMultiKeyPartialThenKbdInteractive(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
clientConf := &ClientConfig{
User: "user",
Auth: []AuthMethod{
PublicKeys(testSigners["rsa"], testSigners["ecdsa"]),
KeyboardInteractive(func(name, instruction string, questions []string, echos []bool) ([]string, error) {
return []string{"correct-token"}, nil
}),
},
HostKeyCallback: InsecureIgnoreHostKey(),
}
go NewServerConn(c1, partialSuccessMultiKeyThenKbdInteractiveServer())
_, _, _, err = NewClientConn(c2, "", clientConf)
if err != nil {
t.Fatalf("client login error: %s", err)
}
}
func TestAuthMethodDynamic(t *testing.T) {
config := &ClientConfig{
User: "testuser",
Auth: nil,
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
if len(ctx.Metadata.SessionID()) == 0 {
t.Error("empty sessionID")
}
if ctx.Algorithms.HostKey == "" {
t.Error("empty Host Key")
}
if slices.Contains(ctx.AllowedMethods, "password") {
return Password(clientPassword), nil
}
return nil, errors.New("auth callback error")
},
}
if err := tryAuth(t, config); err != nil {
t.Fatalf("unable to dial remote side: %s", err)
}
}
func TestAuthCallbackError(t *testing.T) {
config := &ClientConfig{
User: "testuser",
Auth: []AuthMethod{
Password(clientPassword),
},
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
return nil, errors.New("auth callback error")
},
}
if err := tryAuth(t, config); err == nil {
t.Fatal("authentication unexpectedly succeeded after AuthCallback returned an error")
}
}
func TestAuthCallbackPartialSuccess(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
clientConf := &ClientConfig{
User: "user",
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
if slices.Contains(ctx.AllowedMethods, "publickey") && !slices.Contains(ctx.PartialSuccessMethods, "publickey") {
return PublicKeys(testSigners["rsa"]), nil
}
if slices.Contains(ctx.PartialSuccessMethods, "publickey") && slices.Contains(ctx.AllowedMethods, "keyboard-interactive") {
return KeyboardInteractive(func(name, instruction string, questions []string, echos []bool) ([]string, error) {
return []string{"correct-token"}, nil
}), nil
}
return nil, fmt.Errorf("unexpected auth state: allowed=%v partial=%v", ctx.AllowedMethods, ctx.PartialSuccessMethods)
},
}
go NewServerConn(c1, partialSuccessPublicKeyAndKbdInteractiveServer())
_, _, _, err = NewClientConn(c2, "", clientConf)
if err != nil {
t.Fatalf("client login error: %s", err)
}
}
func TestAuthCallbackMultiKeyPartialSuccess(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
clientConf := &ClientConfig{
User: "user",
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
if slices.Contains(ctx.AllowedMethods, "publickey") && !slices.Contains(ctx.PartialSuccessMethods, "publickey") {
return PublicKeys(testSigners["rsa"]), nil
}
if slices.Contains(ctx.PartialSuccessMethods, "publickey") && slices.Contains(ctx.AllowedMethods, "publickey") {
return PublicKeys(testSigners["ecdsa"]), nil
}
return nil, fmt.Errorf("unexpected auth state: allowed=%v partial=%v", ctx.AllowedMethods, ctx.PartialSuccessMethods)
},
}
go NewServerConn(c1, partialSuccessMultiKeyServer())
_, _, _, err = NewClientConn(c2, "", clientConf)
if err != nil {
t.Fatalf("client login error: %s", err)
}
}
func TestAuthCallbackMultiKeyPartialThenKbdInteractive(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
clientConf := &ClientConfig{
User: "user",
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
partialCount := len(ctx.PartialSuccessMethods)
if partialCount == 0 && slices.Contains(ctx.AllowedMethods, "publickey") {
return PublicKeys(testSigners["rsa"]), nil
}
if partialCount == 1 && slices.Contains(ctx.AllowedMethods, "publickey") {
return PublicKeys(testSigners["ecdsa"]), nil
}
if partialCount >= 2 && slices.Contains(ctx.AllowedMethods, "keyboard-interactive") {
return KeyboardInteractive(func(name, instruction string, questions []string, echos []bool) ([]string, error) {
return []string{"correct-token"}, nil
}), nil
}
return nil, fmt.Errorf("unexpected auth state: allowed=%v partial=%v tried=%v",
ctx.AllowedMethods, ctx.PartialSuccessMethods, ctx.TriedMethods)
},
}
go NewServerConn(c1, partialSuccessMultiKeyThenKbdInteractiveServer())
_, _, _, err = NewClientConn(c2, "", clientConf)
if err != nil {
t.Fatalf("client login error: %s", err)
}
}
func TestAuthCallbackPartialSuccessKeyAThenKeyB(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
clientConf := &ClientConfig{
User: "user",
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
if len(ctx.PartialSuccessMethods) == 0 && slices.Contains(ctx.AllowedMethods, "publickey") {
return PublicKeys(testSigners["rsa"]), nil
}
if len(ctx.PartialSuccessMethods) == 1 && slices.Contains(ctx.AllowedMethods, "publickey") {
return PublicKeys(testSigners["ecdsa"]), nil
}
return nil, fmt.Errorf("unexpected auth state: allowed=%v partial=%v",
ctx.AllowedMethods, ctx.PartialSuccessMethods)
},
}
go NewServerConn(c1, partialSuccessKeyAThenKeyBServer())
_, _, _, err = NewClientConn(c2, "", clientConf)
if err != nil {
t.Fatalf("client login error: %s", err)
}
}
func TestAuthCallbackPartialSuccessWithStaticAuth(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
clientConf := &ClientConfig{
User: "user",
Auth: []AuthMethod{
PublicKeys(testSigners["rsa"]),
},
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
if slices.Contains(ctx.PartialSuccessMethods, "publickey") && slices.Contains(ctx.AllowedMethods, "keyboard-interactive") {
return KeyboardInteractive(func(name, instruction string, questions []string, echos []bool) ([]string, error) {
return []string{"correct-token"}, nil
}), nil
}
return nil, nil
},
}
go NewServerConn(c1, partialSuccessPublicKeyAndKbdInteractiveServer())
_, _, _, err = NewClientConn(c2, "", clientConf)
if err != nil {
t.Fatalf("client login error: %s", err)
}
}
func partialSuccessPubKeyForbiddenAfterPartialServer(maxTries int) *ServerConfig {
serverConf := &ServerConfig{
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
return nil, nil
}
return nil, errors.New("invalid credentials")
},
VerifiedPublicKeyCallback: func(conn ConnMetadata, key PublicKey, permissions *Permissions, signatureAlgorithm string) (*Permissions, error) {
if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
return nil, &PartialSuccessError{
Next: ServerAuthCallbacks{
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
return nil, errors.New("legacy public key authentication is forbidden")
},
KeyboardInteractiveCallback: func(conn ConnMetadata, client KeyboardInteractiveChallenge) (*Permissions, error) {
answers, err := client("", "", []string{"token: "}, []bool{true})
if err != nil {
return nil, err
}
if len(answers) == 1 && answers[0] == "correct-token" {
return nil, nil
}
return nil, errors.New("invalid token")
},
},
}
}
return nil, errors.New("invalid credentials")
},
MaxAuthTries: maxTries,
}
serverConf.AddHostKey(testSigners["rsa"])
return serverConf
}
func TestAuthCallbackPartialSuccessWithStaticMultiKey(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
clientConf := &ClientConfig{
User: "user",
Auth: []AuthMethod{
PublicKeys(
testSigners["rsa"],
testSigners["ecdsa"],
testSigners["ed25519"],
),
},
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
if slices.Contains(ctx.PartialSuccessMethods, "publickey") && slices.Contains(ctx.AllowedMethods, "keyboard-interactive") {
return KeyboardInteractive(func(name, instruction string, questions []string, echos []bool) ([]string, error) {
return []string{"correct-token"}, nil
}), nil
}
return nil, nil
},
}
go NewServerConn(c1, partialSuccessPubKeyForbiddenAfterPartialServer(2))
_, _, _, err = NewClientConn(c2, "", clientConf)
if err != nil {
t.Fatalf("client login error: %s", err)
}
}
func TestAuthCallbackPartialSuccessShortCircuit(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
serverConf := partialSuccessPubKeyForbiddenAfterPartialServer(2)
pubkeyAttempts := 0
clientConf := &ClientConfig{
User: "user",
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
if slices.Contains(ctx.AllowedMethods, "publickey") && !slices.Contains(ctx.PartialSuccessMethods, "publickey") {
pubkeyAttempts++
return PublicKeys(testSigners["rsa"], testSigners["ecdsa"], testSigners["ed25519"]), nil
}
if slices.Contains(ctx.PartialSuccessMethods, "publickey") && slices.Contains(ctx.AllowedMethods, "keyboard-interactive") {
return KeyboardInteractive(func(name, instruction string, questions []string, echos []bool) ([]string, error) {
return []string{"correct-token"}, nil
}), nil
}
return nil, fmt.Errorf("unexpected auth state: allowed=%v partial=%v tried=%v",
ctx.AllowedMethods, ctx.PartialSuccessMethods, ctx.TriedMethods)
},
}
go NewServerConn(c1, serverConf)
_, _, _, err = NewClientConn(c2, "", clientConf)
if err != nil {
t.Fatalf("client login error: %s", err)
}
if pubkeyAttempts != 1 {
t.Errorf("expected publickey to be attempted once before short-circuit, got %d", pubkeyAttempts)
}
}
func TestAuthCallbackTriedLoopBound(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
serverConf := &ServerConfig{
MaxAuthTries: -1,
PasswordCallback: func(conn ConnMetadata, pass []byte) (*Permissions, error) {
return nil, errors.New("password rejected")
},
}
serverConf.AddHostKey(testSigners["rsa"])
invocations := 0
clientConf := &ClientConfig{
User: "user",
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
invocations++
return Password("wrong"), nil
},
}
go NewServerConn(c1, serverConf)
_, _, _, err = NewClientConn(c2, "", clientConf)
if err == nil {
t.Fatal("expected the client to abort after exceeding the attempts cap")
}
if !strings.Contains(err.Error(), "too many authentication attempts") {
t.Errorf("unexpected error: %v", err)
}
if invocations != maxAuthClientTried {
t.Errorf("AuthCallback invoked %d times; expected %d",
invocations, maxAuthClientTried)
}
}
func alwaysPartialPubKeyServer() *ServerConfig {
var alwaysPartial func(ConnMetadata, PublicKey) (*Permissions, error)
alwaysPartial = func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
if !bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
return nil, errors.New("invalid credentials")
}
return nil, &PartialSuccessError{
Next: ServerAuthCallbacks{
PublicKeyCallback: alwaysPartial,
},
}
}
serverConf := &ServerConfig{
MaxAuthTries: -1,
PublicKeyCallback: alwaysPartial,
}
serverConf.AddHostKey(testSigners["rsa"])
return serverConf
}
func TestAuthCallbackPartialSuccessLoopBound(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
invocations := 0
clientConf := &ClientConfig{
User: "user",
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
invocations++
return PublicKeys(testSigners["rsa"]), nil
},
}
go NewServerConn(c1, alwaysPartialPubKeyServer())
_, _, _, err = NewClientConn(c2, "", clientConf)
if err == nil {
t.Fatal("expected the client to abort after exceeding the attempts cap")
}
if !strings.Contains(err.Error(), "too many authentication attempts") {
t.Errorf("unexpected error: %v", err)
}
if invocations != maxAuthClientTried {
t.Errorf("AuthCallback invoked %d times; expected %d",
invocations, maxAuthClientTried)
}
}
func TestAuthMethodPassword(t *testing.T) {
config := &ClientConfig{
User: "testuser",
@@ -971,6 +1654,74 @@ func TestAuthMethodGSSAPIWithMIC(t *testing.T) {
}
}
type maliciousGSSAPIWithMICAuthMethod struct{}
func (maliciousGSSAPIWithMICAuthMethod) method() string {
// Reuse an advertised auth method name so the client attempts this
// AuthMethod even when gssapi-with-mic is not advertised.
return "password"
}
func (maliciousGSSAPIWithMICAuthMethod) auth(session []byte, user string, c packetConn, rand io.Reader, _ map[string][]byte) (authResult, []string, error) {
req := &userAuthRequestMsg{
User: user,
Service: serviceSSH,
Method: "gssapi-with-mic",
}
req.Payload = appendU32(req.Payload, 1)
req.Payload = appendString(req.Payload, string(krb5OID))
if err := c.writePacket(Marshal(req)); err != nil {
return authFailure, nil, err
}
packet, err := c.readPacket()
if err != nil {
return authFailure, nil, err
}
switch packet[0] {
case msgUserAuthFailure:
var msg userAuthFailureMsg
if err := Unmarshal(packet, &msg); err != nil {
return authFailure, nil, err
}
if msg.PartialSuccess {
return authPartialSuccess, msg.Methods, nil
}
return authFailure, msg.Methods, nil
default:
return authFailure, nil, unexpectedMessageError(msgUserAuthFailure, packet[0])
}
}
func TestGSSAPIWithMICPartialConfigRejectedAtRuntime(t *testing.T) {
config := &ClientConfig{
User: "testuser",
Auth: []AuthMethod{
maliciousGSSAPIWithMICAuthMethod{},
},
HostKeyCallback: InsecureIgnoreHostKey(),
}
clientErr, serverErrs := tryAuthBothSides(t, config, &GSSAPIWithMICConfig{
Server: &FakeServer{},
})
if clientErr == nil || !strings.Contains(clientErr.Error(), "ssh: unable to authenticate") {
t.Fatalf("client got %v, want authentication failure", clientErr)
}
found := false
for _, err := range serverErrs {
if err != nil && strings.Contains(err.Error(), "ssh: gssapi-with-mic auth not configured") {
found = true
break
}
}
if !found {
t.Fatalf("server auth errors = %v, want gssapi-with-mic auth not configured", serverErrs)
}
}
func TestCompatibleAlgoAndSignatures(t *testing.T) {
type testcase struct {
algo string
@@ -1159,6 +1910,52 @@ func TestPickSignatureAlgorithm(t *testing.T) {
}
}
func TestPickSignatureAlgorithmRespectsSignerPreference(t *testing.T) {
algoSigner, ok := testSigners["rsa"].(AlgorithmSigner)
if !ok {
t.Fatalf("rsa test signer does not implement the AlgorithmSigner interface")
}
serverExtensions := map[string][]byte{
"server-sig-algs": []byte(KeyAlgoRSASHA256 + "," + KeyAlgoRSASHA512),
}
tests := []struct {
name string
signerPrefs []string
expectedAlgo string
}{
{
name: "Signer prefers SHA512 then SHA256",
signerPrefs: []string{KeyAlgoRSASHA512, KeyAlgoRSASHA256},
expectedAlgo: KeyAlgoRSASHA512,
},
{
name: "Signer prefers SHA256 then SHA512",
signerPrefs: []string{KeyAlgoRSASHA256, KeyAlgoRSASHA512},
expectedAlgo: KeyAlgoRSASHA256,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
orderedSigner, err := NewSignerWithAlgorithms(algoSigner, tc.signerPrefs)
if err != nil {
t.Fatalf("failed to create ordered signer: %v", err)
}
_, selectedAlgo, err := pickSignatureAlgorithm(orderedSigner, serverExtensions)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if selectedAlgo != tc.expectedAlgo {
t.Errorf("Algorithm mismatch; got %q want %q", selectedAlgo, tc.expectedAlgo)
}
})
}
}
// configurablePublicKeyCallback is a public key callback that allows to
// configure the signature algorithm and format. This way we can emulate the
// behavior of buggy clients.
+9 -1
View File
@@ -91,9 +91,17 @@ func DiscardRequests(in <-chan *Request) {
}
}
// A connTransport represents the transport for a connection.
type connTransport interface {
packetConn
getAlgorithms() NegotiatedAlgorithms
getSessionID() []byte
waitSession() error
}
// A connection represents an incoming connection.
type connection struct {
transport *handshakeTransport
transport connTransport
sshConn
// The connection protocol.
+155
View File
@@ -0,0 +1,155 @@
// Copyright 2026 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ssh
import (
"encoding/binary"
"errors"
"fmt"
"io"
"golang.org/x/crypto/cryptobyte"
)
const (
muxProtocolVersion = 4
muxMsgHello = 0x00000001
muxCProxy = 0x1000000f
muxSProxy = 0x8000000f
)
const controlProxyRequestID = 0
// handshakeControlProxy attempts to establish a transport connection with an
// OpenSSH ControlMaster socket in proxy mode. For details see:
// https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.mux
func handshakeControlProxy(rw io.ReadWriteCloser) (connTransport, error) {
if err := controlProxyWritePacket(rw, func(b *cryptobyte.Builder) {
b.AddUint32(muxMsgHello)
b.AddUint32(muxProtocolVersion)
}); err != nil {
return nil, fmt.Errorf("mux hello write failed: %w", err)
}
if err := controlProxyWritePacket(rw, func(b *cryptobyte.Builder) {
b.AddUint32(muxCProxy)
b.AddUint32(controlProxyRequestID)
}); err != nil {
return nil, fmt.Errorf("mux client proxy write failed: %w", err)
}
messageType, body, err := controlProxyReadMessage(rw)
if err != nil {
return nil, fmt.Errorf("mux hello read failed: %w", err)
}
if messageType != muxMsgHello {
return nil, fmt.Errorf("expected hello response, got %v", messageType)
}
var v uint32
if !body.ReadUint32(&v) {
return nil, errors.New("EOF reading mux protocol version")
}
if v != muxProtocolVersion {
return nil, fmt.Errorf("mux server has unsupported version %v", v)
}
messageType, body, err = controlProxyReadMessage(rw)
if err != nil {
return nil, fmt.Errorf("mux server proxy read failed: %w", err)
}
if messageType != muxSProxy {
return nil, fmt.Errorf("expected server proxy response, got %v", messageType)
}
var reqID uint32
if !body.ReadUint32(&reqID) {
return nil, errors.New("EOF reading request id")
}
if reqID != controlProxyRequestID {
return nil, fmt.Errorf("expected request id %v, got %v", controlProxyRequestID, reqID)
}
return &controlProxyTransport{rw}, nil
}
// controlProxyTransport implements the connTransport interface for
// ControlMaster connections. Each controlMessage has zero length padding and
// no MAC.
type controlProxyTransport struct {
rw io.ReadWriteCloser
}
func (p *controlProxyTransport) Close() error {
return p.rw.Close()
}
func (p *controlProxyTransport) writePacket(controlMessage []byte) error {
return controlProxyWritePacket(p.rw, func(b *cryptobyte.Builder) {
b.AddUint8(0) // Padding length.
b.AddBytes(controlMessage)
})
}
func (p *controlProxyTransport) readPacket() ([]byte, error) {
buf, err := controlProxyReadPacket(p.rw)
if err != nil {
return nil, fmt.Errorf("ssh: error reading control message: %w", err)
}
// Discard the padding length.
if len(buf) < 1 {
return nil, errors.New("ssh: EOF reading padding length")
}
if buf[0] != 0 {
return nil, errors.New("ssh: unexpected non-zero padding in control message")
}
return buf[1:], nil
}
func (p *controlProxyTransport) getAlgorithms() NegotiatedAlgorithms {
return NegotiatedAlgorithms{}
}
func (p *controlProxyTransport) getSessionID() []byte {
return nil
}
func (p *controlProxyTransport) waitSession() error {
return nil
}
func controlProxyWritePacket(w io.Writer, f cryptobyte.BuilderContinuation) error {
var buf []byte
b := cryptobyte.NewBuilder(buf)
b.AddUint32LengthPrefixed(f)
out, err := b.Bytes()
if err != nil {
return err
}
_, err = w.Write(out)
return err
}
func controlProxyReadPacket(r io.Reader) (cryptobyte.String, error) {
var l uint32
if err := binary.Read(r, binary.BigEndian, &l); err != nil {
return nil, err
}
if l > maxPacket {
return nil, fmt.Errorf("message length %v exceeds maximum %v", l, maxPacket)
}
buf := make([]byte, l)
if _, err := io.ReadFull(r, buf); err != nil {
return nil, err
}
return buf, nil
}
func controlProxyReadMessage(r io.Reader) (messageType uint32, body cryptobyte.String, err error) {
body, err = controlProxyReadPacket(r)
if err != nil {
return 0, nil, fmt.Errorf("error reading message body: %w", err)
}
if !body.ReadUint32(&messageType) {
return 0, nil, errors.New("EOF reading message type")
}
return messageType, body, nil
}
+275
View File
@@ -0,0 +1,275 @@
// Copyright 2026 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ssh
import (
"bytes"
"io"
"strings"
"testing"
)
func TestControlClientHandshake(t *testing.T) {
reqs := [][]byte{
// Hello request.
{0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04},
// Client proxy request.
{0x00, 0x00, 0x00, 0x08, 0x10, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00},
}
respsNormal := [][]byte{
// Hello response.
{0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04},
// Server proxy response.
{0x00, 0x00, 0x00, 0x08, 0x80, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00},
}
for _, tt := range []struct {
name string
resps [][]byte
expectedErr string
}{
{
name: "normal handshake",
resps: respsNormal,
},
{
name: "length greater than max",
resps: [][]byte{
{0xff, 0xff, 0xff, 0xff},
respsNormal[1],
},
expectedErr: "message length 4294967295 exceeds maximum",
},
{
name: "missing hello response",
resps: [][]byte{
{},
},
expectedErr: "use of closed network connection",
},
{
name: "hello response too short",
resps: [][]byte{
{0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00},
respsNormal[1],
},
expectedErr: "EOF",
},
{
name: "bad hello response type",
resps: [][]byte{
{0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04},
respsNormal[1],
},
expectedErr: "expected hello response, got 0",
},
{
name: "bad protocol version",
resps: [][]byte{
{0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00},
respsNormal[1],
},
expectedErr: "mux server has unsupported version 0",
},
{
name: "missing server proxy response",
resps: [][]byte{
respsNormal[0],
},
expectedErr: "use of closed network connection",
},
{
name: "server proxy response too short",
resps: [][]byte{
respsNormal[0],
{0x00, 0x00, 0x00, 0x06, 0x80, 0x00, 0x00, 0x0f, 0x00, 0x00},
},
expectedErr: "EOF",
},
{
name: "bad server proxy response type",
resps: [][]byte{
respsNormal[0],
{0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
},
expectedErr: "expected server proxy response, got 0",
},
{
name: "bad request id",
resps: [][]byte{
respsNormal[0],
{0x00, 0x00, 0x00, 0x08, 0x80, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x01},
},
expectedErr: "expected request id 0, got 1",
},
} {
t.Run(tt.name, func(t *testing.T) {
done := make(chan error, 1)
ok := func() bool {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
go func() {
defer close(done)
_, _, _, err := NewControlClientConn(c2)
c2.Write([]byte{0}) // Dummy message to unblock the final read.
done <- err
}()
i := 0
for ; i < len(reqs) && i < len(tt.resps); i++ {
expected := reqs[i]
buf := make([]byte, len(expected))
if _, err := io.ReadFull(c1, buf); err != nil {
t.Errorf("error reading message %d: %v", i+1, err)
return false
}
if !bytes.Equal(buf, expected) {
t.Errorf(
"unexpected message %d: got %v, want %v",
i+1, buf, expected,
)
return false
}
_, err = c1.Write(tt.resps[i])
if err != nil {
t.Errorf("error writing message %d: %v", i+1, err)
return false
}
}
// Wait for the next message so that the final response can be read.
buf := make([]byte, 1)
c1.Read(buf)
return true
}()
if !ok {
return
}
err := <-done
if tt.expectedErr != "" {
if err == nil || !strings.Contains(err.Error(), tt.expectedErr) {
t.Fatalf("got err %q; want err containing %q", err, tt.expectedErr)
}
return
}
if err != nil {
t.Fatalf("got err %q; want no err", err)
}
})
}
}
func TestControlClientTransport(t *testing.T) {
type response struct {
status bool
payload []byte
err error
}
for _, tt := range []struct {
name string
resp []byte
respStatus bool
respPayload []byte
expectedErr string
}{
{
name: "successful request",
resp: []byte{0x00, 0x00, 0x00, 0x02, 0x00, 0x51},
respStatus: true,
},
{
name: "failed request",
resp: []byte{0x00, 0x00, 0x00, 0x02, 0x00, 0x52},
respStatus: false,
},
{
name: "short response",
resp: []byte{0x00, 0x00, 0x00, 0x00},
expectedErr: "EOF",
},
{
name: "response with payload",
resp: []byte{0x00, 0x00, 0x00, 0x05, 0x00, 0x51, 0x01, 0x02, 0x03},
respStatus: true,
respPayload: []byte{1, 2, 3},
},
} {
t.Run(tt.name, func(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
// Handshake responses.
c1.Write([]byte{
0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04,
0x00, 0x00, 0x00, 0x08, 0x80, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00,
})
conn, chans, reqs, err := NewControlClientConn(c2)
if err != nil {
t.Fatal(err)
}
client := NewClient(conn, chans, reqs)
done := make(chan response, 1)
go func() {
defer close(done)
status, payload, err := client.SendRequest("hello", true, nil)
if err != nil {
done <- response{err: err}
return
}
done <- response{
status: status,
payload: payload,
}
}()
// Discard handshake.
io.CopyN(io.Discard, c1, 24)
expectedReq := []byte{
0x00, 0x00, 0x00, 0x0c, 0x00, 0x50,
0x00, 0x00, 0x00, 0x05, 'h', 'e', 'l', 'l', 'o',
0x01,
}
buf := make([]byte, len(expectedReq))
if _, err := io.ReadFull(c1, buf); err != nil {
t.Fatalf("reading request: %v", err)
}
if !bytes.Equal(buf, expectedReq) {
t.Fatalf("got request %v; want %v", buf, expectedReq)
}
c1.Write(tt.resp)
resp := <-done
if tt.expectedErr != "" {
if resp.err == nil || !strings.Contains(resp.err.Error(), tt.expectedErr) {
t.Fatalf("got err %q; want err containing %q", resp.err, tt.expectedErr)
}
return
}
if resp.err != nil {
t.Fatalf("got err %q; want no err", resp.err)
}
if resp.status != tt.respStatus {
t.Fatalf("got status %v; want %v", resp.status, tt.respStatus)
}
if !bytes.Equal(resp.payload, tt.respPayload) {
t.Errorf("got payload %v; want %v", resp.payload, tt.respPayload)
}
})
}
}
+66 -9
View File
@@ -16,6 +16,7 @@ import (
"io"
"math/big"
"slices"
"sync"
"golang.org/x/crypto/curve25519"
)
@@ -718,15 +719,9 @@ func (gex *dhGEXSHA) Server(c packetConn, randSource io.Reader, magics *handshak
kexDHGexRequest.MaxBits, kexDHGexRequest.PreferredBits)
}
var p *big.Int
// We hardcode sending Oakley Group 14 (2048 bits), Oakley Group 15 (3072
// bits) or Oakley Group 16 (4096 bits), based on the requested max size.
if kexDHGexRequest.MaxBits < 3072 {
p, _ = new(big.Int).SetString(oakleyGroup14, 16)
} else if kexDHGexRequest.MaxBits < 4096 {
p, _ = new(big.Int).SetString(oakleyGroup15, 16)
} else {
p, _ = new(big.Int).SetString(oakleyGroup16, 16)
p, err := chooseDH(kexDHGexRequest)
if err != nil {
return nil, err
}
g := big.NewInt(2)
@@ -805,3 +800,65 @@ func (gex *dhGEXSHA) Server(c packetConn, randSource io.Reader, magics *handshak
Hash: gex.hashFunc,
}, err
}
type dhKEXGroup struct {
size int
p *big.Int
}
// supportedDHKEXGroups returns the DH groups the server is willing to offer
// for diffie-hellman-group-exchange-* key exchanges. The list is built lazily
// on first use to keep the hex-to-big.Int parse out of package initialization.
var supportedDHKEXGroups = sync.OnceValue(func() []dhKEXGroup {
specs := []struct {
size int
hex string
}{
{2048, oakleyGroup14},
{3072, oakleyGroup15},
{4096, oakleyGroup16},
}
out := make([]dhKEXGroup, 0, len(specs))
for _, s := range specs {
p, _ := new(big.Int).SetString(s.hex, 16)
out = append(out, dhKEXGroup{size: s.size, p: p})
}
return out
})
// chooseDH picks a DH group for the given client request, mirroring the
// algorithm used by OpenSSH's choose_dh in dh.c: prefer the smallest known
// group larger than or equal to the client's PreferredBits, and otherwise pick
// the largest group within the accepted [MinBits, MaxBits] range.
func chooseDH(req kexDHGexRequestMsg) (*big.Int, error) {
var best *big.Int
bestSize := 0
wantBits := int(req.PreferredBits)
for _, group := range supportedDHKEXGroups() {
if uint32(group.size) < req.MinBits || uint32(group.size) > req.MaxBits {
continue
}
if bestSize == 0 {
best = group.p
bestSize = group.size
continue
}
closerFromAbove := group.size >= wantBits && group.size < bestSize
closerFromBelow := group.size > bestSize && bestSize < wantBits
if closerFromAbove || closerFromBelow {
best = group.p
bestSize = group.size
}
}
if bestSize == 0 {
return nil, fmt.Errorf("ssh: no suitable DH group found for request min: %d, preferred: %d, max: %d",
req.MinBits, req.PreferredBits, req.MaxBits)
}
return best, nil
}
+83
View File
@@ -9,6 +9,7 @@ package ssh
import (
"crypto/rand"
"fmt"
"math/big"
"reflect"
"sync"
"testing"
@@ -65,6 +66,88 @@ func TestKexes(t *testing.T) {
}
}
func TestChooseDH(t *testing.T) {
oakley := map[int]string{
2048: oakleyGroup14,
3072: oakleyGroup15,
4096: oakleyGroup16,
}
expected := func(size int) *big.Int {
hex, ok := oakley[size]
if !ok {
t.Fatalf("test setup: no Oakley group for size %d", size)
}
p, _ := new(big.Int).SetString(hex, 16)
return p
}
tests := []struct {
name string
request kexDHGexRequestMsg
want int // expected bit size; 0 means error expected
wantErr bool
}{
{
name: "Standard 2048 request",
request: kexDHGexRequestMsg{MinBits: 1024, PreferredBits: 2048, MaxBits: 8192},
want: 2048,
},
{
name: "Standard 3072 request",
request: kexDHGexRequestMsg{MinBits: 1024, PreferredBits: 3072, MaxBits: 8192},
want: 3072,
},
{
name: "Standard 4096 request",
request: kexDHGexRequestMsg{MinBits: 1024, PreferredBits: 4096, MaxBits: 8192},
want: 4096,
},
{
name: "Preferred 2500 -> Expect 3072 (round up)",
request: kexDHGexRequestMsg{MinBits: 1024, PreferredBits: 2500, MaxBits: 8192},
want: 3072,
},
{
name: "Preferred 3500 -> Expect 4096 (round up)",
request: kexDHGexRequestMsg{MinBits: 1024, PreferredBits: 3500, MaxBits: 8192},
want: 4096,
},
{
name: "Preferred too high (8000) -> Expect 4096 (cap at max available)",
request: kexDHGexRequestMsg{MinBits: 1024, PreferredBits: 8000, MaxBits: 8192},
want: 4096,
},
{
name: "No group in range",
request: kexDHGexRequestMsg{MinBits: 2500, PreferredBits: 2500, MaxBits: 2900},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := chooseDH(tt.request)
if (err != nil) != tt.wantErr {
t.Errorf("chooseDH() error = %v, wantErr %t", err, tt.wantErr)
return
}
if tt.wantErr {
return
}
if got == nil {
t.Fatalf("chooseDH() returned nil big.Int but expected success")
}
if got.BitLen() != tt.want {
t.Errorf("chooseDH() got size = %d, want %d", got.BitLen(), tt.want)
}
if want := expected(tt.want); got.Cmp(want) != 0 {
t.Errorf("chooseDH() returned the wrong group for size %d", tt.want)
}
})
}
}
func BenchmarkKexes(b *testing.B) {
type kexResultErr struct {
result *kexResult
+96 -3
View File
@@ -76,7 +76,7 @@ func parsePubKey(in []byte, algo string) (pubKey PublicKey, rest []byte, err err
case InsecureKeyAlgoDSA:
return parseDSA(in)
case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521:
return parseECDSA(in)
return parseECDSA(in, algo)
case KeyAlgoSKECDSA256:
return parseSKECDSA(in)
case KeyAlgoED25519:
@@ -469,6 +469,12 @@ func parseRSA(in []byte) (out PublicKey, rest []byte, err error) {
return nil, nil, err
}
// 8192 bits is also the maximum RSA key size accepted by crypto/tls for
// signature verification:
// https://github.com/golang/go/blob/69801b25/src/crypto/tls/handshake_client.go#L1096
if w.N.BitLen() > 8192 {
return nil, nil, errors.New("ssh: rsa modulus too large")
}
if w.E.BitLen() > 24 {
return nil, nil, errors.New("ssh: exponent too large")
}
@@ -574,6 +580,24 @@ func checkDSAParams(param *dsa.Parameters) error {
return fmt.Errorf("ssh: unsupported DSA key size %d", l)
}
// FIPS 186-2 specifies that Q must be exactly 160 bits. We must enforce
// this to prevent DoS attacks where an attacker sends a huge Q which makes
// verification slow.
if l := param.Q.BitLen(); l != 160 {
return fmt.Errorf("ssh: unsupported DSA sub-prime size %d", l)
}
// The generator G is an element of the group, so it must be strictly less
// than the modulus P.
if param.G.Cmp(param.P) >= 0 {
return errors.New("ssh: DSA generator larger than modulus")
}
// G must be positive.
if param.G.Sign() <= 0 {
return errors.New("ssh: DSA generator must be positive")
}
return nil
}
@@ -596,6 +620,14 @@ func parseDSA(in []byte) (out PublicKey, rest []byte, err error) {
return nil, nil, err
}
// The public value Y must be a non-zero element of the group, i.e.
// strictly between 0 and P. crypto/dsa.Verify does not range-check Y,
// so we reject out-of-range values here to prevent a maliciously
// oversized Y from slowing verification.
if w.Y.Sign() <= 0 || w.Y.Cmp(w.P) >= 0 {
return nil, nil, errors.New("ssh: DSA public value Y out of range")
}
key := &dsaPublicKey{
Parameters: param,
Y: w.Y,
@@ -774,7 +806,7 @@ func supportedEllipticCurve(curve elliptic.Curve) bool {
}
// parseECDSA parses an ECDSA key according to RFC 5656, section 3.1.
func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) {
func parseECDSA(in []byte, expectedType string) (out PublicKey, rest []byte, err error) {
var w struct {
Curve string
KeyBytes []byte
@@ -785,6 +817,12 @@ func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) {
return nil, nil, err
}
actualType := "ecdsa-sha2-" + w.Curve
if expectedType != actualType {
return nil, nil, fmt.Errorf("ssh: algorithm type mismatch: expected %q, found curve %q (type %q)",
expectedType, w.Curve, actualType)
}
key := new(ecdsa.PublicKey)
switch w.Curve {
@@ -869,11 +907,25 @@ type skFields struct {
Counter uint32
}
// flagUserPresence is the "user present" bit (UP) in the SK signature
// flags, matching the FIDO CTAP2 authenticatorData UP flag. See
// openssh/PROTOCOL.u2f.
const flagUserPresence = 0x01
// errSKMissingUserPresence is returned by SK key Verify methods when
// the signature does not assert user presence and the key was not
// marked as no-touch-required.
var errSKMissingUserPresence = errors.New("ssh: signature missing required user presence flag")
type skECDSAPublicKey struct {
// application is a URL-like string, typically "ssh:" for SSH.
// see openssh/PROTOCOL.u2f for details.
application string
ecdsa.PublicKey
// noTouchRequired, when true, disables the default user-presence
// check in Verify. It is set by skKeyWithoutUP on a clone of the
// key, never on an instance shared across authentication attempts.
noTouchRequired bool
}
func (k *skECDSAPublicKey) Type() string {
@@ -959,6 +1011,10 @@ func (k *skECDSAPublicKey) Verify(data []byte, sig *Signature) error {
return err
}
if skf.Flags&flagUserPresence == 0 && !k.noTouchRequired {
return errSKMissingUserPresence
}
blob := struct {
ApplicationDigest []byte `ssh:"rest"`
Flags byte
@@ -992,6 +1048,10 @@ type skEd25519PublicKey struct {
// see openssh/PROTOCOL.u2f for details.
application string
ed25519.PublicKey
// noTouchRequired, when true, disables the default user-presence
// check in Verify. It is set by skKeyWithoutUP on a clone of the
// key, never on an instance shared across authentication attempts.
noTouchRequired bool
}
func (k *skEd25519PublicKey) Type() string {
@@ -1066,6 +1126,10 @@ func (k *skEd25519PublicKey) Verify(data []byte, sig *Signature) error {
return err
}
if skf.Flags&flagUserPresence == 0 && !k.noTouchRequired {
return errSKMissingUserPresence
}
blob := struct {
ApplicationDigest []byte `ssh:"rest"`
Flags byte
@@ -1408,6 +1472,17 @@ func passphraseProtectedOpenSSHKey(passphrase []byte) openSSHDecryptFunc {
return nil, err
}
// OpenSSH does not impose an upper bound on the bcrypt round count
// stored in the key file, but bcrypt_pbkdf cost is linear in rounds:
// the default is 16, ssh-keygen lets users pick anything up to
// INT_MAX. Cap at 2048 (128x the default, a few seconds of CPU) so
// that an oversized value in the file cannot tie up the caller for
// months.
const maxRounds = 1 << 11
if opts.Rounds > maxRounds {
return nil, fmt.Errorf("ssh: bcrypt KDF rounds %d exceed maximum %d", opts.Rounds, maxRounds)
}
k, err := bcrypt_pbkdf.Key(passphrase, []byte(opts.Salt), int(opts.Rounds), 32+16)
if err != nil {
return nil, err
@@ -1577,10 +1652,28 @@ func parseOpenSSHPrivateKey(key []byte, decrypt openSSHDecryptFunc) (crypto.Priv
return nil, err
}
// Mirror the validation done in parseRSA for public keys: cap the
// modulus at the same limit enforced by crypto/tls, reject oversized
// or invalid exponents, and additionally bound the prime factors to
// avoid the expensive CRT coefficient recomputation in pk.Precompute.
if key.N.BitLen() > 8192 {
return nil, errors.New("ssh: rsa modulus too large")
}
if key.P.BitLen() > 4096 || key.Q.BitLen() > 4096 {
return nil, errors.New("ssh: rsa prime too large")
}
if key.E.BitLen() > 24 {
return nil, errors.New("ssh: exponent too large")
}
e := key.E.Int64()
if e < 3 || e&1 == 0 {
return nil, errors.New("ssh: incorrect exponent")
}
pk := &rsa.PrivateKey{
PublicKey: rsa.PublicKey{
N: key.N,
E: int(key.E.Int64()),
E: int(e),
},
D: key.D,
Primes: []*big.Int{key.P, key.Q},
+646 -12
View File
@@ -12,6 +12,7 @@ import (
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/hex"
@@ -19,6 +20,7 @@ import (
"errors"
"fmt"
"io"
"math/big"
"reflect"
"strings"
"testing"
@@ -216,6 +218,214 @@ func TestParseRSAPrivateKey(t *testing.T) {
}
}
func TestParseRSAModulusTooLarge(t *testing.T) {
rsa16384 := "ssh-rsa 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"
_, _, _, _, err := ParseAuthorizedKey([]byte(rsa16384))
if err == nil {
t.Fatal("ParseAuthorizedKey accepted a 16384-bit modulus; expected it to be rejected")
}
expectedError := "rsa modulus too large"
if !strings.Contains(err.Error(), expectedError) {
t.Errorf("unexpected error message: got %q, want substring %q", err.Error(), expectedError)
}
}
func TestParsePrivateKeyRSAModulusTooLarge(t *testing.T) {
rsa16384 := []byte(`-----BEGIN OPENSSH PRIVATE KEY-----
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
QHAxNnM=
-----END OPENSSH PRIVATE KEY-----
`)
_, err := ParseRawPrivateKey(rsa16384)
if err == nil {
t.Fatal("ParseRawPrivateKey accepted a 16384-bit modulus; expected it to be rejected")
}
expectedError := "rsa modulus too large"
if !strings.Contains(err.Error(), expectedError) {
t.Errorf("unexpected error message: got %q, want substring %q", err.Error(), expectedError)
}
}
func TestParseECPrivateKey(t *testing.T) {
key := testPrivateKeys["ecdsa"]
@@ -272,18 +482,18 @@ func TestParseEncryptedPrivateKeysWithPassphrase(t *testing.T) {
}
func TestParseEncryptedPrivateKeysWithUnsupportedCiphers(t *testing.T) {
for _, tt := range testdata.UnsupportedCipherData {
t.Run(tt.Name, func(t *testing.T){
_, err := ParsePrivateKeyWithPassphrase(tt.PEMBytes, []byte(tt.EncryptionKey))
if err == nil {
t.Fatalf("expected 'unknown cipher' error for %q, got nil", tt.Name)
// If this cipher is now supported, remove it from testdata.UnsupportedCipherData
}
if !strings.Contains(err.Error(), "unknown cipher") {
t.Errorf("wanted 'unknown cipher' error, got %v", err.Error())
}
})
}
for _, tt := range testdata.UnsupportedCipherData {
t.Run(tt.Name, func(t *testing.T) {
_, err := ParsePrivateKeyWithPassphrase(tt.PEMBytes, []byte(tt.EncryptionKey))
if err == nil {
t.Fatalf("expected 'unknown cipher' error for %q, got nil", tt.Name)
// If this cipher is now supported, remove it from testdata.UnsupportedCipherData
}
if !strings.Contains(err.Error(), "unknown cipher") {
t.Errorf("wanted 'unknown cipher' error, got %v", err.Error())
}
})
}
}
func TestParseEncryptedPrivateKeysWithIncorrectPassphrase(t *testing.T) {
@@ -296,6 +506,38 @@ func TestParseEncryptedPrivateKeysWithIncorrectPassphrase(t *testing.T) {
}
}
func TestParseEncryptedPrivateKeyExcessiveBcryptRounds(t *testing.T) {
// Craft a minimal openssh-key-v1 blob whose KdfOpts declares a bcrypt
// round count above the accepted maximum. The check must reject the file
// before bcrypt_pbkdf is invoked, so the rest of the blob (public key,
// encrypted body) can be empty.
kdfOpts := Marshal(struct {
Salt []byte
Rounds uint32
}{
Salt: []byte("salt-not-used"),
Rounds: (1 << 11) + 1,
})
header := Marshal(openSSHEncryptedPrivateKey{
CipherName: "aes256-ctr",
KdfName: "bcrypt",
KdfOpts: string(kdfOpts),
NumKeys: 1,
})
pemBytes := pem.EncodeToMemory(&pem.Block{
Type: "OPENSSH PRIVATE KEY",
Bytes: append([]byte(privateKeyAuthMagic), header...),
})
_, err := ParseRawPrivateKeyWithPassphrase(pemBytes, []byte("password"))
if err == nil {
t.Fatal("expected error for excessive bcrypt rounds, got nil")
}
if !strings.Contains(err.Error(), "bcrypt KDF rounds") {
t.Errorf("got error %q, want substring %q", err.Error(), "bcrypt KDF rounds")
}
}
func TestParseDSA(t *testing.T) {
// We actually exercise the ParsePrivateKey codepath here, as opposed to
// using the ParseRawPrivateKey+NewSignerFromKey path that testdata_test.go
@@ -356,6 +598,72 @@ func TestMarshalParsePublicKey(t *testing.T) {
}
}
func TestParseDSAHugeQ(t *testing.T) {
P := new(big.Int).Lsh(big.NewInt(1), 1023)
Q := new(big.Int).Lsh(big.NewInt(1), 20000) // very large
// G and Y: Dummy values, just needs to be < P to pass that specific check
G := big.NewInt(2)
Y := big.NewInt(5)
rawKey := struct {
P, Q, G, Y *big.Int
}{
P: P,
Q: Q,
G: G,
Y: Y,
}
inputBytes := Marshal(&rawKey)
_, _, err := parseDSA(inputBytes)
if err == nil {
t.Fatal("parseDSA accepted a DSA key with large Q")
}
expectedError := "ssh: unsupported DSA sub-prime size"
if !strings.Contains(err.Error(), expectedError) {
t.Errorf("unexpected error message: got %q, want substring %q", err.Error(), expectedError)
}
}
func TestParseDSAYOutOfRange(t *testing.T) {
// Valid 1024/160 parameters (values don't need to be a real DSA group,
// they only need to pass the checkDSAParams bit-length checks and the
// G < P / G > 0 checks).
P := new(big.Int).Lsh(big.NewInt(1), 1023)
P.SetBit(P, 0, 1) // make P odd so it can pass as a prime candidate shape
Q := new(big.Int).Lsh(big.NewInt(1), 159)
Q.SetBit(Q, 0, 1)
G := big.NewInt(2)
for _, tc := range []struct {
name string
Y *big.Int
}{
{"Y_zero", big.NewInt(0)},
{"Y_negative", big.NewInt(-1)},
{"Y_equals_P", new(big.Int).Set(P)},
{"Y_greater_than_P", new(big.Int).Add(P, big.NewInt(1))},
{"Y_much_greater_than_P", new(big.Int).Lsh(big.NewInt(1), 20000)},
} {
t.Run(tc.name, func(t *testing.T) {
rawKey := struct {
P, Q, G, Y *big.Int
}{P: P, Q: Q, G: G, Y: tc.Y}
_, _, err := parseDSA(Marshal(&rawKey))
if err == nil {
t.Fatalf("parseDSA accepted a DSA key with Y=%s (P=%s)", tc.Y, P)
}
expectedError := "DSA public value Y out of range"
if !strings.Contains(err.Error(), expectedError) {
t.Errorf("unexpected error message: got %q, want substring %q", err.Error(), expectedError)
}
})
}
}
func TestMarshalPrivateKey(t *testing.T) {
tests := []struct {
name string
@@ -760,6 +1068,296 @@ func TestSKKeys(t *testing.T) {
}
}
// skTestHarness builds SK-formatted signatures over a fixed payload
// using a caller-supplied signing function, letting tests vary the UP
// flag byte without duplicating the wire-format scaffolding.
type skTestHarness struct {
format string
application string
data []byte
// sign takes the SHA-256 digest of the marshalled SK blob and
// returns the value to embed in Signature.Blob. For ECDSA keys the
// helper feeds the digest to ecdsa.Sign; for ed25519 the helper
// feeds the raw marshalled blob to ed25519.Sign.
signDigest func(digest []byte) []byte
signBlob func(blob []byte) []byte
}
func (h skTestHarness) sign(t *testing.T, flags byte) *Signature {
t.Helper()
hsh := sha256.New()
hsh.Write([]byte(h.application))
appDigest := hsh.Sum(nil)
hsh.Reset()
hsh.Write(h.data)
dataDigest := hsh.Sum(nil)
var counter uint32 = 1
blob := struct {
ApplicationDigest []byte `ssh:"rest"`
Flags byte
Counter uint32
MessageDigest []byte `ssh:"rest"`
}{appDigest, flags, counter, dataDigest}
marshalled := Marshal(blob)
var sigBlob []byte
if h.signDigest != nil {
hsh.Reset()
hsh.Write(marshalled)
sigBlob = h.signDigest(hsh.Sum(nil))
} else {
sigBlob = h.signBlob(marshalled)
}
return &Signature{
Format: h.format,
Blob: sigBlob,
Rest: Marshal(struct {
Flags byte
Counter uint32
}{flags, counter}),
}
}
func TestSKUserPresence(t *testing.T) {
ecKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
h := skTestHarness{
format: "sk-ecdsa-sha2-nistp256@openssh.com",
application: "ssh:",
data: []byte("test data"),
signDigest: func(digest []byte) []byte {
r, s, err := ecdsa.Sign(rand.Reader, ecKey, digest)
if err != nil {
t.Fatal(err)
}
return Marshal(struct{ R, S *big.Int }{r, s})
},
}
pk := &skECDSAPublicKey{
application: h.application,
PublicKey: ecKey.PublicKey,
}
// Valid signature with UP=1 should pass.
if err := pk.Verify(h.data, h.sign(t, flagUserPresence)); err != nil {
t.Errorf("Verify failed with UP=1: %v", err)
}
// Valid signature with UP=0 should fail with the user-presence sentinel.
sigNoUP := h.sign(t, 0)
if err := pk.Verify(h.data, sigNoUP); !errors.Is(err, errSKMissingUserPresence) {
t.Errorf("expected errSKMissingUserPresence, got: %v", err)
}
// UV set but UP clear must still fail: we only waive UP, never UV-only.
if err := pk.Verify(h.data, h.sign(t, 0x04)); !errors.Is(err, errSKMissingUserPresence) {
t.Errorf("UV-only (flags=0x04): expected errSKMissingUserPresence, got: %v", err)
}
// With noTouchRequired, UP=0 passes; UP=1+UV=1 also passes.
pk.noTouchRequired = true
if err := pk.Verify(h.data, sigNoUP); err != nil {
t.Errorf("Verify with noTouchRequired failed: %v", err)
}
if err := pk.Verify(h.data, h.sign(t, flagUserPresence|0x04)); err != nil {
t.Errorf("Verify UP|UV with noTouchRequired failed: %v", err)
}
}
func TestSKKeyWithoutUP(t *testing.T) {
ecKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
edPub, _, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
skEC := &skECDSAPublicKey{PublicKey: ecKey.PublicKey}
skED := &skEd25519PublicKey{PublicKey: edPub}
certEC := &Certificate{Key: &skECDSAPublicKey{PublicKey: ecKey.PublicKey}}
certED := &Certificate{Key: &skEd25519PublicKey{PublicKey: edPub}}
rsaKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
rsaPub, err := NewPublicKey(&rsaKey.PublicKey)
if err != nil {
t.Fatal(err)
}
certRSA := &Certificate{Key: rsaPub}
// SK raw keys: return a clone with the flag set, original untouched.
gotEC := skKeyWithoutUP(skEC)
if gotEC == skEC {
t.Error("skECDSAPublicKey: expected a clone, got the original pointer")
}
if !gotEC.(*skECDSAPublicKey).noTouchRequired {
t.Error("skECDSAPublicKey clone: noTouchRequired not set")
}
if skEC.noTouchRequired {
t.Error("skECDSAPublicKey: original mutated")
}
gotED := skKeyWithoutUP(skED)
if gotED == skED {
t.Error("skEd25519PublicKey: expected a clone, got the original pointer")
}
if !gotED.(*skEd25519PublicKey).noTouchRequired {
t.Error("skEd25519PublicKey clone: noTouchRequired not set")
}
if skED.noTouchRequired {
t.Error("skEd25519PublicKey: original mutated")
}
// Certificate wrapping SK: return a clone of the cert with a cloned
// SK key inside. Neither the original cert nor the original inner
// key must be mutated.
originalInnerEC := certEC.Key
gotCertEC := skKeyWithoutUP(certEC)
if gotCertEC == certEC {
t.Error("*Certificate(SK ecdsa): expected a clone, got the original pointer")
}
if got := gotCertEC.(*Certificate).Key.(*skECDSAPublicKey); !got.noTouchRequired {
t.Error("*Certificate(SK ecdsa): inner clone missing noTouchRequired")
}
if certEC.Key != originalInnerEC {
t.Error("*Certificate(SK ecdsa): original cert's Key pointer mutated")
}
if originalInnerEC.(*skECDSAPublicKey).noTouchRequired {
t.Error("*Certificate(SK ecdsa): original inner key mutated")
}
gotCertED := skKeyWithoutUP(certED)
if gotCertED == certED {
t.Error("*Certificate(SK ed25519): expected a clone, got the original pointer")
}
if got := gotCertED.(*Certificate).Key.(*skEd25519PublicKey); !got.noTouchRequired {
t.Error("*Certificate(SK ed25519): inner clone missing noTouchRequired")
}
// Non-SK key inside a cert: return original unchanged (nothing to clone).
if got := skKeyWithoutUP(certRSA); got != certRSA {
t.Error("*Certificate(RSA): expected the original pointer back")
}
// Plain non-SK key: return original unchanged.
if got := skKeyWithoutUP(rsaPub); got != rsaPub {
t.Error("rsaPublicKey: expected the original pointer back")
}
// Pathological: *Certificate whose Key is itself a *Certificate.
// The SSH cert format forbids this and parseCert rejects it, but
// a Go caller can still construct such a value. skKeyWithoutUP
// must not recurse into it (or panic); it returns the input
// unchanged. This also defends against a hypothetical cycle built
// from hand-constructed Certificate pointers.
nestedCert := &Certificate{Key: &Certificate{Key: skEC}}
if got := skKeyWithoutUP(nestedCert); got != nestedCert {
t.Error("*Certificate wrapping *Certificate: expected the original pointer back")
}
selfCycle := &Certificate{}
selfCycle.Key = selfCycle
if got := skKeyWithoutUP(selfCycle); got != selfCycle {
t.Error("self-referential *Certificate: expected the original pointer back")
}
}
func TestNoTouchAllowed(t *testing.T) {
ecKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
sk := &skECDSAPublicKey{PublicKey: ecKey.PublicKey}
certNoExt := &Certificate{Key: sk}
certOptOut := &Certificate{
Key: sk,
Permissions: Permissions{Extensions: map[string]string{"no-touch-required": ""}},
}
// Non-empty value: OpenSSH writes "" but any value must be accepted
// because the check is presence-only.
certOptOutNonEmpty := &Certificate{
Key: sk,
Permissions: Permissions{Extensions: map[string]string{"no-touch-required": "yes"}},
}
// no-touch-required belongs in Extensions, never CriticalOptions.
// Putting it in CriticalOptions must NOT be treated as opt-out.
certCritOnly := &Certificate{
Key: sk,
Permissions: Permissions{CriticalOptions: map[string]string{"no-touch-required": ""}},
}
permsEmpty := &Permissions{}
permsOptOut := &Permissions{Extensions: map[string]string{"no-touch-required": ""}}
permsCritOnly := &Permissions{CriticalOptions: map[string]string{"no-touch-required": ""}}
cases := []struct {
name string
pub PublicKey
perms *Permissions
want bool
}{
{"nil perms, no cert", sk, nil, false},
{"empty perms, no cert", sk, permsEmpty, false},
{"perms opt-out, raw key", sk, permsOptOut, true},
{"nil perms, cert opt-out", certOptOut, nil, true},
{"nil perms, cert opt-out non-empty value", certOptOutNonEmpty, nil, true},
{"nil perms, cert no ext", certNoExt, nil, false},
{"perms opt-out, cert no ext", certNoExt, permsOptOut, true},
{"empty perms, cert opt-out", certOptOut, permsEmpty, true},
// Negative controls: CriticalOptions must not waive UP.
{"critical-options only, raw key", sk, permsCritOnly, false},
{"critical-options only, cert", certCritOnly, nil, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := noTouchAllowed(tc.pub, tc.perms); got != tc.want {
t.Errorf("noTouchAllowed = %v, want %v", got, tc.want)
}
})
}
}
func TestSKUserPresenceEd25519(t *testing.T) {
pub, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
h := skTestHarness{
format: "sk-ssh-ed25519@openssh.com",
application: "ssh:",
data: []byte("test data"),
signBlob: func(blob []byte) []byte {
return ed25519.Sign(priv, blob)
},
}
pk := &skEd25519PublicKey{
application: h.application,
PublicKey: pub,
}
if err := pk.Verify(h.data, h.sign(t, flagUserPresence)); err != nil {
t.Errorf("Verify failed with UP=1: %v", err)
}
sigNoUP := h.sign(t, 0)
if err := pk.Verify(h.data, sigNoUP); !errors.Is(err, errSKMissingUserPresence) {
t.Errorf("expected errSKMissingUserPresence, got: %v", err)
}
pk.noTouchRequired = true
if err := pk.Verify(h.data, sigNoUP); err != nil {
t.Errorf("Verify with noTouchRequired failed: %v", err)
}
}
func TestNewSignerWithAlgos(t *testing.T) {
algorithSigner, ok := testSigners["rsa"].(AlgorithmSigner)
if !ok {
@@ -863,3 +1461,39 @@ cLYUOHfQDw==
t.Fatal("parsing an SSH certificate using another certificate as signature key succeeded; expected failure")
}
}
func TestParseECDSAAlgorithmMismatch(t *testing.T) {
cases := []struct {
keyName string // key fixture in testPublicKeys
nativeAlgo string // algorithm actually carried in the key blob
askedAlgo string // algorithm passed to parsePubKey
}{
{"ecdsap256", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384"},
{"ecdsap256", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp521"},
{"ecdsap384", "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp256"},
{"ecdsap384", "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521"},
{"ecdsap521", "ecdsa-sha2-nistp521", "ecdsa-sha2-nistp256"},
{"ecdsap521", "ecdsa-sha2-nistp521", "ecdsa-sha2-nistp384"},
}
for _, tc := range cases {
t.Run(tc.nativeAlgo+"_as_"+tc.askedAlgo, func(t *testing.T) {
pubKey := testPublicKeys[tc.keyName]
algo, in, ok := parseString(pubKey.Marshal())
if !ok {
t.Fatal("unable to parse public key wire format")
}
if string(algo) != tc.nativeAlgo {
t.Fatalf("test setup failed: expected %q, got %q", tc.nativeAlgo, algo)
}
_, _, err := parsePubKey(in, tc.askedAlgo)
if err == nil {
t.Fatal("expected error due to algorithm mismatch, but got nil")
}
if !strings.Contains(err.Error(), "algorithm type mismatch") {
t.Fatalf("unexpected error message: %v", err)
}
})
}
}
+27 -6
View File
@@ -160,8 +160,13 @@ func (db *hostKeyDB) IsHostAuthority(remote ssh.PublicKey, address string) bool
// IsRevoked can be used as a callback in ssh.CertChecker
func (db *hostKeyDB) IsRevoked(key *ssh.Certificate) bool {
_, ok := db.revoked[string(key.Marshal())]
return ok
if _, ok := db.revoked[string(key.Marshal())]; ok {
return true
}
if _, ok := db.revoked[string(key.SignatureKey.Marshal())]; ok {
return true
}
return false
}
const markerCert = "@cert-authority"
@@ -173,7 +178,7 @@ func nextWord(line []byte) (string, []byte) {
return string(line), nil
}
return string(line[:i]), bytes.TrimSpace(line[i:])
return string(line[:i]), trimSpace(line[i:])
}
func parseLine(line []byte) (marker, host string, key ssh.PublicKey, err error) {
@@ -183,12 +188,17 @@ func parseLine(line []byte) (marker, host string, key ssh.PublicKey, err error)
}
host, line = nextWord(line)
// If the extracted 'host' starts with '@', it means we either encountered
// a second marker (e.g., "@cert-authority @revoked") or an unknown marker
// (e.g., "@unknown"). Both are invalid.
if len(host) > 0 && host[0] == '@' {
return "", "", nil, fmt.Errorf("knownhosts: unexpected marker: %q", host)
}
if len(line) == 0 {
return "", "", nil, errors.New("knownhosts: missing host pattern")
}
// ignore the keytype as it's in the key blob anyway.
_, line = nextWord(line)
wantType, line := nextWord(line)
if len(line) == 0 {
return "", "", nil, errors.New("knownhosts: missing key type pattern")
}
@@ -204,6 +214,10 @@ func parseLine(line []byte) (marker, host string, key ssh.PublicKey, err error)
return "", "", nil, err
}
if key.Type() != wantType {
return "", "", nil, fmt.Errorf("knownhosts: key type mismatch: found %q, want %q", key.Type(), wantType)
}
return marker, host, key, nil
}
@@ -382,7 +396,7 @@ func (db *hostKeyDB) Read(r io.Reader, filename string) error {
for scanner.Scan() {
lineNum++
line := scanner.Bytes()
line = bytes.TrimSpace(line)
line = trimSpace(line)
if len(line) == 0 || line[0] == '#' {
continue
}
@@ -530,3 +544,10 @@ func newHashedHost(encoded string) (*hashedHost, error) {
func (h *hashedHost) match(a addr) bool {
return bytes.Equal(hashHost(Normalize(a.String()), h.salt), h.hash)
}
// trimSpace removes leading and trailing ASCII whitespace (space and tab). It
// is used instead of bytes.TrimSpace to match OpenSSH behavior, which strictly
// parses only ASCII space (0x20) and tab (0x09) as whitespace.
func trimSpace(in []byte) []byte {
return bytes.Trim(in, " \t")
}
+134 -1
View File
@@ -6,9 +6,13 @@ package knownhosts
import (
"bytes"
"crypto/ed25519"
"crypto/rand"
"encoding/base64"
"fmt"
"net"
"reflect"
"strings"
"testing"
"golang.org/x/crypto/ssh"
@@ -272,7 +276,45 @@ func TestWildcardMatch(t *testing.T) {
}
}
// TODO(hanwen): test coverage for certificates.
func TestRevokedCA(t *testing.T) {
_, caPriv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
caSigner, err := ssh.NewSignerFromKey(caPriv)
if err != nil {
t.Fatal(err)
}
caKey := caSigner.PublicKey()
_, hostPriv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
hostKey, err := ssh.NewPublicKey(hostPriv.Public())
if err != nil {
t.Fatal(err)
}
cert := &ssh.Certificate{
CertType: ssh.HostCert,
Key: hostKey,
ValidBefore: ssh.CertTimeInfinity,
ValidPrincipals: []string{"server.org"},
}
if err := cert.SignCert(rand.Reader, caSigner); err != nil {
t.Fatal(err)
}
caLine := "ssh-ed25519 " + serialize(caKey)[len("ssh-ed25519 "):]
knownHostsData := "@revoked server.org " + caLine + "\n" +
"@cert-authority server.org " + caLine + "\n"
db := testDB(t, knownHostsData)
if !db.IsRevoked(cert) {
t.Error("IsRevoked returned false for certificate signed by revoked CA")
}
}
const testHostname = "hostname"
@@ -367,3 +409,94 @@ func TestIssue36126(t *testing.T) {
t.Errorf("should have passed the check, got %v", err)
}
}
func TestUnicodeSpace(t *testing.T) {
line := fmt.Sprintf("server.org %s  %s", edKey.Type(), base64.StdEncoding.EncodeToString(edKey.Marshal()))
db := newHostKeyDB()
err := db.Read(bytes.NewBufferString(line), "testdb")
if err == nil {
t.Fatal("Read succeeded on line with Unicode space, expected error due to strict ASCII parsing")
}
}
func TestUnicodeSpaceTrimming(t *testing.T) {
const unicodeSpace = " "
line := fmt.Sprintf("%sserver.org %s", unicodeSpace, edKeyStr)
db := newHostKeyDB()
err := db.Read(bytes.NewBufferString(line), "testdb")
if err != nil {
t.Fatalf("Read failed: %v", err)
}
lines := db.lines
if len(lines) != 1 {
t.Fatalf("Expected 1 line, got %d", len(lines))
}
cleanAddr := addr{host: "server.org", port: "22"}
dirtyAddr := addr{host: unicodeSpace + "server.org", port: "22"}
if lines[0].match(cleanAddr) {
t.Errorf("Matched clean host 'server.org', implying Unicode space was trimmed")
}
if !lines[0].match(dirtyAddr) {
t.Errorf("Did not match dirty host, implying parsing issue")
}
}
func TestKeyTypeMismatch(t *testing.T) {
line := fmt.Sprintf("server.org ssh-rsa %s", base64.StdEncoding.EncodeToString(edKey.Marshal()))
db := newHostKeyDB()
err := db.Read(bytes.NewBufferString(line), "testdb")
if err == nil {
t.Fatal("Read succeeded on line with key type mismatch, expected error")
}
expectedErr := `knownhosts: key type mismatch: found "ssh-ed25519", want "ssh-rsa"`
if !strings.Contains(err.Error(), expectedErr) {
t.Fatalf("got error %q, want to contain %q", err.Error(), expectedErr)
}
}
func TestMultipleMarkers(t *testing.T) {
lineDouble := fmt.Sprintf("@cert-authority @revoked server.org %s %s", edKey.Type(), base64.StdEncoding.EncodeToString(edKey.Marshal()))
db := newHostKeyDB()
err := db.Read(bytes.NewBufferString(lineDouble), "testdb")
if err == nil {
t.Fatal("Read succeeded on line with multiple markers, expected error")
}
expectedError := "unexpected marker"
if !strings.Contains(err.Error(), expectedError) {
t.Errorf("got error %q, want it to contain %q", err.Error(), expectedError)
}
lineUnknown := fmt.Sprintf("@unknown-marker server.org %s %s", edKey.Type(), base64.StdEncoding.EncodeToString(edKey.Marshal()))
err = db.Read(bytes.NewBufferString(lineUnknown), "testdb")
if err == nil {
t.Fatal("Read succeeded on line with unknown marker, expected error")
}
if !strings.Contains(err.Error(), expectedError) {
t.Errorf("got error %q, want it to contain %q", err.Error(), expectedError)
}
}
func TestUnknownMarker(t *testing.T) {
line := fmt.Sprintf("@unknown-marker server.org %s %s", edKey.Type(), base64.StdEncoding.EncodeToString(edKey.Marshal()))
db := newHostKeyDB()
err := db.Read(bytes.NewBufferString(line), "testdb")
if err == nil {
t.Fatal("Read succeeded on line with unknown marker, expected error")
}
expectedError := "unexpected marker"
if !strings.Contains(err.Error(), expectedError) {
t.Errorf("got error %q, want it to contain %q", err.Error(), expectedError)
}
}
+35 -4
View File
@@ -91,9 +91,10 @@ type mux struct {
incomingChannels chan NewChannel
globalSentMu sync.Mutex
globalResponses chan interface{}
incomingRequests chan *Request
globalSentMu sync.Mutex
globalSentPending atomic.Bool
globalResponses chan interface{}
incomingRequests chan *Request
errCond *sync.Cond
err error
@@ -141,6 +142,27 @@ func (m *mux) SendRequest(name string, wantReply bool, payload []byte) (bool, []
if wantReply {
m.globalSentMu.Lock()
defer m.globalSentMu.Unlock()
// Open the gate so that responses arriving while this request is in
// flight are allowed to reach globalResponses. Any response arriving
// while no request is pending is dropped by handleGlobalPacket.
m.globalSentPending.Store(true)
defer m.globalSentPending.Store(false)
// Drain any spurious responses that may have been buffered. This prevents
// a previously buffered unexpected response from being consumed instead
// of the actual response for this request.
drain:
for {
select {
case _, ok := <-m.globalResponses:
if !ok {
break drain
}
default:
break drain
}
}
}
if err := m.sendMessage(globalRequestMsg{
@@ -267,7 +289,16 @@ func (m *mux) handleGlobalPacket(packet []byte) error {
mux: m,
}
case *globalRequestSuccessMsg, *globalRequestFailureMsg:
m.globalResponses <- msg
// Drop responses that arrive when no SendRequest is waiting, to
// prevent a malicious peer from staging responses for a future
// caller.
if !m.globalSentPending.Load() {
return nil
}
select {
case m.globalResponses <- msg:
default:
}
default:
panic(fmt.Sprintf("not a global message %#v", msg))
}
+606
View File
@@ -10,6 +10,7 @@ import (
"io"
"sync"
"testing"
"time"
)
func muxPair() (*mux, *mux) {
@@ -825,6 +826,50 @@ func TestMuxChannelWindowDeferredUpdates(t *testing.T) {
}
}
func TestMuxChannelRejectRemovesFromMux(t *testing.T) {
serverMux, clientMux := muxPair()
defer serverMux.Close()
defer clientMux.Close()
var wg sync.WaitGroup
t.Cleanup(wg.Wait)
wg.Add(1)
go func() {
defer wg.Done()
// The server waits for the channel creation request
newCh, ok := <-serverMux.incomingChannels
if !ok {
t.Error("failed to accept channel")
return
}
ch := newCh.(*channel)
if serverMux.chanList.getChan(ch.localId) == nil {
t.Errorf("channel %d is not in the chanList before Reject", ch.localId)
}
if err := ch.Reject(Prohibited, "rejecting this channel"); err != nil {
t.Errorf("Reject failed: %v", err)
}
if serverMux.chanList.getChan(ch.localId) != nil {
t.Errorf("channel %d is still in the chanList after Reject", ch.localId)
}
}()
_, _, err := clientMux.OpenChannel("test_leak", nil)
if err == nil {
t.Fatal("expected an error (channel rejected), but got nil")
}
if _, ok := err.(*OpenChannelError); !ok {
t.Errorf("expected *OpenChannelError, got: %T", err)
}
}
// Don't ship code with debug=true.
func TestDebug(t *testing.T) {
if debugMux {
@@ -837,3 +882,564 @@ func TestDebug(t *testing.T) {
t.Error("transport debug switched on")
}
}
func TestMuxUnexpectedGlobalResponsesDiscarded(t *testing.T) {
clientPipe, serverPipe := memPipe()
client := newMux(clientPipe)
defer serverPipe.Close()
defer client.Close()
done := make(chan error, 1)
go func() {
// Send multiple unexpected global responses, this should not block the
// globalResponses channel.
for i := range 5 {
err := serverPipe.writePacket(Marshal(globalRequestSuccessMsg{
Data: []byte{byte(i)},
}))
if err != nil {
done <- fmt.Errorf("send success msg %d: %w", i, err)
return
}
}
for i := range 5 {
err := serverPipe.writePacket(Marshal(globalRequestFailureMsg{
Data: []byte{byte(i)},
}))
if err != nil {
done <- fmt.Errorf("send failure msg %d: %w", i, err)
return
}
}
// Now send a global request and wait for the response. This
// verifies the mux is still processing packets.
err := serverPipe.writePacket(Marshal(globalRequestMsg{
Type: "keepalive@golang.org",
WantReply: true,
Data: nil,
}))
if err != nil {
done <- fmt.Errorf("send global request: %w", err)
return
}
packet, err := serverPipe.readPacket()
if err != nil {
done <- fmt.Errorf("read packet: %w", err)
return
}
decoded, err := decode(packet)
if err != nil {
done <- fmt.Errorf("decode: %w", err)
return
}
switch decoded.(type) {
case *globalRequestSuccessMsg, *globalRequestFailureMsg:
// Expected response
default:
done <- fmt.Errorf("unexpected packet type: %T", decoded)
return
}
done <- nil
}()
// Handle the incoming request from the server and reply
req, ok := <-client.incomingRequests
if !ok {
t.Fatal("incomingRequests channel closed unexpectedly")
}
if req.Type != "keepalive@golang.org" {
t.Fatalf("unexpected request type: %s", req.Type)
}
if err := req.Reply(true, nil); err != nil {
t.Fatalf("Reply: %v", err)
}
if err := <-done; err != nil {
t.Fatal(err)
}
}
func TestMuxConcurrentGlobalRequests(t *testing.T) {
clientMux, serverMux := muxPair()
defer serverMux.Close()
defer clientMux.Close()
const numRequests = 50
serverDone := make(chan struct{})
go func() {
defer close(serverDone)
for r := range serverMux.incomingRequests {
if r.WantReply {
replyData := append([]byte("reply:"), r.Payload...)
r.Reply(true, replyData)
}
}
}()
var clientWg sync.WaitGroup
clientWg.Add(numRequests)
errCh := make(chan error, numRequests)
for i := range numRequests {
go func(id int) {
defer clientWg.Done()
payloadStr := fmt.Sprintf("req-%d", id)
payload := []byte(payloadStr)
// This call blocks until the globalSentMu is acquired.
// The mutex ensures that even with many concurrent attempts,
// the "drain" and "send" logic happens atomically per request.
ok, data, err := clientMux.SendRequest("echo", true, payload)
if err != nil {
errCh <- fmt.Errorf("req %d error: %v", id, err)
return
}
if !ok {
errCh <- fmt.Errorf("req %d failed (want success)", id)
return
}
expected := "reply:" + payloadStr
if string(data) != expected {
errCh <- fmt.Errorf("req %d mismatch: got %q, want %q", id, string(data), expected)
}
}(i)
}
clientWg.Wait()
close(errCh)
for err := range errCh {
if err != nil {
t.Fatal(err)
}
}
clientMux.Close()
<-serverDone
}
func TestMuxGlobalResponseDroppedWhenIdle(t *testing.T) {
clientPipe, serverPipe := memPipe()
clientMux := newMux(clientPipe)
defer serverPipe.Close()
defer clientMux.Close()
errCh := make(chan error, 1)
go func() {
// Send a spurious response while no SendRequest is pending.
if err := serverPipe.writePacket(Marshal(globalRequestSuccessMsg{
Data: []byte("spurious"),
})); err != nil {
errCh <- fmt.Errorf("send spurious: %w", err)
return
}
// Follow with a global request; once the client observes this on
// incomingRequests, the mux loop has necessarily processed (and
// dropped) the prior spurious response.
if err := serverPipe.writePacket(Marshal(globalRequestMsg{
Type: "sync@example.com",
WantReply: false,
})); err != nil {
errCh <- fmt.Errorf("send sync request: %w", err)
return
}
errCh <- nil
}()
if err := <-errCh; err != nil {
t.Fatal(err)
}
req, ok := <-clientMux.incomingRequests
if !ok {
t.Fatal("incomingRequests closed unexpectedly")
}
if req.Type != "sync@example.com" {
t.Fatalf("unexpected sync request type %q", req.Type)
}
// The spurious response preceded the sync request, so by now the mux
// loop has processed it. The pending-gate must have caused it to be
// dropped rather than buffered.
if n := len(clientMux.globalResponses); n != 0 {
t.Fatalf("globalResponses buffer should be empty after idle drop, has %d entries", n)
}
}
func TestMuxStaleResponseDrained(t *testing.T) {
// Simulate a stale response sitting in globalResponses (e.g. a response
// that slipped in through the pending-gate on a prior SendRequest that
// exited without consuming it). The drain step in the next SendRequest
// must discard it so the caller receives the correct reply.
clientMux, serverMux := muxPair()
defer serverMux.Close()
defer clientMux.Close()
clientMux.globalResponses <- &globalRequestSuccessMsg{Data: []byte("stale")}
serverDone := make(chan struct{})
go func() {
defer close(serverDone)
for req := range serverMux.incomingRequests {
if req.WantReply {
req.Reply(true, append([]byte("reply:"), req.Payload...))
}
}
}()
ok, data, err := clientMux.SendRequest("test", true, []byte("hello"))
if err != nil {
t.Fatalf("request failed: %v", err)
}
if !ok {
t.Fatal("expected success response")
}
if string(data) != "reply:hello" {
t.Fatalf("got %q, want %q (drain did not remove stale response)", data, "reply:hello")
}
clientMux.Close()
<-serverDone
}
func TestMuxGlobalResponseAcceptedWhilePending(t *testing.T) {
// Positive control: when a SendRequest is actually pending, the
// response must be delivered (the gate is open).
clientMux, serverMux := muxPair()
defer serverMux.Close()
defer clientMux.Close()
serverDone := make(chan struct{})
go func() {
defer close(serverDone)
for req := range serverMux.incomingRequests {
if req.WantReply {
req.Reply(true, []byte("pong"))
}
}
}()
ok, data, err := clientMux.SendRequest("ping", true, nil)
if err != nil {
t.Fatalf("SendRequest: %v", err)
}
if !ok || string(data) != "pong" {
t.Fatalf("unexpected response: ok=%v data=%q", ok, data)
}
clientMux.Close()
<-serverDone
}
func TestChannelUnexpectedResponsesDiscarded(t *testing.T) {
// A malicious peer that spams channelRequestSuccess/Failure messages
// for an open, idle channel must not be able to stall the mux read
// loop by filling ch.msg. After the flood, the channel must still be
// usable: a subsequent legitimate SendRequest receives its reply.
clientMux, serverMux := muxPair()
defer serverMux.Close()
defer clientMux.Close()
serverRes := make(chan *channel, 1)
go func() {
newCh, ok := <-serverMux.incomingChannels
if !ok {
close(serverRes)
return
}
c, _, err := newCh.Accept()
if err != nil {
close(serverRes)
return
}
serverRes <- c.(*channel)
}()
clientCh, err := clientMux.openChannel("chan", nil)
if err != nil {
t.Fatalf("openChannel: %v", err)
}
serverCh := <-serverRes
if serverCh == nil {
t.Fatal("server did not accept channel")
}
// Spam many unsolicited success/failure responses. More than chanSize
// to ensure ch.msg would overflow without the pending-gate.
const spam = chanSize * 4
done := make(chan error, 1)
go func() {
for i := range spam {
if err := serverCh.ackRequest(i%2 == 0); err != nil {
done <- fmt.Errorf("ackRequest %d: %w", i, err)
return
}
}
// Echo any legitimate request back.
for req := range serverCh.incomingRequests {
if req.WantReply {
if err := req.Reply(true, append([]byte("reply:"), req.Payload...)); err != nil {
done <- fmt.Errorf("reply: %w", err)
return
}
}
}
done <- nil
}()
// If the flood had wedged the mux loop, this SendRequest would never
// receive a reply.
ok, err := clientCh.SendRequest("ping", true, []byte("hello"))
if err != nil {
t.Fatalf("SendRequest: %v", err)
}
if !ok {
t.Fatal("expected success reply")
}
// Clean up so the server goroutine can exit.
clientCh.Close()
serverCh.Close()
if err := <-done; err != nil {
if !errors.Is(err, io.EOF) {
t.Fatal(err)
}
}
}
func TestChannelConcurrentRequests(t *testing.T) {
writer, reader, mux := channelPair(t)
defer writer.Close()
defer reader.Close()
defer mux.Close()
serverDone := make(chan struct{})
go func() {
defer close(serverDone)
for req := range writer.incomingRequests {
if req.WantReply {
req.Reply(true, append([]byte("reply:"), req.Payload...))
}
}
}()
const numRequests = 50
var wg sync.WaitGroup
wg.Add(numRequests)
errCh := make(chan error, numRequests)
for i := 0; i < numRequests; i++ {
go func(id int) {
defer wg.Done()
payload := []byte(fmt.Sprintf("req-%d", id))
ok, err := reader.SendRequest("echo", true, payload)
if err != nil {
errCh <- fmt.Errorf("req %d: %v", id, err)
return
}
if !ok {
errCh <- fmt.Errorf("req %d: expected success", id)
}
}(i)
}
wg.Wait()
close(errCh)
for err := range errCh {
if err != nil {
t.Fatal(err)
}
}
reader.Close()
writer.Close()
<-serverDone
}
func TestChannelResponseDroppedWhenIdle(t *testing.T) {
// A spurious response arriving while no SendRequest is pending must
// be dropped rather than buffered in ch.msg.
writer, reader, mux := channelPair(t)
defer writer.Close()
defer reader.Close()
defer mux.Close()
// Server sends an unsolicited reply, then a request so we can
// synchronise: once the client observes the request, the mux loop has
// necessarily processed (and dropped) the prior spurious reply.
errCh := make(chan error, 1)
go func() {
if err := writer.ackRequest(true); err != nil {
errCh <- err
return
}
if _, err := writer.SendRequest("sync", false, nil); err != nil {
errCh <- err
return
}
errCh <- nil
}()
req := <-reader.incomingRequests
if req.Type != "sync" {
t.Fatalf("unexpected request type %q", req.Type)
}
if n := len(reader.msg); n != 0 {
t.Fatalf("ch.msg should be empty after idle drop, has %d entries", n)
}
if err := <-errCh; err != nil {
t.Fatal(err)
}
}
func TestChannelStaleResponseDrained(t *testing.T) {
// Simulate a stale response sitting in ch.msg (e.g. a response that
// slipped through the pending-gate on a prior SendRequest that exited
// without consuming it). The drain step in the next SendRequest must
// discard it so the caller receives the correct reply.
writer, reader, mux := channelPair(t)
defer writer.Close()
defer reader.Close()
defer mux.Close()
reader.msg <- &channelRequestSuccessMsg{PeersID: reader.remoteId}
serverDone := make(chan struct{})
go func() {
defer close(serverDone)
for req := range writer.incomingRequests {
if req.WantReply {
req.Reply(false, append([]byte("nack:"), req.Payload...))
}
}
}()
ok, err := reader.SendRequest("test", true, []byte("hello"))
if err != nil {
t.Fatalf("SendRequest: %v", err)
}
// If the stale success had been consumed, ok would be true.
if ok {
t.Fatal("got stale success response; drain did not remove it")
}
reader.Close()
writer.Close()
<-serverDone
}
func TestChannelResponseAcceptedWhilePending(t *testing.T) {
// Positive control: when a SendRequest is actually pending, the
// response must be delivered (the gate is open).
writer, reader, mux := channelPair(t)
defer writer.Close()
defer reader.Close()
defer mux.Close()
serverDone := make(chan struct{})
go func() {
defer close(serverDone)
for req := range writer.incomingRequests {
if req.WantReply {
req.Reply(true, nil)
}
}
}()
ok, err := reader.SendRequest("ping", true, nil)
if err != nil {
t.Fatalf("SendRequest: %v", err)
}
if !ok {
t.Fatal("expected success")
}
reader.Close()
writer.Close()
<-serverDone
}
func TestChannelSendRequestAfterCloseNoSpinloop(t *testing.T) {
writer, reader, mux := channelPair(t)
defer writer.Close()
defer mux.Close()
// Close the channel, this closes reader.msg.
if err := reader.Close(); err != nil {
t.Fatalf("Close: %v", err)
}
// Wait for reader.msg to actually be closed by the mux loop.
for {
select {
case _, ok := <-reader.msg:
if !ok {
goto closed
}
case <-time.After(2 * time.Second):
t.Fatal("reader.msg was not closed")
}
}
closed:
done := make(chan error, 1)
go func() {
_, err := reader.SendRequest("ping", true, nil)
done <- err
}()
select {
case err := <-done:
if !errors.Is(err, io.EOF) {
t.Fatalf("SendRequest after close: got %v, want io.EOF", err)
}
case <-time.After(2 * time.Second):
t.Fatal("SendRequest spinloop on closed ch.msg")
}
}
func TestMuxSendRequestAfterCloseNoSpinloop(t *testing.T) {
a, b := muxPair()
defer a.Close()
// Closing the underlying conn causes mux.loop to exit and close
// b.globalResponses.
if err := b.Close(); err != nil {
t.Fatalf("Close: %v", err)
}
// Wait for globalResponses to actually be closed by loop().
for {
select {
case _, ok := <-b.globalResponses:
if !ok {
goto closed
}
case <-time.After(2 * time.Second):
t.Fatal("globalResponses was not closed")
}
}
closed:
done := make(chan error, 1)
go func() {
_, _, err := b.SendRequest("ping", true, nil)
done <- err
}()
select {
case err := <-done:
if err == nil {
t.Fatal("SendRequest after close: got nil error")
}
case <-time.After(2 * time.Second):
t.Fatal("SendRequest spinloop on closed globalResponses")
}
}
+147 -18
View File
@@ -34,21 +34,29 @@ type Permissions struct {
// or not supported.
CriticalOptions map[string]string
// Extensions are extra functionality that the server may
// offer on authenticated connections. Lack of support for an
// extension does not preclude authenticating a user. Common
// extensions are "permit-agent-forwarding",
// "permit-X11-forwarding". The Go SSH library currently does
// not act on any extension, and it is up to server
// implementations to honor them. Extensions can be used to
// pass data from the authentication callbacks to the server
// application layer.
// Extensions are extra functionality that the server may offer on
// authenticated connections. Lack of support for an extension does not
// preclude authenticating a user. Common extensions are
// "permit-agent-forwarding", "permit-X11-forwarding". In general the Go
// SSH library does not act on extensions and it is up to server
// implementations to honor them; extensions can also be used to pass data
// from the authentication callbacks to the server application layer.
//
// The one extension acted upon by this library is "no-touch-required",
// which applies only to security-key public keys
// (sk-ecdsa-sha2-nistp256@openssh.com and sk-ssh-ed25519@openssh.com).
// When present, it waives the default requirement that SK signatures
// assert user presence (i.e. a physical touch of the authenticator)
// during signature verification.
Extensions map[string]string
// ExtraData allows to store user defined data.
ExtraData map[any]any
}
// GSSAPIWithMICConfig includes the server callbacks for gssapi-with-mic
// authentication. If either field is nil, gssapi-with-mic is considered not
// configured.
type GSSAPIWithMICConfig struct {
// AllowLogin, must be set, is called when gssapi-with-mic
// authentication is selected (RFC 4462 section 3). The srcName is from the
@@ -63,6 +71,10 @@ type GSSAPIWithMICConfig struct {
Server GSSAPIServer
}
func gssapiWithMICConfigured(config *GSSAPIWithMICConfig) bool {
return config != nil && config.AllowLogin != nil && config.Server != nil
}
// SendAuthBanner implements [ServerPreAuthConn].
func (s *connection) SendAuthBanner(msg string) error {
return s.transport.writePacket(Marshal(&userAuthBannerMsg{
@@ -84,6 +96,79 @@ type ServerPreAuthConn interface {
SendAuthBanner(string) error
}
// noTouchRequiredExtension is the extension name used by OpenSSH in
// authorized_keys options and certificate extensions to mark keys
// whose signatures do not need to assert user presence (touch). See
// ssh-keygen(1) and sshd(8).
const noTouchRequiredExtension = "no-touch-required"
// noTouchAllowed reports whether the user presence requirement on
// SK signatures should be waived for this authentication attempt. The
// requirement is waived when the "no-touch-required" extension is
// present either in the Permissions returned by the auth callback
// (authorized_keys-level opt-out) or in the certificate's own
// Extensions (CA-level opt-out), matching OpenSSH behavior. OpenSSH
// reads the per-key opt-out only from cert Extensions and
// authorized_keys options (never from CriticalOptions); we follow the
// same rule.
func noTouchAllowed(pubKey PublicKey, perms *Permissions) bool {
if perms != nil {
if _, ok := perms.Extensions[noTouchRequiredExtension]; ok {
return true
}
}
if cert, ok := pubKey.(*Certificate); ok {
if _, ok := cert.Extensions[noTouchRequiredExtension]; ok {
return true
}
}
return false
}
// skKeyWithoutUP returns a PublicKey equivalent to pubKey but whose
// Verify accepts SK signatures with the user-presence flag clear. If
// pubKey is not (and does not wrap) an SK key, pubKey is returned
// unchanged. The returned value never mutates pubKey: for SK keys a
// shallow copy is made so that the noTouchRequired flag is set only on
// the clone.
//
// The implementation is iterative rather than recursive. When pubKey
// is a *Certificate we unwrap exactly one level to look at the inner
// key. The SSH cert format forbids Certificate.Key from being another
// Certificate (parseCert rejects it), but nothing stops callers from
// constructing such a value directly in Go; a recursive descent could
// otherwise be driven to unbounded depth by a hand-crafted or cyclic
// Certificate. A malformed input of that shape simply returns
// unchanged here.
func skKeyWithoutUP(pubKey PublicKey) PublicKey {
cert, isCert := pubKey.(*Certificate)
target := pubKey
if isCert {
target = cert.Key
}
var cloned PublicKey
switch k := target.(type) {
case *skECDSAPublicKey:
c := *k
c.noTouchRequired = true
cloned = &c
case *skEd25519PublicKey:
c := *k
c.noTouchRequired = true
cloned = &c
default:
// Not an SK key (or a pathological *Certificate wrapping
// another *Certificate): pubKey is already usable for Verify.
return pubKey
}
if !isCert {
return cloned
}
c := *cert
c.Key = cloned
return &c
}
// ServerConfig holds server specific configuration data.
type ServerConfig struct {
// Config contains configuration shared between client and server.
@@ -242,8 +327,10 @@ func (c *pubKeyCache) add(candidate cachedPubKey) {
type ServerConn struct {
Conn
// If the succeeding authentication callback returned a
// non-nil Permissions pointer, it is stored here.
// If the succeeding authentication callback returned a non-nil Permissions
// pointer, it is stored here. These are the permissions from the final,
// successful authentication method. Permissions returned by callbacks that
// return PartialSuccessError are not preserved and must be nil.
Permissions *Permissions
}
@@ -302,8 +389,7 @@ func (s *connection) serverHandshake(config *ServerConfig) (*Permissions, error)
}
if !config.NoClientAuth && config.PasswordCallback == nil && config.PublicKeyCallback == nil &&
config.KeyboardInteractiveCallback == nil && (config.GSSAPIWithMICConfig == nil ||
config.GSSAPIWithMICConfig.AllowLogin == nil || config.GSSAPIWithMICConfig.Server == nil) {
config.KeyboardInteractiveCallback == nil && !gssapiWithMICConfigured(config.GSSAPIWithMICConfig) {
return nil, errors.New("ssh: no authentication methods configured but NoClientAuth is also false")
}
@@ -527,6 +613,15 @@ func (b *BannerError) Error() string {
return b.Err.Error()
}
// maxAuthServerAttempts caps the total number of SSH_MSG_USERAUTH_REQUEST
// messages the server will process on a single connection, regardless of
// outcome (failure, partial success, public key query, or none). It is a
// backstop against clients that drive the authentication loop indefinitely
// without ever incurring a real failure — for example by repeatedly
// triggering PartialSuccessError or by spamming public key offer queries —
// neither of which increment the MaxAuthTries failure counter.
const maxAuthServerAttempts = 128
func (s *connection) serverAuthenticate(config *ServerConfig) (*Permissions, error) {
if config.PreAuthConnCallback != nil {
config.PreAuthConnCallback(s)
@@ -537,6 +632,7 @@ func (s *connection) serverAuthenticate(config *ServerConfig) (*Permissions, err
var perms *Permissions
authFailures := 0
authAttempts := 0
noneAuthCount := 0
var authErrs []error
var calledBannerCallback bool
@@ -565,6 +661,19 @@ userAuthLoop:
return nil, &ServerAuthError{Errors: authErrs}
}
if authAttempts >= maxAuthServerAttempts {
discMsg := &disconnectMsg{
Reason: 2,
Message: "too many authentication attempts",
}
if err := s.transport.writePacket(Marshal(discMsg)); err != nil {
return nil, err
}
authErrs = append(authErrs, discMsg)
return nil, &ServerAuthError{Errors: authErrs}
}
authAttempts++
var userAuthReq userAuthRequestMsg
if packet, err := s.transport.readPacket(); err != nil {
if err == io.EOF {
@@ -737,8 +846,15 @@ userAuthLoop:
}
signedData := buildDataSignedForAuth(sessionID, userAuthReq, algo, pubKeyData)
if err := pubKey.Verify(signedData, sig); err != nil {
// pubKey is reused below for VerifiedPublicKeyCallback and
// must remain the key as presented by the client; derive a
// separate value for Verify that carries any applicable
// no-touch-required opt-out.
pubKeyForVerify := pubKey
if noTouchAllowed(pubKey, candidate.perms) {
pubKeyForVerify = skKeyWithoutUP(pubKey)
}
if err := pubKeyForVerify.Verify(signedData, sig); err != nil {
return nil, err
}
@@ -750,9 +866,16 @@ userAuthLoop:
// considered verified and the callback must not run.
perms, authErr = config.VerifiedPublicKeyCallback(s, pubKey, perms, algo)
}
if authErr == nil && perms != nil && perms.CriticalOptions != nil {
if saco := perms.CriticalOptions[sourceAddressCriticalOption]; saco != "" {
if err := checkSourceAddress(s.RemoteAddr(), saco); err != nil {
authErr = err
}
}
}
}
case "gssapi-with-mic":
if authConfig.GSSAPIWithMICConfig == nil {
if !gssapiWithMICConfigured(authConfig.GSSAPIWithMICConfig) {
authErr = errors.New("ssh: gssapi-with-mic auth not configured")
break
}
@@ -824,6 +947,13 @@ userAuthLoop:
var failureMsg userAuthFailureMsg
if partialSuccess, ok := authErr.(*PartialSuccessError); ok {
// Permissions are not preserved between authentication steps. To
// avoid confusion about the final state of the connection, we
// disallow returning non-nil Permissions combined with
// PartialSuccessError.
if perms != nil {
return nil, errors.New("ssh: permissions must be nil when returning PartialSuccessError")
}
// After a partial success error we don't allow changing the user
// name and execute the NoClientAuthCallback.
partialSuccessReturned = true
@@ -878,8 +1008,7 @@ userAuthLoop:
if authConfig.KeyboardInteractiveCallback != nil {
failureMsg.Methods = append(failureMsg.Methods, "keyboard-interactive")
}
if authConfig.GSSAPIWithMICConfig != nil && authConfig.GSSAPIWithMICConfig.Server != nil &&
authConfig.GSSAPIWithMICConfig.AllowLogin != nil {
if gssapiWithMICConfigured(authConfig.GSSAPIWithMICConfig) {
failureMsg.Methods = append(failureMsg.Methods, "gssapi-with-mic")
}
+278 -5
View File
@@ -6,11 +6,17 @@ package ssh
import (
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"io"
"math/big"
"net"
"reflect"
"slices"
"strings"
"sync/atomic"
"testing"
@@ -160,6 +166,52 @@ func TestMaxAuthTriesNoneMethod(t *testing.T) {
}
}
func TestMaxAuthServerAttempts(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
invocations := 0
clientConf := &ClientConfig{
User: "user",
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
invocations++
return PublicKeys(testSigners["rsa"]), nil
},
}
go NewServerConn(c1, alwaysPartialPubKeyServer())
_, _, _, err = NewClientConn(c2, "", clientConf)
if err == nil {
t.Fatal("expected the server to disconnect after exceeding the attempts cap")
}
// The error must be the server's disconnect, not the client-side
// "too many authentication attempts (N), aborting" bound. The
// disconnect format is set by disconnectMsg.Error().
if !strings.Contains(err.Error(), "ssh: disconnect") ||
!strings.Contains(err.Error(), "too many authentication attempts") {
t.Fatalf("expected server disconnect, got: %v", err)
}
// Server-side request sequence per AuthCallback iteration:
// 1 "none" (initial, before any AuthCallback)
// 2 pubkey query (AuthCallback #k, server returns OK)
// 3 pubkey signed (AuthCallback #k, server returns partial)
// So after k complete callbacks the server has processed 1+2k requests.
// The (k+1)-th callback's query is processed as request number 2(k+1);
// the subsequent signed request is rejected by the cap check
// (authAttempts >= maxAuthServerAttempts), so 2(k+1) = maxAuthServerAttempts
// and invocations = maxAuthServerAttempts / 2.
expected := maxAuthServerAttempts / 2
if invocations != expected {
t.Errorf("AuthCallback invoked %d times; want %d", invocations, expected)
}
}
func TestMaxAuthTriesFirstNoneAuthErrorIgnored(t *testing.T) {
username := "testuser"
serverConfig := &ServerConfig{
@@ -526,12 +578,18 @@ func TestVerifiedPublicCallbackPartialSuccess(t *testing.T) {
serverConf.AddHostKey(testSigners["rsa"])
clientConf := ClientConfig{
User: "user",
Auth: []AuthMethod{
PublicKeys(testSigners["rsa"]),
Password(clientPassword),
},
User: "user",
Auth: nil,
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
if slices.Contains(ctx.AllowedMethods, "publickey") && !slices.Contains(ctx.PartialSuccessMethods, "publickey") {
return PublicKeys(testSigners["rsa"]), nil
}
if slices.Contains(ctx.AllowedMethods, "password") && slices.Contains(ctx.PartialSuccessMethods, "publickey") {
return Password(clientPassword), nil
}
return nil, nil
},
}
go NewServerConn(c1, serverConf)
@@ -664,6 +722,44 @@ func TestVerifiedPubKeyCallbackError(t *testing.T) {
}
}
func TestVerifiedPubKeyCallbackSourceAddress(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
serverConf := &ServerConfig{
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
return nil, nil
},
VerifiedPublicKeyCallback: func(conn ConnMetadata, key PublicKey, permissions *Permissions, signatureAlgorithm string) (*Permissions, error) {
return &Permissions{
CriticalOptions: map[string]string{
sourceAddressCriticalOption: "192.168.99.99",
},
}, nil
},
}
serverConf.AddHostKey(testSigners["rsa"])
clientConf := ClientConfig{
User: "user",
Auth: []AuthMethod{
PublicKeys(testSigners["rsa"]),
},
HostKeyCallback: InsecureIgnoreHostKey(),
}
go NewServerConn(c1, serverConf)
_, _, _, err = NewClientConn(c2, "", &clientConf)
if err == nil {
t.Fatal("client login succeed with VerifiedPublicKeyCallback returning mismatching source-address")
}
}
func TestVerifiedPublicCallbackPartialSuccessBadUsage(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
@@ -808,6 +904,60 @@ func TestVerifiedPublicKeyCallbackOnly(t *testing.T) {
<-done
}
func TestPartialSuccessWithNonNilPerms(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
serverConf := &ServerConfig{
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
return nil, nil
}
return nil, errors.New("invalid credentials")
},
VerifiedPublicKeyCallback: func(conn ConnMetadata, key PublicKey, permissions *Permissions, signatureAlgorithm string) (*Permissions, error) {
if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
// Intentionally return non-nil Permissions along with a
// PartialSuccessError. Since permissions are reset between
// authentication steps, this constitutes invalid library usage
// and the server is expected to reject the connection.
return &Permissions{Extensions: map[string]string{"permit-port-forwarding": ""}}, &PartialSuccessError{
Next: ServerAuthCallbacks{
PasswordCallback: func(conn ConnMetadata, password []byte) (*Permissions, error) {
if string(password) == clientPassword {
return nil, nil
}
return nil, nil
},
},
}
}
return nil, errors.New("invalid credentials")
},
}
serverConf.AddHostKey(testSigners["rsa"])
clientConf := ClientConfig{
User: "user",
Auth: []AuthMethod{
PublicKeys(testSigners["rsa"]),
Password(clientPassword),
},
HostKeyCallback: InsecureIgnoreHostKey(),
}
go NewServerConn(c1, serverConf)
_, _, _, err = NewClientConn(c2, "", &clientConf)
if err == nil {
t.Fatal("authentication succeeded unexpectedly; server should have rejected non-nil Permissions combined with PartialSuccessError")
}
}
type markerConn struct {
closed uint32
used uint32
@@ -850,3 +1000,126 @@ func (*markerConn) RemoteAddr() net.Addr { return nil }
func (*markerConn) SetDeadline(t time.Time) error { return nil }
func (*markerConn) SetReadDeadline(t time.Time) error { return nil }
func (*markerConn) SetWriteDeadline(t time.Time) error { return nil }
// skTestSigner is a Signer that produces SK-ECDSA signatures over
// user-auth data, simulating a FIDO/U2F authenticator. The flags
// byte (UP and other bits) is caller-controlled so tests can exercise
// the server's user-presence enforcement and its opt-out paths. This
// is test-only: the real Signer is hardware-backed.
type skTestSigner struct {
priv *ecdsa.PrivateKey
pub PublicKey
flags byte
application string
}
func (s *skTestSigner) PublicKey() PublicKey { return s.pub }
func (s *skTestSigner) Sign(r io.Reader, data []byte) (*Signature, error) {
h := sha256.New()
h.Write([]byte(s.application))
appDigest := h.Sum(nil)
h.Reset()
h.Write(data)
dataDigest := h.Sum(nil)
var counter uint32 = 1
blob := struct {
ApplicationDigest []byte `ssh:"rest"`
Flags byte
Counter uint32
MessageDigest []byte `ssh:"rest"`
}{appDigest, s.flags, counter, dataDigest}
h.Reset()
h.Write(Marshal(blob))
digest := h.Sum(nil)
x, y, err := ecdsa.Sign(r, s.priv, digest)
if err != nil {
return nil, err
}
return &Signature{
Format: KeyAlgoSKECDSA256,
Blob: Marshal(struct{ R, S *big.Int }{x, y}),
Rest: Marshal(struct {
Flags byte
Counter uint32
}{s.flags, counter}),
}, nil
}
// TestServerAuthSKUserPresence drives the full userAuthLoop with an SK
// public-key client and verifies the server's wiring of the UP check
// and its two opt-out paths: the per-key Permissions.Extensions route
// and (via cert) the cert-level route. It also confirms that non-SK
// clients are unaffected by the new code path.
func TestServerAuthSKUserPresence(t *testing.T) {
userKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
skPub := &skECDSAPublicKey{application: "ssh:", PublicKey: userKey.PublicKey}
runAuth := func(t *testing.T, signer Signer, perms *Permissions) error {
t.Helper()
c1, c2, err := netPipe()
if err != nil {
t.Fatal(err)
}
defer c1.Close()
defer c2.Close()
serverConf := &ServerConfig{
PublicKeyCallback: func(ConnMetadata, PublicKey) (*Permissions, error) {
return perms, nil
},
}
serverConf.AddHostKey(testSigners["ecdsa"])
serverErr := make(chan error, 1)
go func() {
_, _, _, err := NewServerConn(c1, serverConf)
serverErr <- err
}()
clientConf := &ClientConfig{
User: "user",
Auth: []AuthMethod{PublicKeys(signer)},
HostKeyCallback: InsecureIgnoreHostKey(),
}
_, _, _, clientErr := NewClientConn(c2, "", clientConf)
<-serverErr
return clientErr
}
optOut := &Permissions{Extensions: map[string]string{noTouchRequiredExtension: ""}}
t.Run("UP=1, default perms accepts", func(t *testing.T) {
s := &skTestSigner{priv: userKey, pub: skPub, flags: flagUserPresence, application: "ssh:"}
if err := runAuth(t, s, nil); err != nil {
t.Errorf("expected auth to succeed: %v", err)
}
})
t.Run("UP=0, default perms rejects", func(t *testing.T) {
s := &skTestSigner{priv: userKey, pub: skPub, flags: 0, application: "ssh:"}
if err := runAuth(t, s, nil); err == nil {
t.Error("expected auth to fail with UP=0")
}
})
t.Run("UP=0, perms opt-out accepts", func(t *testing.T) {
s := &skTestSigner{priv: userKey, pub: skPub, flags: 0, application: "ssh:"}
if err := runAuth(t, s, optOut); err != nil {
t.Errorf("expected auth to succeed with opt-out: %v", err)
}
})
t.Run("UP=0, perms CriticalOptions does NOT opt out", func(t *testing.T) {
s := &skTestSigner{priv: userKey, pub: skPub, flags: 0, application: "ssh:"}
critOnly := &Permissions{CriticalOptions: map[string]string{noTouchRequiredExtension: ""}}
if err := runAuth(t, s, critOnly); err == nil {
t.Error("no-touch-required in CriticalOptions must not waive UP")
}
})
t.Run("non-SK RSA signer unaffected", func(t *testing.T) {
if err := runAuth(t, testSigners["rsa"], nil); err != nil {
t.Errorf("plain RSA auth must still work: %v", err)
}
})
}
+3
View File
@@ -423,6 +423,9 @@ func (s *Session) wait(reqs <-chan *Request) error {
for msg := range reqs {
switch msg.Type {
case "exit-status":
if len(msg.Payload) < 4 {
return errors.New("ssh: malformed exit-status request")
}
wm.status = int(binary.BigEndian.Uint32(msg.Payload))
case "exit-signal":
var sigval struct {
+30
View File
@@ -334,6 +334,25 @@ func TestExitWithoutStatusOrSignal(t *testing.T) {
}
}
func TestExitStatusShortPayload(t *testing.T) {
for _, payload := range [][]byte{nil, {0}, {0, 0}, {0, 0, 0}} {
conn := dial(exitStatusShortPayloadHandler(payload), t)
session, err := conn.NewSession()
if err != nil {
t.Fatalf("unable to request new session: %v", err)
}
if err := session.Shell(); err != nil {
t.Fatalf("unable to execute command: %v", err)
}
err = session.Wait()
if err == nil {
t.Fatalf("expected error for payload length %d", len(payload))
}
session.Close()
conn.Close()
}
}
// windowTestBytes is the number of bytes that we'll send to the SSH server.
const windowTestBytes = 16000 * 200
@@ -482,6 +501,17 @@ func exitWithoutSignalOrStatus(ch Channel, in <-chan *Request, t *testing.T) {
readLine(shell, t)
}
func exitStatusShortPayloadHandler(payload []byte) serverType {
return func(ch Channel, in <-chan *Request, t *testing.T) {
defer ch.Close()
shell := newServerShell(ch, in, "> ")
readLine(shell, t)
if _, err := ch.SendRequest("exit-status", false, payload); err != nil {
t.Errorf("unable to send status: %v", err)
}
}
}
func shellHandler(ch Channel, in <-chan *Request, t *testing.T) {
defer ch.Close()
// this string is returned to stdout
+2 -3
View File
@@ -24,9 +24,8 @@ func TestAgentForward(t *testing.T) {
t.Fatalf("Error adding key: %s", err)
}
if err := keyring.Add(agent.AddedKey{
PrivateKey: testPrivateKeys["ecdsa"],
ConfirmBeforeUse: true,
LifetimeSecs: 3600,
PrivateKey: testPrivateKeys["ecdsa"],
LifetimeSecs: 3600,
}); err != nil {
t.Fatalf("Error adding key with constraints: %s", err)
}
+93 -4
View File
@@ -7,11 +7,13 @@ package test
import (
"bytes"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"testing"
"time"
"golang.org/x/crypto/internal/testenv"
"golang.org/x/crypto/ssh"
@@ -88,7 +90,8 @@ func TestSSHCLIAuth(t *testing.T) {
}
// test public key authentication.
cmd := testenv.Command(t, sshCLI, "-vvv", "-i", keyPrivPath, "-o", "StrictHostKeyChecking=no",
cmd := testenv.Command(t, sshCLI, "-F", "none", "-vvv", "-i", keyPrivPath,
"-o", "StrictHostKeyChecking=no", "-o", "IdentityAgent=none",
"-p", port, "testpubkey@127.0.0.1", "true")
out, err := cmd.CombinedOutput()
if err != nil {
@@ -97,7 +100,8 @@ func TestSSHCLIAuth(t *testing.T) {
// Test SSH user certificate authentication.
// The username must match one of the principals included in the certificate.
// The certificate "rsa-user-testcertificate" has "testcertificate" as principal.
cmd = testenv.Command(t, sshCLI, "-vvv", "-i", keyPrivPath, "-o", "StrictHostKeyChecking=no",
cmd = testenv.Command(t, sshCLI, "-F", "none", "-vvv", "-i", keyPrivPath,
"-o", "StrictHostKeyChecking=no", "-o", "IdentityAgent=none",
"-p", port, "testcertificate@127.0.0.1", "true")
out, err = cmd.CombinedOutput()
if err != nil {
@@ -119,7 +123,7 @@ func TestSSHCLIKeyExchanges(t *testing.T) {
keyExchanges := append(ssh.SupportedAlgorithms().KeyExchanges, ssh.InsecureAlgorithms().KeyExchanges...)
for _, kex := range keyExchanges {
t.Run(kex, func(t *testing.T) {
cmd := testenv.Command(t, sshCLI, "-Q", "kex")
cmd := testenv.Command(t, sshCLI, "-F", "none", "-Q", "kex")
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("%s failed to check if the KEX is supported, error: %v, command output %q", kex, err, string(out))
@@ -152,7 +156,8 @@ func TestSSHCLIKeyExchanges(t *testing.T) {
t.Fatalf("unable to get server port: %v", err)
}
cmd = testenv.Command(t, sshCLI, "-vvv", "-i", keyPrivPath, "-o", "StrictHostKeyChecking=no",
cmd = testenv.Command(t, sshCLI, "-F", "none", "-vvv", "-i", keyPrivPath,
"-o", "StrictHostKeyChecking=no", "-o", "IdentityAgent=none",
"-o", fmt.Sprintf("KexAlgorithms=%s", kex), "-p", port, "testpubkey@127.0.0.1", "true")
out, err = cmd.CombinedOutput()
if err != nil {
@@ -161,3 +166,87 @@ func TestSSHCLIKeyExchanges(t *testing.T) {
})
}
}
func TestSSHCLIControlClientConn(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skipf("always fails on Windows, see #64403")
}
sshCLI := sshClient(t)
keyFiles := map[string][]byte{
"rsa": testdata.PEMBytes["rsa"],
"rsa.pub": ssh.MarshalAuthorizedKey(testPublicKeys["rsa"]),
}
keyPrivPath := setupSSHCLIKeys(t, keyFiles, "rsa")
config := &ssh.ServerConfig{
PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
if conn.User() == "testcontrolproxy" && bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
return nil, nil
}
return nil, fmt.Errorf("pubkey for %q not acceptable", conn.User())
},
}
config.AddHostKey(testSigners["rsa"])
server, err := newTestServer(config)
if err != nil {
t.Fatalf("unable to start test server: %v", err)
}
defer server.Close()
port, err := server.port()
if err != nil {
t.Fatalf("unable to get server port: %v", err)
}
dir, err := os.MkdirTemp("", "controlSocket")
if err != nil {
t.Fatalf("unable to create temp dir for control socket: %v", err)
}
defer os.RemoveAll(dir)
csPath := filepath.Join(dir, "c")
cmd := testenv.Command(t, sshCLI, "-vvv", "-i", keyPrivPath, "-o", "StrictHostKeyChecking=no",
"-p", port, "-o", "ControlPath="+csPath, "-o", "ControlMaster=yes", "-N", "testcontrolproxy@127.0.0.1")
var output bytes.Buffer
cmd.Stdout = &output
cmd.Stderr = &output
if err := cmd.Start(); err != nil {
t.Fatalf("control socket master start failed, error: %v", err)
}
defer func() {
cmd.Process.Kill()
cmd.Wait()
if t.Failed() {
t.Logf("OpenSSH output:\n\n%s", cmd.Stdout)
}
}()
for i := range 10 {
if _, err := os.Stat(csPath); err == nil {
break
} else if !os.IsNotExist(err) {
t.Fatalf("unable to stat control socket: %v", err)
}
time.Sleep((1 << i) * 5 * time.Millisecond)
}
conn, err := net.Dial("unix", csPath)
if err != nil {
t.Fatalf("unable to open control socket: %v", err)
}
defer conn.Close()
cc, chans, reqs, err := ssh.NewControlClientConn(conn)
if err != nil {
t.Fatalf("unable to create client: %v", err)
}
client := ssh.NewClient(cc, chans, reqs)
defer client.Close()
session, err := client.NewSession()
if err != nil {
t.Fatalf("unable to create session: %v", err)
}
defer session.Close()
out, err := session.CombinedOutput("true")
if err != nil {
t.Fatalf("command execution failed, error: %v, command output %q", err, string(out))
}
}
Binary file not shown.
+122 -267
View File
@@ -21,853 +21,708 @@ var unparsedCertificates = []unparsedCertificate{
certStartOff: 2633,
certLength: 1471,
},
{
cn: "CN=AffirmTrust Commercial,O=AffirmTrust,C=US",
sha256Hash: "0376ab1d54c5f9803ce4b2e201a0ee7eef7b57b636e8a93c9b8d4860c96f5fa7",
certStartOff: 4104,
certLength: 848,
distrustAfter: "2024-11-30T23:59:59Z",
},
{
cn: "CN=AffirmTrust Networking,O=AffirmTrust,C=US",
sha256Hash: "0a81ec5a929777f145904af38d5d509f66b5e2c58fcdb531058b0e17f3f0b41b",
certStartOff: 4952,
certLength: 848,
distrustAfter: "2024-11-30T23:59:59Z",
},
{
cn: "CN=AffirmTrust Premium ECC,O=AffirmTrust,C=US",
sha256Hash: "bd71fdf6da97e4cf62d1647add2581b07d79adf8397eb4ecba9c5e8488821423",
certStartOff: 5800,
certLength: 514,
distrustAfter: "2024-11-30T23:59:59Z",
},
{
cn: "CN=AffirmTrust Premium,O=AffirmTrust,C=US",
sha256Hash: "70a73f7f376b60074248904534b11482d5bf0e698ecc498df52577ebf2e93b9a",
certStartOff: 6314,
certLength: 1354,
distrustAfter: "2024-11-30T23:59:59Z",
},
{
cn: "CN=Amazon Root CA 1,O=Amazon,C=US",
sha256Hash: "8ecde6884f3d87b1125ba31ac3fcb13d7016de7f57cc904fe1cb97c6ae98196e",
certStartOff: 7668,
certStartOff: 4104,
certLength: 837,
},
{
cn: "CN=Amazon Root CA 2,O=Amazon,C=US",
sha256Hash: "1ba5b2aa8c65401a82960118f80bec4f62304d83cec4713a19c39c011ea46db4",
certStartOff: 8505,
certStartOff: 4941,
certLength: 1349,
},
{
cn: "CN=Amazon Root CA 3,O=Amazon,C=US",
sha256Hash: "18ce6cfe7bf14e60b2e347b8dfe868cb31d02ebb3ada271569f50343b46db3a4",
certStartOff: 9854,
certStartOff: 6290,
certLength: 442,
},
{
cn: "CN=Amazon Root CA 4,O=Amazon,C=US",
sha256Hash: "e35d28419ed02025cfa69038cd623962458da5c695fbdea3c22b0bfb25897092",
certStartOff: 10296,
certStartOff: 6732,
certLength: 502,
},
{
cn: "CN=Atos TrustedRoot 2011,O=Atos,C=DE",
sha256Hash: "f356bea244b7a91eb35d53ca9ad7864ace018e2d35d5f8f96ddf68a6f41aa474",
certStartOff: 10798,
certStartOff: 7234,
certLength: 891,
},
{
cn: "CN=Atos TrustedRoot Root CA ECC TLS 2021,O=Atos,C=DE",
sha256Hash: "b2fae53e14ccd7ab9212064701ae279c1d8988facb775fa8a008914e663988a8",
certStartOff: 11689,
certStartOff: 8125,
certLength: 537,
},
{
cn: "CN=Atos TrustedRoot Root CA RSA TLS 2021,O=Atos,C=DE",
sha256Hash: "81a9088ea59fb364c548a6f85559099b6f0405efbf18e5324ec9f457ba00112f",
certStartOff: 12226,
certStartOff: 8662,
certLength: 1384,
},
{
cn: "CN=Autoridad de Certificacion Firmaprofesional CIF A62634068,C=ES",
sha256Hash: "57de0583efd2b26e0361da99da9df4648def7ee8441c3b728afa9bcde0f9b26a",
certStartOff: 13610,
certStartOff: 10046,
certLength: 1560,
},
{
cn: "CN=BJCA Global Root CA1,O=BEIJING CERTIFICATE AUTHORITY,C=CN",
sha256Hash: "f3896f88fe7c0a882766a7fa6ad2749fb57a7f3e98fb769c1fa7b09c2c44d5ae",
certStartOff: 15170,
certStartOff: 11606,
certLength: 1400,
},
{
cn: "CN=BJCA Global Root CA2,O=BEIJING CERTIFICATE AUTHORITY,C=CN",
sha256Hash: "574df6931e278039667b720afdc1600fc27eb66dd3092979fb73856487212882",
certStartOff: 16570,
certStartOff: 13006,
certLength: 553,
},
{
cn: "CN=Buypass Class 2 Root CA,O=Buypass AS-983163327,C=NO",
sha256Hash: "9a114025197c5bb95d94e63d55cd43790847b646b23cdf11ada4a00eff15fb48",
certStartOff: 17123,
certStartOff: 13559,
certLength: 1373,
},
{
cn: "CN=Buypass Class 3 Root CA,O=Buypass AS-983163327,C=NO",
sha256Hash: "edf7ebbca27a2a384d387b7d4010c666e2edb4843e4c29b4ae1d5b9332e6b24d",
certStartOff: 18496,
certStartOff: 14932,
certLength: 1373,
},
{
cn: "CN=CA Disig Root R2,O=Disig a.s.,L=Bratislava,C=SK",
sha256Hash: "e23d4a036d7b70e9f595b1422079d2b91edfbb1fb651a0633eaa8a9dc5f80703",
certStartOff: 19869,
certStartOff: 16305,
certLength: 1389,
},
{
cn: "CN=CFCA EV ROOT,O=China Financial Certification Authority,C=CN",
sha256Hash: "5cc3d78e4e1d5e45547a04e6873e64f90cf9536d1ccc2ef800f355c4c5fd70fd",
certStartOff: 21258,
certStartOff: 17694,
certLength: 1425,
},
{
cn: "CN=COMODO Certification Authority,O=COMODO CA Limited,L=Salford,ST=Greater Manchester,C=GB",
sha256Hash: "0c2cd63df7806fa399ede809116b575bf87989f06518f9808c860503178baf66",
certStartOff: 22683,
certLength: 1057,
},
{
cn: "CN=COMODO ECC Certification Authority,O=COMODO CA Limited,L=Salford,ST=Greater Manchester,C=GB",
sha256Hash: "1793927a0614549789adce2f8f34f7f0b66d0f3ae3a3b84d21ec15dbba4fadc7",
certStartOff: 23740,
certStartOff: 19119,
certLength: 653,
},
{
cn: "CN=COMODO RSA Certification Authority,O=COMODO CA Limited,L=Salford,ST=Greater Manchester,C=GB",
sha256Hash: "52f0e1c4e58ec629291b60317f074671b85d7ea80d5b07273463534b32b40234",
certStartOff: 24393,
certStartOff: 19772,
certLength: 1500,
},
{
cn: "CN=Certainly Root E1,O=Certainly,C=US",
sha256Hash: "b4585f22e4ac756a4e8612a1361c5d9d031a93fd84febb778fa3068b0fc42dc2",
certStartOff: 25893,
certStartOff: 21272,
certLength: 507,
},
{
cn: "CN=Certainly Root R1,O=Certainly,C=US",
sha256Hash: "77b82cd8644c4305f7acc5cb156b45675004033d51c60c6202a8e0c33467d3a0",
certStartOff: 26400,
certStartOff: 21779,
certLength: 1355,
},
{
cn: "CN=Certigna Root CA,OU=0002 48146308100036,O=Dhimyotis,C=FR",
sha256Hash: "d48d3d23eedb50a459e55197601c27774b9d7b18c94d5a059511a10250b93168",
certStartOff: 27755,
certStartOff: 23134,
certLength: 1631,
},
{
cn: "CN=Certigna,O=Dhimyotis,C=FR",
sha256Hash: "e3b6a2db2ed7ce48842f7ac53241c7b71d54144bfb40c11f3f1d0b42f5eea12d",
certStartOff: 29386,
certLength: 940,
},
{
cn: "CN=Certum EC-384 CA,OU=Certum Certification Authority,O=Asseco Data Systems S.A.,C=PL",
sha256Hash: "6b328085625318aa50d173c98d8bda09d57e27413d114cf787a0f5d06c030cf6",
certStartOff: 30326,
certStartOff: 24765,
certLength: 617,
},
{
cn: "CN=Certum Trusted Network CA 2,OU=Certum Certification Authority,O=Unizeto Technologies S.A.,C=PL",
sha256Hash: "b676f2eddae8775cd36cb0f63cd1d4603961f49e6265ba013a2f0307b6d0b804",
certStartOff: 30943,
certStartOff: 25382,
certLength: 1494,
},
{
cn: "CN=Certum Trusted Network CA,OU=Certum Certification Authority,O=Unizeto Technologies S.A.,C=PL",
sha256Hash: "5c58468d55f58e497e743982d2b50010b6d165374acf83a7d4a32db768c4408e",
certStartOff: 32437,
certStartOff: 26876,
certLength: 959,
},
{
cn: "CN=Certum Trusted Root CA,OU=Certum Certification Authority,O=Asseco Data Systems S.A.,C=PL",
sha256Hash: "fe7696573855773e37a95e7ad4d9cc96c30157c15d31765ba9b15704e1ae78fd",
certStartOff: 33396,
certStartOff: 27835,
certLength: 1476,
},
{
cn: "CN=D-TRUST BR Root CA 1 2020,O=D-Trust GmbH,C=DE",
sha256Hash: "e59aaa816009c22bff5b25bad37df306f049797c1f81d85ab089e657bd8f0044",
certStartOff: 34872,
certStartOff: 29311,
certLength: 735,
},
{
cn: "CN=D-TRUST BR Root CA 2 2023,O=D-Trust GmbH,C=DE",
sha256Hash: "0552e6f83fdf65e8fa9670e666df28a4e21340b510cbe52566f97c4fb94b2bd1",
certStartOff: 35607,
certStartOff: 30046,
certLength: 1453,
},
{
cn: "CN=D-TRUST EV Root CA 1 2020,O=D-Trust GmbH,C=DE",
sha256Hash: "08170d1aa36453901a2f959245e347db0c8d37abaabc56b81aa100dc958970db",
certStartOff: 37060,
certStartOff: 31499,
certLength: 735,
},
{
cn: "CN=D-TRUST EV Root CA 2 2023,O=D-Trust GmbH,C=DE",
sha256Hash: "8e8221b2e7d4007836a1672f0dcc299c33bc07d316f132fa1a206d587150f1ce",
certStartOff: 37795,
certStartOff: 32234,
certLength: 1453,
},
{
cn: "CN=D-TRUST Root Class 3 CA 2 2009,O=D-Trust GmbH,C=DE",
sha256Hash: "49e7a442acf0ea6287050054b52564b650e4f49e42e348d6aa38e039e957b1c1",
certStartOff: 39248,
certStartOff: 33687,
certLength: 1079,
},
{
cn: "CN=D-TRUST Root Class 3 CA 2 EV 2009,O=D-Trust GmbH,C=DE",
sha256Hash: "eec5496b988ce98625b934092eec2908bed0b0f316c2d4730c84eaf1f3d34881",
certStartOff: 40327,
certStartOff: 34766,
certLength: 1095,
},
{
cn: "CN=DigiCert Assured ID Root CA,OU=www.digicert.com,O=DigiCert Inc,C=US",
sha256Hash: "3e9099b5015e8f486c00bcea9d111ee721faba355a89bcf1df69561e3dc6325c",
certStartOff: 41422,
certLength: 955,
},
{
cn: "CN=DigiCert Assured ID Root G2,OU=www.digicert.com,O=DigiCert Inc,C=US",
sha256Hash: "7d05ebb682339f8c9451ee094eebfefa7953a114edb2f44949452fab7d2fc185",
certStartOff: 42377,
certStartOff: 35861,
certLength: 922,
},
{
cn: "CN=DigiCert Assured ID Root G3,OU=www.digicert.com,O=DigiCert Inc,C=US",
sha256Hash: "7e37cb8b4c47090cab36551ba6f45db840680fba166a952db100717f43053fc2",
certStartOff: 43299,
certStartOff: 36783,
certLength: 586,
},
{
cn: "CN=DigiCert Global Root CA,OU=www.digicert.com,O=DigiCert Inc,C=US",
sha256Hash: "4348a0e9444c78cb265e058d5e8944b4d84f9662bd26db257f8934a443c70161",
certStartOff: 43885,
certLength: 947,
},
{
cn: "CN=DigiCert Global Root G2,OU=www.digicert.com,O=DigiCert Inc,C=US",
sha256Hash: "cb3ccbb76031e5e0138f8dd39a23f9de47ffc35e43c1144cea27d46a5ab1cb5f",
certStartOff: 44832,
certStartOff: 37369,
certLength: 914,
},
{
cn: "CN=DigiCert Global Root G3,OU=www.digicert.com,O=DigiCert Inc,C=US",
sha256Hash: "31ad6648f8104138c738f39ea4320133393e3a18cc02296ef97c2ac9ef6731d0",
certStartOff: 45746,
certStartOff: 38283,
certLength: 579,
},
{
cn: "CN=DigiCert High Assurance EV Root CA,OU=www.digicert.com,O=DigiCert Inc,C=US",
sha256Hash: "7431e5f4c3c1ce4690774f0b61e05440883ba9a01ed00ba6abd7806ed3b118cf",
certStartOff: 46325,
certLength: 969,
},
{
cn: "CN=DigiCert TLS ECC P384 Root G5,O=DigiCert\\, Inc.,C=US",
sha256Hash: "018e13f0772532cf809bd1b17281867283fc48c6e13be9c69812854a490c1b05",
certStartOff: 47294,
certStartOff: 38862,
certLength: 541,
},
{
cn: "CN=DigiCert TLS RSA4096 Root G5,O=DigiCert\\, Inc.,C=US",
sha256Hash: "371a00dc0533b3721a7eeb40e8419e70799d2b0a0f2c1d80693165f7cec4ad75",
certStartOff: 47835,
certStartOff: 39403,
certLength: 1386,
},
{
cn: "CN=DigiCert Trusted Root G4,OU=www.digicert.com,O=DigiCert Inc,C=US",
sha256Hash: "552f7bdcf1a7af9e6ce672017f4f12abf77240c78e761ac203d1d9d20ac89988",
certStartOff: 49221,
certStartOff: 40789,
certLength: 1428,
},
{
cn: "CN=Entrust Root Certification Authority - EC1,OU=See www.entrust.net/legal-terms+OU=(c) 2012 Entrust\\, Inc. - for authorized use only,O=Entrust\\, Inc.,C=US",
sha256Hash: "02ed0eb28c14da45165c566791700d6451d7fb56f0b2ab1d3b8eb070e56edff5",
certStartOff: 50649,
certLength: 765,
distrustAfter: "2024-11-30T23:59:59Z",
},
{
cn: "CN=Entrust Root Certification Authority - G2,OU=See www.entrust.net/legal-terms+OU=(c) 2009 Entrust\\, Inc. - for authorized use only,O=Entrust\\, Inc.,C=US",
sha256Hash: "43df5774b03e7fef5fe40d931a7bedf1bb2e6b42738c4e6d3841103d3aa7f339",
certStartOff: 51414,
certLength: 1090,
distrustAfter: "2024-11-30T23:59:59Z",
},
{
cn: "CN=Entrust Root Certification Authority,OU=www.entrust.net/CPS is incorporated by reference+OU=(c) 2006 Entrust\\, Inc.,O=Entrust\\, Inc.,C=US",
sha256Hash: "73c176434f1bc6d5adf45b0e76e727287c8de57616c1e6e6141a2b2cbc7d8e4c",
certStartOff: 52504,
certStartOff: 42217,
certLength: 1173,
distrustAfter: "2024-11-30T23:59:59Z",
},
{
cn: "CN=FIRMAPROFESIONAL CA ROOT-A WEB,O=Firmaprofesional SA,C=ES,2.5.4.97=#130f56415445532d413632363334303638",
sha256Hash: "bef256daf26e9c69bdec1602359798f3caf71821a03e018257c53c65617f3d4a",
certStartOff: 53677,
certLength: 638,
},
{
cn: "CN=GDCA TrustAUTH R5 ROOT,O=GUANG DONG CERTIFICATE AUTHORITY CO.\\,LTD.,C=CN",
sha256Hash: "bfff8fd04433487d6a8aa60c1a29767a9fc2bbb05e420f713a13b992891d3893",
certStartOff: 54315,
certStartOff: 43390,
certLength: 1420,
},
{
cn: "CN=GLOBALTRUST 2020,O=e-commerce monitoring GmbH,C=AT",
sha256Hash: "9a296a5182d1d451a2e37f439b74daafa267523329f90f9a0d2007c334e23c9a",
certStartOff: 55735,
certLength: 1414,
distrustAfter: "2024-06-30T00:00:00Z",
},
{
cn: "CN=GTS Root R1,O=Google Trust Services LLC,C=US",
sha256Hash: "d947432abde7b7fa90fc2e6b59101b1280e0e1c7e4e40fa3c6887fff57a7f4cf",
certStartOff: 57149,
certLength: 1371,
},
{
cn: "CN=GTS Root R2,O=Google Trust Services LLC,C=US",
sha256Hash: "8d25cd97229dbf70356bda4eb3cc734031e24cf00fafcfd32dc76eb5841c7ea8",
certStartOff: 58520,
certStartOff: 44810,
certLength: 1371,
},
{
cn: "CN=GTS Root R3,O=Google Trust Services LLC,C=US",
sha256Hash: "34d8a73ee208d9bcdb0d956520934b4e40e69482596e8b6f73c8426b010a6f48",
certStartOff: 59891,
certStartOff: 46181,
certLength: 525,
},
{
cn: "CN=GTS Root R4,O=Google Trust Services LLC,C=US",
sha256Hash: "349dfa4058c5e263123b398ae795573c4e1313c83fe68f93556cd5e8031b3c7d",
certStartOff: 60416,
certStartOff: 46706,
certLength: 525,
},
{
cn: "CN=GlobalSign Root E46,O=GlobalSign nv-sa,C=BE",
sha256Hash: "cbb9c44d84b8043e1050ea31a69f514955d7bfd2e2c6b49301019ad61d9f5058",
certStartOff: 60941,
certStartOff: 47231,
certLength: 527,
},
{
cn: "CN=GlobalSign Root R46,O=GlobalSign nv-sa,C=BE",
sha256Hash: "4fa3126d8d3a11d1c4855a4f807cbad6cf919d3a5a88b03bea2c6372d93c40c9",
certStartOff: 61468,
certStartOff: 47758,
certLength: 1374,
},
{
cn: "CN=GlobalSign,OU=GlobalSign ECC Root CA - R4,O=GlobalSign",
sha256Hash: "b085d70b964f191a73e4af0d54ae7a0e07aafdaf9b71dd0862138ab7325a24a2",
certStartOff: 62842,
certStartOff: 49132,
certLength: 480,
},
{
cn: "CN=GlobalSign,OU=GlobalSign ECC Root CA - R5,O=GlobalSign",
sha256Hash: "179fbc148a3dd00fd24ea13458cc43bfa7f59c8182d783a513f6ebec100c8924",
certStartOff: 63322,
certStartOff: 49612,
certLength: 546,
},
{
cn: "CN=GlobalSign,OU=GlobalSign Root CA - R3,O=GlobalSign",
sha256Hash: "cbb522d7b7f127ad6a0113865bdf1cd4102e7d0759af635a7cf4720dc963c53b",
certStartOff: 63868,
certStartOff: 50158,
certLength: 867,
},
{
cn: "CN=GlobalSign,OU=GlobalSign Root CA - R6,O=GlobalSign",
sha256Hash: "2cabeafe37d06ca22aba7391c0033d25982952c453647349763a3ab5ad6ccf69",
certStartOff: 64735,
certStartOff: 51025,
certLength: 1415,
},
{
cn: "CN=Go Daddy Root Certificate Authority - G2,O=GoDaddy.com\\, Inc.,L=Scottsdale,ST=Arizona,C=US",
sha256Hash: "45140b3247eb9cc8c5b4f0d7b53091f73292089e6e5a63e2749dd3aca9198eda",
certStartOff: 66150,
certStartOff: 52440,
certLength: 969,
},
{
cn: "CN=HARICA TLS ECC Root CA 2021,O=Hellenic Academic and Research Institutions CA,C=GR",
sha256Hash: "3f99cc474acfce4dfed58794665e478d1547739f2e780f1bb4ca9b133097d401",
certStartOff: 67119,
certStartOff: 53409,
certLength: 600,
},
{
cn: "CN=HARICA TLS RSA Root CA 2021,O=Hellenic Academic and Research Institutions CA,C=GR",
sha256Hash: "d95d0e8eda79525bf9beb11b14d2100d3294985f0c62d9fabd9cd999eccb7b1d",
certStartOff: 67719,
certStartOff: 54009,
certLength: 1448,
},
{
cn: "CN=Hellenic Academic and Research Institutions ECC RootCA 2015,O=Hellenic Academic and Research Institutions Cert. Authority,L=Athens,C=GR",
sha256Hash: "44b545aa8a25e65a73ca15dc27fc36d24c1cb9953a066539b11582dc487b4833",
certStartOff: 69167,
certStartOff: 55457,
certLength: 711,
},
{
cn: "CN=Hellenic Academic and Research Institutions RootCA 2015,O=Hellenic Academic and Research Institutions Cert. Authority,L=Athens,C=GR",
sha256Hash: "a040929a02ce53b4acf4f2ffc6981ce4496f755e6d45fe0b2a692bcd52523f36",
certStartOff: 69878,
certStartOff: 56168,
certLength: 1551,
},
{
cn: "CN=HiPKI Root CA - G1,O=Chunghwa Telecom Co.\\, Ltd.,C=TW",
sha256Hash: "f015ce3cc239bfef064be9f1d2c417e1a0264a0a94be1f0c8d121864eb6949cc",
certStartOff: 71429,
certStartOff: 57719,
certLength: 1390,
},
{
cn: "CN=Hongkong Post Root CA 3,O=Hongkong Post,L=Hong Kong,ST=Hong Kong,C=HK",
sha256Hash: "5a2fc03f0c83b090bbfa40604b0988446c7636183df9846e17101a447fb8efd6",
certStartOff: 72819,
certStartOff: 59109,
certLength: 1491,
},
{
cn: "CN=ISRG Root X1,O=Internet Security Research Group,C=US",
sha256Hash: "96bcec06264976f37460779acf28c5a7cfe8a3c0aae11a8ffcee05c0bddf08c6",
certStartOff: 74310,
certStartOff: 60600,
certLength: 1391,
},
{
cn: "CN=ISRG Root X2,O=Internet Security Research Group,C=US",
sha256Hash: "69729b8e15a86efc177a57afb7171dfc64add28c2fca8cf1507e34453ccb1470",
certStartOff: 75701,
certStartOff: 61991,
certLength: 543,
},
{
cn: "CN=IdenTrust Commercial Root CA 1,O=IdenTrust,C=US",
sha256Hash: "5d56499be4d2e08bcfcad08a3e38723d50503bde706948e42f55603019e528ae",
certStartOff: 76244,
certStartOff: 62534,
certLength: 1380,
},
{
cn: "CN=IdenTrust Public Sector Root CA 1,O=IdenTrust,C=US",
sha256Hash: "30d0895a9a448a262091635522d1f52010b5867acae12c78ef958fd4f4389f2f",
certStartOff: 77624,
certStartOff: 63914,
certLength: 1386,
},
{
cn: "CN=Izenpe.com,O=IZENPE S.A.,C=ES",
sha256Hash: "2530cc8e98321502bad96f9b1fba1b099e2d299e0f4548bb914f363bc0d4531f",
certStartOff: 79010,
certStartOff: 65300,
certLength: 1525,
},
{
cn: "CN=Microsec e-Szigno Root CA 2009,O=Microsec Ltd.,L=Budapest,C=HU,1.2.840.113549.1.9.1=#0c10696e666f40652d737a69676e6f2e6875",
sha256Hash: "3c5f81fea5fab82c64bfa2eaecafcde8e077fc8620a7cae537163df36edbf378",
certStartOff: 80535,
certStartOff: 66825,
certLength: 1038,
},
{
cn: "CN=Microsoft ECC Root Certificate Authority 2017,O=Microsoft Corporation,C=US",
sha256Hash: "358df39d764af9e1b766e9c972df352ee15cfac227af6ad1d70e8e4a6edcba02",
certStartOff: 81573,
certStartOff: 67863,
certLength: 605,
},
{
cn: "CN=Microsoft RSA Root Certificate Authority 2017,O=Microsoft Corporation,C=US",
sha256Hash: "c741f70f4b2a8d88bf2e71c14122ef53ef10eba0cfa5e64cfa20f418853073e0",
certStartOff: 82178,
certStartOff: 68468,
certLength: 1452,
},
{
cn: "CN=NAVER Global Root Certification Authority,O=NAVER BUSINESS PLATFORM Corp.,C=KR",
sha256Hash: "88f438dcf8ffd1fa8f429115ffe5f82ae1e06e0c70c375faad717b34a49e7265",
certStartOff: 83630,
certStartOff: 69920,
certLength: 1446,
},
{
cn: "CN=NetLock Arany (Class Gold) Főtanúsítvány,OU=Tanúsítványkiadók (Certification Services),O=NetLock Kft.,L=Budapest,C=HU",
sha256Hash: "6c61dac3a2def031506be036d2a6fe401994fbd13df9c8d466599274c446ec98",
certStartOff: 85076,
certStartOff: 71366,
certLength: 1049,
},
{
cn: "CN=OISTE Server Root ECC G1,O=OISTE Foundation,C=CH",
sha256Hash: "eec997c0c30f216f7e3b8b307d2bae42412d753fc8219dafd1520b2572850f49",
certStartOff: 86125,
certStartOff: 72415,
certLength: 569,
},
{
cn: "CN=OISTE Server Root RSA G1,O=OISTE Foundation,C=CH",
sha256Hash: "9ae36232a5189ffddb353dfd26520c015395d22777dac59db57b98c089a651e6",
certStartOff: 86694,
certStartOff: 72984,
certLength: 1415,
},
{
cn: "CN=OISTE WISeKey Global Root GB CA,OU=OISTE Foundation Endorsed,O=WISeKey,C=CH",
sha256Hash: "6b9c08e86eb0f767cfad65cd98b62149e5494a67f5845e7bd1ed019f27b86bd6",
certStartOff: 88109,
certStartOff: 74399,
certLength: 953,
},
{
cn: "CN=OISTE WISeKey Global Root GC CA,OU=OISTE Foundation Endorsed,O=WISeKey,C=CH",
sha256Hash: "8560f91c3624daba9570b5fea0dbe36ff11a8323be9486854fb3f34a5571198d",
certStartOff: 89062,
certStartOff: 75352,
certLength: 621,
},
{
cn: "CN=QuoVadis Root CA 1 G3,O=QuoVadis Limited,C=BM",
sha256Hash: "8a866fd1b276b57e578e921c65828a2bed58e9f2f288054134b7f1f4bfc9cc74",
certStartOff: 89683,
certStartOff: 75973,
certLength: 1380,
},
{
cn: "CN=QuoVadis Root CA 2 G3,O=QuoVadis Limited,C=BM",
sha256Hash: "8fe4fb0af93a4d0d67db0bebb23e37c71bf325dcbcdd240ea04daf58b47e1840",
certStartOff: 91063,
certStartOff: 77353,
certLength: 1380,
},
{
cn: "CN=QuoVadis Root CA 2,O=QuoVadis Limited,C=BM",
sha256Hash: "85a0dd7dd720adb7ff05f83d542b209dc7ff4528f7d677b18389fea5e5c49e86",
certStartOff: 92443,
certLength: 1467,
},
{
cn: "CN=QuoVadis Root CA 3 G3,O=QuoVadis Limited,C=BM",
sha256Hash: "88ef81de202eb018452e43f864725cea5fbd1fc2d9d205730709c5d8b8690f46",
certStartOff: 93910,
certStartOff: 78733,
certLength: 1380,
},
{
cn: "CN=QuoVadis Root CA 3,O=QuoVadis Limited,C=BM",
sha256Hash: "18f1fc7f205df8adddeb7fe007dd57e3af375a9c4d8d73546bf4f1fed1e18d35",
certStartOff: 95290,
certLength: 1697,
},
{
cn: "CN=SSL.com EV Root Certification Authority ECC,O=SSL Corporation,L=Houston,ST=Texas,C=US",
sha256Hash: "22a2c1f7bded704cc1e701b5f408c310880fe956b5de2a4a44f99c873a25a7c8",
certStartOff: 96987,
certStartOff: 80113,
certLength: 664,
},
{
cn: "CN=SSL.com EV Root Certification Authority RSA R2,O=SSL Corporation,L=Houston,ST=Texas,C=US",
sha256Hash: "2e7bf16cc22485a7bbe2aa8696750761b0ae39be3b2fe9d0cc6d4ef73491425c",
certStartOff: 97651,
certStartOff: 80777,
certLength: 1519,
},
{
cn: "CN=SSL.com Root Certification Authority ECC,O=SSL Corporation,L=Houston,ST=Texas,C=US",
sha256Hash: "3417bb06cc6007da1b961c920b8ab4ce3fad820e4aa30b9acbc4a74ebdcebc65",
certStartOff: 99170,
certStartOff: 82296,
certLength: 657,
},
{
cn: "CN=SSL.com Root Certification Authority RSA,O=SSL Corporation,L=Houston,ST=Texas,C=US",
sha256Hash: "85666a562ee0be5ce925c1d8890a6f76a87ec16d4d7d5f29ea7419cf20123b69",
certStartOff: 99827,
certStartOff: 82953,
certLength: 1505,
},
{
cn: "CN=SSL.com TLS ECC Root CA 2022,O=SSL Corporation,C=US",
sha256Hash: "c32ffd9f46f936d16c3673990959434b9ad60aafbb9e7cf33654f144cc1ba143",
certStartOff: 101332,
certStartOff: 84458,
certLength: 574,
},
{
cn: "CN=SSL.com TLS RSA Root CA 2022,O=SSL Corporation,C=US",
sha256Hash: "8faf7d2e2cb4709bb8e0b33666bf75a5dd45b5de480f8ea8d4bfe6bebc17f2ed",
certStartOff: 101906,
certStartOff: 85032,
certLength: 1421,
},
{
cn: "CN=SZAFIR ROOT CA2,O=Krajowa Izba Rozliczeniowa S.A.,C=PL",
sha256Hash: "a1339d33281a0b56e557d3d32b1ce7f9367eb094bd5fa72a7e5004c8ded7cafe",
certStartOff: 103327,
certStartOff: 86453,
certLength: 886,
},
{
cn: "CN=Sectigo Public Server Authentication Root E46,O=Sectigo Limited,C=GB",
sha256Hash: "c90f26f0fb1b4018b22227519b5ca2b53e2ca5b3be5cf18efe1bef47380c5383",
certStartOff: 104213,
certStartOff: 87339,
certLength: 574,
},
{
cn: "CN=Sectigo Public Server Authentication Root R46,O=Sectigo Limited,C=GB",
sha256Hash: "7bb647a62aeeac88bf257aa522d01ffea395e0ab45c73f93f65654ec38f25a06",
certStartOff: 104787,
certStartOff: 87913,
certLength: 1422,
},
{
cn: "CN=Secure Global CA,O=SecureTrust Corporation,C=US",
sha256Hash: "4200f5043ac8590ebb527d209ed1503029fbcbd41ca1b506ec27f15ade7dac69",
certStartOff: 106209,
certLength: 960,
},
{
cn: "CN=SecureSign Root CA12,O=Cybertrust Japan Co.\\, Ltd.,C=JP",
sha256Hash: "3f034bb5704d44b2d08545a02057de93ebf3905fce721acbc730c06ddaee904e",
certStartOff: 107169,
certStartOff: 89335,
certLength: 886,
},
{
cn: "CN=SecureSign Root CA14,O=Cybertrust Japan Co.\\, Ltd.,C=JP",
sha256Hash: "4b009c1034494f9ab56bba3ba1d62731fc4d20d8955adcec10a925607261e338",
certStartOff: 108055,
certStartOff: 90221,
certLength: 1398,
},
{
cn: "CN=SecureSign Root CA15,O=Cybertrust Japan Co.\\, Ltd.,C=JP",
sha256Hash: "e778f0f095fe843729cd1a0082179e5314a9c291442805e1fb1d8fb6b8886c3a",
certStartOff: 109453,
certStartOff: 91619,
certLength: 551,
},
{
cn: "CN=SecureTrust CA,O=SecureTrust Corporation,C=US",
sha256Hash: "f1c1b50ae5a20dd8030ec9f6bc24823dd367b5255759b4e71b61fce9f7375d73",
certStartOff: 110004,
certLength: 956,
},
{
cn: "CN=Security Communication ECC RootCA1,O=SECOM Trust Systems CO.\\,LTD.,C=JP",
sha256Hash: "e74fbda55bd564c473a36b441aa799c8a68e077440e8288b9fa1e50e4bbaca11",
certStartOff: 110960,
certStartOff: 92170,
certLength: 572,
},
{
cn: "CN=Starfield Root Certificate Authority - G2,O=Starfield Technologies\\, Inc.,L=Scottsdale,ST=Arizona,C=US",
sha256Hash: "2ce1cb0bf9d2f9e102993fbe215152c3b2dd0cabde1c68e5319b839154dbb7f5",
certStartOff: 111532,
certStartOff: 92742,
certLength: 993,
},
{
cn: "CN=Starfield Services Root Certificate Authority - G2,O=Starfield Technologies\\, Inc.,L=Scottsdale,ST=Arizona,C=US",
sha256Hash: "568d6905a2c88708a4b3025190edcfedb1974a606a13c6e5290fcb2ae63edab5",
certStartOff: 112525,
certStartOff: 93735,
certLength: 1011,
},
{
cn: "CN=SwissSign Gold CA - G2,O=SwissSign AG,C=CH",
sha256Hash: "62dd0be9b9f50a163ea0f8e75c053b1eca57ea55c8688f647c6881f2c8357b95",
certStartOff: 113536,
certLength: 1470,
},
{
cn: "CN=SwissSign RSA TLS Root CA 2022 - 1,O=SwissSign AG,C=CH",
sha256Hash: "193144f431e0fddb740717d4de926a571133884b4360d30e272913cbe660ce41",
certStartOff: 115006,
certStartOff: 94746,
certLength: 1431,
},
{
cn: "CN=T-TeleSec GlobalRoot Class 2,OU=T-Systems Trust Center,O=T-Systems Enterprise Services GmbH,C=DE",
sha256Hash: "91e2f5788d5810eba7ba58737de1548a8ecacd014598bc0b143e041b17052552",
certStartOff: 116437,
certStartOff: 96177,
certLength: 967,
},
{
cn: "CN=T-TeleSec GlobalRoot Class 3,OU=T-Systems Trust Center,O=T-Systems Enterprise Services GmbH,C=DE",
sha256Hash: "fd73dad31c644ff1b43bef0ccdda96710b9cd9875eca7e31707af3e96d522bbd",
certStartOff: 117404,
certStartOff: 97144,
certLength: 967,
},
{
cn: "CN=TWCA CYBER Root CA,OU=Root CA,O=TAIWAN-CA,C=TW",
sha256Hash: "3f63bb2814be174ec8b6439cf08d6d56f0b7c405883a5648a334424d6b3ec558",
certStartOff: 118371,
certStartOff: 98111,
certLength: 1425,
},
{
cn: "CN=TWCA Global Root CA,OU=Root CA,O=TAIWAN-CA,C=TW",
sha256Hash: "59769007f7685d0fcd50872f9f95d5755a5b2b457d81f3692b610a98672f0e1b",
certStartOff: 119796,
certStartOff: 99536,
certLength: 1349,
},
{
cn: "CN=TWCA Root Certification Authority,OU=Root CA,O=TAIWAN-CA,C=TW",
sha256Hash: "bfd88fe1101c41ae3e801bf8be56350ee9bad1a6b9bd515edc5c6d5b8711ac44",
certStartOff: 121145,
certStartOff: 100885,
certLength: 895,
},
{
cn: "CN=Telekom Security TLS ECC Root 2020,O=Deutsche Telekom Security GmbH,C=DE",
sha256Hash: "578af4ded0853f4e5998db4aeaf9cbea8d945f60b620a38d1a3c13b2bc7ba8e1",
certStartOff: 122040,
certStartOff: 101780,
certLength: 582,
},
{
cn: "CN=Telekom Security TLS RSA Root 2023,O=Deutsche Telekom Security GmbH,C=DE",
sha256Hash: "efc65cadbb59adb6efe84da22311b35624b71b3b1ea0da8b6655174ec8978646",
certStartOff: 122622,
certStartOff: 102362,
certLength: 1463,
},
{
cn: "CN=Telia Root CA v2,O=Telia Finland Oyj,C=FI",
sha256Hash: "242b69742fcb1e5b2abf98898b94572187544e5b4d9911786573621f6a74b82c",
certStartOff: 124085,
certStartOff: 103825,
certLength: 1400,
},
{
cn: "CN=TeliaSonera Root CA v1,O=TeliaSonera",
sha256Hash: "dd6936fe21f8f077c123a1a521c12224f72255b73e03a7260693e8a24b0fa389",
certStartOff: 125485,
certLength: 1340,
},
{
cn: "CN=TrustAsia Global Root CA G3,O=TrustAsia Technologies\\, Inc.,C=CN",
sha256Hash: "e0d3226aeb1163c2e48ff9be3b50b4c6431be7bb1eacc5c36b5d5ec509039a08",
certStartOff: 126825,
certStartOff: 105225,
certLength: 1449,
},
{
cn: "CN=TrustAsia Global Root CA G4,O=TrustAsia Technologies\\, Inc.,C=CN",
sha256Hash: "be4b56cb5056c0136a526df444508daa36a0b54f42e4ac38f72af470e479654c",
certStartOff: 128274,
certStartOff: 106674,
certLength: 601,
},
{
cn: "CN=TrustAsia TLS ECC Root CA,O=TrustAsia Technologies\\, Inc.,C=CN",
sha256Hash: "c0076b9ef0531fb1a656d67c4ebe97cd5dbaa41ef44598acc2489878c92d8711",
certStartOff: 128875,
certStartOff: 107275,
certLength: 565,
},
{
cn: "CN=TrustAsia TLS RSA Root CA,O=TrustAsia Technologies\\, Inc.,C=CN",
sha256Hash: "06c08d7dafd876971eb1124fe67f847ec0c7a158d3ea53cbe940e2ea9791f4c3",
certStartOff: 129440,
certStartOff: 107840,
certLength: 1412,
},
{
cn: "CN=Trustwave Global Certification Authority,O=Trustwave Holdings\\, Inc.,L=Chicago,ST=Illinois,C=US",
sha256Hash: "97552015f5ddfc3c8788c006944555408894450084f100867086bc1a2bb58dc8",
certStartOff: 130852,
certLength: 1502,
},
{
cn: "CN=Trustwave Global ECC P256 Certification Authority,O=Trustwave Holdings\\, Inc.,L=Chicago,ST=Illinois,C=US",
sha256Hash: "945bbc825ea554f489d1fd51a73ddf2ea624ac7019a05205225c22a78ccfa8b4",
certStartOff: 132354,
certLength: 612,
},
{
cn: "CN=Trustwave Global ECC P384 Certification Authority,O=Trustwave Holdings\\, Inc.,L=Chicago,ST=Illinois,C=US",
sha256Hash: "55903859c8c0c3ebb8759ece4e2557225ff5758bbd38ebd48276601e1bd58097",
certStartOff: 132966,
certLength: 673,
},
{
cn: "CN=TunTrust Root CA,O=Agence Nationale de Certification Electronique,C=TN",
sha256Hash: "2e44102ab58cb85419451c8e19d9acf3662cafbc614b6a53960a30f7d0e2eb41",
certStartOff: 133639,
certStartOff: 109252,
certLength: 1463,
},
{
cn: "CN=UCA Extended Validation Root,O=UniTrust,C=CN",
sha256Hash: "d43af9b35473755c9684fc06d7d8cb70ee5c28e773fb294eb41ee71722924d24",
certStartOff: 135102,
certStartOff: 110715,
certLength: 1374,
},
{
cn: "CN=UCA Global G2 Root,O=UniTrust,C=CN",
sha256Hash: "9bea11c976fe014764c1be56a6f914b5a560317abd9988393382e5161aa0493c",
certStartOff: 136476,
certStartOff: 112089,
certLength: 1354,
},
{
cn: "CN=USERTrust ECC Certification Authority,O=The USERTRUST Network,L=Jersey City,ST=New Jersey,C=US",
sha256Hash: "4ff460d54b9c86dabfbcfc5712e0400d2bed3fbc4d4fbdaa86e06adcd2a9ad7a",
certStartOff: 137830,
certStartOff: 113443,
certLength: 659,
},
{
cn: "CN=USERTrust RSA Certification Authority,O=The USERTRUST Network,L=Jersey City,ST=New Jersey,C=US",
sha256Hash: "e793c9b02fd8aa13e21c31228accb08119643b749c898964b1746d46c3d4cbd2",
certStartOff: 138489,
certStartOff: 114102,
certLength: 1506,
},
{
cn: "CN=e-Szigno Root CA 2017,O=Microsec Ltd.,L=Budapest,C=HU,2.5.4.97=#130e56415448552d3233353834343937",
sha256Hash: "beb00b30839b9bc32c32e4447905950641f26421b15ed089198b518ae2ea1b99",
certStartOff: 139995,
certStartOff: 115608,
certLength: 580,
},
{
cn: "CN=e-Szigno TLS Root CA 2023,O=Microsec Ltd.,L=Budapest,C=HU,2.5.4.97=#130e56415448552d3233353834343937",
sha256Hash: "b49141502d00663d740f2e7ec340c52800962666121a36d09cf7dd2b90384fb4",
certStartOff: 116188,
certLength: 723,
},
{
cn: "CN=emSign ECC Root CA - C3,OU=emSign PKI,O=eMudhra Inc,C=US",
sha256Hash: "bc4d809b15189d78db3e1d8cf4f9726a795da1643ca5f1358e1ddb0edc0d7eb3",
certStartOff: 140575,
certStartOff: 116911,
certLength: 559,
},
{
cn: "CN=emSign ECC Root CA - G3,OU=emSign PKI,O=eMudhra Technologies Limited,C=IN",
sha256Hash: "86a1ecba089c4a8d3bbe2734c612ba341d813e043cf9e8a862cd5c57a36bbe6b",
certStartOff: 141134,
certStartOff: 117470,
certLength: 594,
},
{
cn: "CN=emSign Root CA - C1,OU=emSign PKI,O=eMudhra Inc,C=US",
sha256Hash: "125609aa301da0a249b97a8239cb6a34216f44dcac9f3954b14292f2e8c8608f",
certStartOff: 141728,
certStartOff: 118064,
certLength: 887,
},
{
cn: "CN=emSign Root CA - G1,OU=emSign PKI,O=eMudhra Technologies Limited,C=IN",
sha256Hash: "40f6af0346a99aa1cd1d555a4e9cce62c7f9634603ee406615833dc8c8d00367",
certStartOff: 142615,
certStartOff: 118951,
certLength: 920,
},
{
cn: "CN=vTrus ECC Root CA,O=iTrusChina Co.\\,Ltd.,C=CN",
sha256Hash: "30fbba2c32238e2a98547af97931e550428b9b3f1c8eeb6633dcfa86c5b27dd3",
certStartOff: 143535,
certStartOff: 119871,
certLength: 531,
},
{
cn: "CN=vTrus Root CA,O=iTrusChina Co.\\,Ltd.,C=CN",
sha256Hash: "8a71de6559336f426c26e53880d00d88a18da4c6a91f0dcb6194e206c5c96387",
certStartOff: 144066,
certStartOff: 120402,
certLength: 1370,
},
{
cn: "OU=AC RAIZ FNMT-RCM,O=FNMT-RCM,C=ES",
sha256Hash: "ebc5570c29018c4d67b1aa127baf12f703b4611ebc17b7dab5573894179b93fa",
certStartOff: 145436,
certStartOff: 121772,
certLength: 1415,
},
{
cn: "OU=Security Communication RootCA2,O=SECOM Trust Systems CO.\\,LTD.,C=JP",
sha256Hash: "513b2cecb810d4cde5dd85391adfc6c2dd60d87bb736d2b521484aa47a0ebef6",
certStartOff: 146851,
certStartOff: 123187,
certLength: 891,
},
{
cn: "OU=certSIGN ROOT CA G2,O=CERTSIGN SA,C=RO",
sha256Hash: "657cfe2fa73faa38462571f332a2363a46fce7020951710702cdfbb6eeda3305",
certStartOff: 147742,
certStartOff: 124078,
certLength: 1355,
},
{
cn: "OU=certSIGN ROOT CA,O=certSIGN,C=RO",
sha256Hash: "eaa962c4fa4a6bafebe415196d351ccd888d4f53f3fa8ae6d7c466a94e6042bb",
certStartOff: 149097,
certLength: 828,
},
{
cn: "OU=ePKI Root Certification Authority,O=Chunghwa Telecom Co.\\, Ltd.,C=TW",
sha256Hash: "c0a6f4dc63a24bfdcf54ef2a6a082a0a72de35803e2ff5ff527ae5d87206dfd5",
certStartOff: 149925,
certStartOff: 125433,
certLength: 1460,
distrustAfter: "2025-04-15T23:59:59Z",
},
{
cn: "SERIALNUMBER=G63287510,CN=ANF Secure Server Root CA,OU=ANF CA Raiz,O=ANF Autoridad de Certificacion,C=ES",
sha256Hash: "fb8fec759169b9106b1e511644c618c51304373f6c0643088d8beffd1b997599",
certStartOff: 151385,
certStartOff: 126893,
certLength: 1523,
},
}
+34 -1
View File
@@ -7,7 +7,9 @@ package bundle
import (
"crypto/sha256"
"crypto/x509"
"encoding/asn1"
"encoding/hex"
"regexp"
"testing"
)
@@ -19,7 +21,7 @@ func TestBundle(t *testing.T) {
continue
}
if unparsed.cn != cert.Subject.String() {
if !subjectsEqual(unparsed.cn, cert.Subject.String()) {
t.Errorf("unparsedCertificates[%v].cn = %q; want = %q", i, unparsed.cn, cert.Subject.String())
}
@@ -30,3 +32,34 @@ func TestBundle(t *testing.T) {
}
}
}
// subjectsEqual reports whether two RFC 2253 DN strings match.
//
// It tolerates the rendering difference introduced in Go 1.27, where
// string-typed attribute values for OIDs outside attributeTypeNames are
// rendered as strings rather than hex-encoded DER (see Go CL 773800).
//
// This can be removed when Go 1.25/1.26 are no longer supported.
func subjectsEqual(a, b string) bool {
return a == b || normalizeHexValues(a) == normalizeHexValues(b)
}
// normalizeHexValues rewrites any "oid=#hex" to the equivalent "oid=value"
// rendering produced by Go 1.27+.
func normalizeHexValues(s string) string {
return hexAttrRE.ReplaceAllStringFunc(s, func(match string) string {
m := hexAttrRE.FindStringSubmatch(match)
der, err := hex.DecodeString(m[2])
if err != nil {
return match
}
var v string
if rest, err := asn1.Unmarshal(der, &v); err != nil || len(rest) != 0 {
return match
}
return m[1] + "=" + v
})
}
// hexAttrRE matches a "oid=#hex" attribute value in an RFC 2253 DN string.
var hexAttrRE = regexp.MustCompile(`([\d.]+)=#([[:xdigit:]]+)`)
+1 -1
View File
@@ -1,3 +1,3 @@
module golang.org/x/crypto/x509roots/fallback
go 1.24.0
go 1.25.0