Compare commits

...
Author SHA1 Message Date
ys-ll 18e0be4596 ssh: add aes192-cbc and aes256-cbc cipher modes
Some legacy devices only offer AES-256 in CBC mode, which the package
did not implement. Register both the 192-bit and 256-bit variants of
the existing AES-CBC packet cipher so they can be enabled through a
custom Config. aes.NewCipher already handles 24- and 32-byte keys, so
both registrations reuse the existing implementation.
2026-09-22 10:35:51 +08:00
Xiaolin Zhao 7a4a4d6bea salsa20: add loong64 SIMD implementation
Benchmark results on Loongson-3C6000 @ 2.20GHz:

goos: linux
goarch: loong64
pkg: golang.org/x/crypto/salsa20
cpu: Loongson-3C6000/S @ 2200.00MHz
      |  old.bench   |              new.bench              |
      |    sec/op    |   sec/op     vs base                |
XOR1K   3835.5n ± 0%   493.9n ± 0%  -87.12% (p=0.000 n=10)

      |  old.bench   |               new.bench                |
      |     B/s      |      B/s       vs base                 |
XOR1K   254.6Mi ± 0%   1977.4Mi ± 0%  +676.64% (p=0.000 n=10)

Change-Id: I9f795e7f4e2c467ba9a41c9e6f460612536021ba
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/683255
Reviewed-by: abner chenc <chenguoqi@loongson.cn>
Reviewed-by: Cherry Mui <cherryyz@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-09-21 00:02:45 -07:00
Xiaolin Zhao 1f7c531b64 blake2b: add loong64 SIMD implementation
Benchmark results on Loongson-3C6000 @ 2.20GHz:

goos: linux
goarch: loong64
pkg: golang.org/x/crypto/blake2b
cpu: Loongson-3C6000/S @ 2200.00MHz
         |  old.bench  |              new.bench              |
         |   sec/op    |   sec/op     vs base                |
Write128   350.0n ± 0%   178.3n ± 0%  -49.06% (p=0.000 n=10)
Write1K    2.687µ ± 0%   1.286µ ± 0%  -52.14% (p=0.000 n=10)
Sum128     362.6n ± 0%   183.7n ± 0%  -49.34% (p=0.000 n=10)
Sum1K      2.788µ ± 0%   1.295µ ± 0%  -53.54% (p=0.000 n=10)
geomean    987.4n        483.3n       -51.06%

         |  old.bench   |               new.bench               |
         |     B/s      |     B/s       vs base                 |
Write128   348.8Mi ± 0%   684.8Mi ± 0%   +96.31% (p=0.000 n=10)
Write1K    363.5Mi ± 0%   759.6Mi ± 0%  +108.99% (p=0.000 n=10)
Sum128     336.6Mi ± 0%   664.4Mi ± 0%   +97.37% (p=0.000 n=10)
Sum1K      350.3Mi ± 0%   754.0Mi ± 0%  +115.23% (p=0.000 n=10)
geomean    349.7Mi        714.5Mi       +104.32%

Change-Id: I181a0284c5913cca34f074466f7d83439554e450
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/659775
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: abner chenc <chenguoqi@loongson.cn>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2026-09-19 18:40:00 -07:00
Xiaolin Zhao 234d0b5a5f chacha20: add loong64 SIMD implementation
Add an assembly implementation of ChaCha20 for Loong64 using LSX SIMD
instructions. This significantly improves performance across all message
sizes on LoongArch machines.

Benchmark results on Loongson-3C6000 @ 2.20GHz:

goos: linux
goarch: loong64
pkg: golang.org/x/crypto/chacha20
cpu: Loongson-3C6000/S @ 2200.00MHz
                 │  old.bench   │              new.bench              │
                 │    sec/op    │   sec/op     vs base                │
ChaCha20/64         188.4n ± 0%   156.9n ± 0%  -16.72% (p=0.000 n=10)
ChaCha20/256        666.4n ± 0%   151.5n ± 0%  -77.27% (p=0.000 n=10)
ChaCha20/10x25     1037.0n ± 0%   578.9n ± 0%  -44.18% (p=0.000 n=10)
ChaCha20/4096      10.207µ ± 0%   1.955µ ± 0%  -80.85% (p=0.000 n=10)
ChaCha20/100x40    11.856µ ± 0%   5.785µ ± 0%  -51.21% (p=0.000 n=10)
ChaCha20/65536     162.99µ ± 0%   31.60µ ± 0%  -80.61% (p=0.000 n=10)
ChaCha20/1000x65   165.57µ ± 0%   41.93µ ± 0%  -74.67% (p=0.000 n=10)
geomean             6.369µ        2.141µ       -66.38%

                 │  old.bench   │               new.bench                │
                 │     B/s      │      B/s       vs base                 │
ChaCha20/64        323.9Mi ± 0%    389.0Mi ± 0%   +20.10% (p=0.000 n=10)
ChaCha20/256       366.4Mi ± 0%   1611.2Mi ± 0%  +339.80% (p=0.000 n=10)
ChaCha20/10x25     229.8Mi ± 0%    411.8Mi ± 0%   +79.19% (p=0.000 n=10)
ChaCha20/4096      382.7Mi ± 0%   1998.1Mi ± 0%  +422.08% (p=0.000 n=10)
ChaCha20/100x40    321.8Mi ± 0%    659.4Mi ± 0%  +104.94% (p=0.000 n=10)
ChaCha20/65536     383.5Mi ± 0%   1977.8Mi ± 0%  +415.78% (p=0.000 n=10)
ChaCha20/1000x65   374.4Mi ± 0%   1478.4Mi ± 0%  +294.86% (p=0.000 n=10)
geomean            335.9Mi         999.2Mi       +197.50%

Change-Id: I6b8d243819d0ab1a1d6540648ed9bd00ecad5a2e
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/683196
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>
Reviewed-by: abner chenc <chenguoqi@loongson.cn>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2026-09-19 18:39:20 -07:00
XiaolinZhao a083cb74b6 argon2: add loong64 LSX implementation of blamka
Benchmark results on Loongson-3C6000 @ 2.20GHz:

goos: linux
goarch: loong64
pkg: golang.org/x/crypto/argon2
cpu: Loongson-3C6000/S @ 2200.00MHz
                                             |  old.bench   |              new.bench              |
                                             |    sec/op    |   sec/op     vs base                |
Argon2i/_Time:_3_Memory:_32_MB,_Threads:_1     123.36m ± 0%   76.67m ± 0%  -37.85% (p=0.000 n=10)
Argon2i/_Time:_4_Memory:_32_MB,_Threads:_1      163.7m ± 0%   101.3m ± 0%  -38.09% (p=0.000 n=10)
Argon2i/_Time:_5_Memory:_32_MB,_Threads:_1      195.0m ± 0%   116.5m ± 8%  -40.24% (p=0.000 n=10)
Argon2i/_Time:_3_Memory:_64_MB,_Threads:_4      259.4m ± 0%   165.3m ± 0%  -36.28% (p=0.000 n=10)
Argon2i/_Time:_4_Memory:_64_MB,_Threads:_4      349.9m ± 0%   220.8m ± 0%  -36.92% (p=0.000 n=10)
Argon2i/_Time:_5_Memory:_64_MB,_Threads:_4      437.6m ± 0%   276.0m ± 0%  -36.92% (p=0.000 n=10)
Argon2d/_Time:_3,_Memory:_32_MB,_Threads:_1    116.34m ± 0%   72.07m ± 0%  -38.06% (p=0.000 n=10)
Argon2d/_Time:_4,_Memory:_32_MB,_Threads:_1    154.42m ± 0%   95.28m ± 0%  -38.30% (p=0.000 n=10)
Argon2d/_Time:_5,_Memory:_32_MB,_Threads:_1     192.4m ± 0%   115.9m ± 2%  -39.73% (p=0.000 n=10)
Argon2d/_Time:_3,_Memory:_64_MB,_Threads:_4     254.4m ± 0%   165.2m ± 0%  -35.06% (p=0.000 n=10)
Argon2d/_Time:_4,_Memory:_64_MB,_Threads:_4     345.5m ± 1%   221.0m ± 0%  -36.04% (p=0.000 n=10)
Argon2d/_Time:_5,_Memory:_64_MB,_Threads:_4     432.1m ± 0%   276.2m ± 0%  -36.09% (p=0.000 n=10)
Argon2id/_Time:_3,_Memory:_32_MB,_Threads:_1   116.49m ± 0%   72.38m ± 0%  -37.86% (p=0.000 n=10)
Argon2id/_Time:_4,_Memory:_32_MB,_Threads:_1   154.59m ± 0%   95.71m ± 3%  -38.09% (p=0.000 n=10)
Argon2id/_Time:_5,_Memory:_32_MB,_Threads:_1    192.5m ± 0%   115.0m ± 0%  -40.25% (p=0.000 n=10)
Argon2id/_Time:_3,_Memory:_64_MB,_Threads:_4    255.6m ± 0%   165.7m ± 0%  -35.18% (p=0.000 n=10)
Argon2id/_Time:_4,_Memory:_64_MB,_Threads:_4    345.4m ± 0%   221.5m ± 0%  -35.87% (p=0.000 n=10)
Argon2id/_Time:_5,_Memory:_64_MB,_Threads:_4    431.9m ± 0%   276.6m ± 0%  -35.96% (p=0.000 n=10)
geomean                                         227.7m        142.6m       -37.40%

                                             |  old.bench   |               new.bench               |
                                             |     B/op     |     B/op      vs base                 |
Argon2i/_Time:_3_Memory:_32_MB,_Threads:_1     32.00Mi ± 0%   32.00Mi ± 0%       ~ (p=1.000 n=10) ¹
Argon2i/_Time:_4_Memory:_32_MB,_Threads:_1     32.00Mi ± 0%   32.00Mi ± 0%       ~ (p=1.000 n=10) ¹
Argon2i/_Time:_5_Memory:_32_MB,_Threads:_1     32.00Mi ± 0%   32.00Mi ± 0%       ~ (p=1.000 n=10) ¹
Argon2i/_Time:_3_Memory:_64_MB,_Threads:_4     64.01Mi ± 0%   64.01Mi ± 0%       ~ (p=1.000 n=10) ¹
Argon2i/_Time:_4_Memory:_64_MB,_Threads:_4     64.01Mi ± 0%   64.01Mi ± 0%       ~ (p=1.000 n=10) ¹
Argon2i/_Time:_5_Memory:_64_MB,_Threads:_4     64.01Mi ± 0%   64.01Mi ± 0%       ~ (p=1.000 n=10) ¹
Argon2d/_Time:_3,_Memory:_32_MB,_Threads:_1    32.00Mi ± 0%   32.00Mi ± 0%       ~ (p=1.000 n=10) ¹
Argon2d/_Time:_4,_Memory:_32_MB,_Threads:_1    32.00Mi ± 0%   32.00Mi ± 0%       ~ (p=1.000 n=10) ¹
Argon2d/_Time:_5,_Memory:_32_MB,_Threads:_1    32.00Mi ± 0%   32.00Mi ± 0%       ~ (p=1.000 n=10) ¹
Argon2d/_Time:_3,_Memory:_64_MB,_Threads:_4    64.01Mi ± 0%   64.01Mi ± 0%       ~ (p=1.000 n=10) ¹
Argon2d/_Time:_4,_Memory:_64_MB,_Threads:_4    64.01Mi ± 0%   64.01Mi ± 0%       ~ (p=1.000 n=10) ¹
Argon2d/_Time:_5,_Memory:_64_MB,_Threads:_4    64.01Mi ± 0%   64.01Mi ± 0%       ~ (p=1.000 n=10) ¹
Argon2id/_Time:_3,_Memory:_32_MB,_Threads:_1   32.00Mi ± 0%   32.00Mi ± 0%       ~ (p=1.000 n=10) ¹
Argon2id/_Time:_4,_Memory:_32_MB,_Threads:_1   32.00Mi ± 0%   32.00Mi ± 0%       ~ (p=1.000 n=10) ¹
Argon2id/_Time:_5,_Memory:_32_MB,_Threads:_1   32.00Mi ± 0%   32.00Mi ± 0%       ~ (p=1.000 n=10) ¹
Argon2id/_Time:_3,_Memory:_64_MB,_Threads:_4   64.01Mi ± 0%   64.01Mi ± 0%       ~ (p=1.000 n=10) ¹
Argon2id/_Time:_4,_Memory:_64_MB,_Threads:_4   64.01Mi ± 0%   64.01Mi ± 0%       ~ (p=1.000 n=10) ¹
Argon2id/_Time:_5,_Memory:_64_MB,_Threads:_4   64.01Mi ± 0%   64.01Mi ± 0%       ~ (p=1.000 n=10) ¹
geomean                                        45.26Mi        45.26Mi       +0.00%
¹ all samples are equal

                                             | old.bench  |              new.bench              |
                                             | allocs/op  | allocs/op   vs base                 |
Argon2i/_Time:_3_Memory:_32_MB,_Threads:_1     31.00 ± 0%   31.00 ± 0%       ~ (p=1.000 n=10) ¹
Argon2i/_Time:_4_Memory:_32_MB,_Threads:_1     39.00 ± 0%   39.00 ± 0%       ~ (p=1.000 n=10) ¹
Argon2i/_Time:_5_Memory:_32_MB,_Threads:_1     47.00 ± 0%   47.00 ± 0%       ~ (p=1.000 n=10) ¹
Argon2i/_Time:_3_Memory:_64_MB,_Threads:_4     73.00 ± 0%   73.00 ± 0%       ~ (p=1.000 n=10) ¹
Argon2i/_Time:_4_Memory:_64_MB,_Threads:_4     93.00 ± 0%   93.00 ± 0%       ~ (p=1.000 n=10) ¹
Argon2i/_Time:_5_Memory:_64_MB,_Threads:_4     113.0 ± 0%   113.0 ± 0%       ~ (p=1.000 n=10) ¹
Argon2d/_Time:_3,_Memory:_32_MB,_Threads:_1    31.00 ± 0%   31.00 ± 0%       ~ (p=1.000 n=10) ¹
Argon2d/_Time:_4,_Memory:_32_MB,_Threads:_1    39.00 ± 0%   39.00 ± 0%       ~ (p=1.000 n=10) ¹
Argon2d/_Time:_5,_Memory:_32_MB,_Threads:_1    47.00 ± 0%   47.00 ± 0%       ~ (p=1.000 n=10) ¹
Argon2d/_Time:_3,_Memory:_64_MB,_Threads:_4    73.00 ± 0%   73.00 ± 0%       ~ (p=1.000 n=10) ¹
Argon2d/_Time:_4,_Memory:_64_MB,_Threads:_4    93.00 ± 0%   93.00 ± 0%       ~ (p=1.000 n=10) ¹
Argon2d/_Time:_5,_Memory:_64_MB,_Threads:_4    113.0 ± 0%   113.0 ± 0%       ~ (p=1.000 n=10) ¹
Argon2id/_Time:_3,_Memory:_32_MB,_Threads:_1   31.00 ± 0%   31.00 ± 0%       ~ (p=1.000 n=10) ¹
Argon2id/_Time:_4,_Memory:_32_MB,_Threads:_1   39.00 ± 0%   39.00 ± 0%       ~ (p=1.000 n=10) ¹
Argon2id/_Time:_5,_Memory:_32_MB,_Threads:_1   47.00 ± 0%   47.00 ± 0%       ~ (p=1.000 n=10) ¹
Argon2id/_Time:_3,_Memory:_64_MB,_Threads:_4   73.00 ± 0%   73.00 ± 0%       ~ (p=1.000 n=10) ¹
Argon2id/_Time:_4,_Memory:_64_MB,_Threads:_4   93.00 ± 0%   93.00 ± 0%       ~ (p=1.000 n=10) ¹
Argon2id/_Time:_5,_Memory:_64_MB,_Threads:_4   113.0 ± 0%   113.0 ± 0%       ~ (p=1.000 n=10) ¹
geomean                                        59.32        59.32       +0.00%
¹ all samples are equal

Change-Id: Ia814057ddfdefbe1d23431fa366189ffe5852b96
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/826304
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>
Reviewed-by: abner chenc <chenguoqi@loongson.cn>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2026-09-19 18:38:21 -07:00
Daniel McCarney b4dcfb54b8 acme: support standards-compliant order finalization
When an order finalization response is not immediately valid,
Client.CreateOrderCert depends on the ACME server returning a Location
header. The header value is used as the URL for polling the updated
order status. RFC 8555 does not require this header, so CreateOrderCert
does not interoperate with ACME servers that omit it (e.g. Pebble
v2.9.0+).

This commit adds Client.CreateCertFromOrder, which accepts an *Order and
uses its URI for polling instead of relying on the finalization
response's Location header. It also updates existing callers and
documentation to use the new method and updates the integration tests to
Pebble v2.10.1 (the latest available version), which omits the
finalization Location header.

Fixes golang/go#77704

Change-Id: I0852f19c5d18d6debc9c9686fa2c14a2e39663c2
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/817000
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: Roland Shoemaker <roland@golang.org>
2026-09-18 12:05:15 -07:00
Gopher Robot b853e4b620 x509roots/fallback: update bundle
This is an automated CL which updates the NSS root bundle.

[git-generate]
go generate ./x509roots

Change-Id: I975f934aabe6eaf6b9f256db2b6942c45c9bd7b4
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/833664
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
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-09-16 08:43:51 -07:00
Gopher Robot 3f62bf119e go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I39f495ef42016b2ab0c91f54b792ac16b967006f
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/829324
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: Cherry Mui <cherryyz@google.com>
2026-09-08 11:05:01 -07:00
Nicola Murino 86efde54dc ssh: reject unexpected message types on established channels
ch.msg is only read while the channel open or a channel request with a
reply is pending, so anything the default arm of channel.handlePacket
delivered to it was never consumed. The blocking send there let a
misbehaving peer fill the buffer with well-formed but unexpected message
types carrying a valid channel id and stall the mux read loop,
deadlocking the whole connection.

No conforming peer sends such messages during the connection protocol.
Treat them as a protocol error and tear the connection down, as
handleUnknownChannelPacket already does for the same messages when the
channel id is not in use.

Fixes CVE-2026-56855
Fixes golang/go#81317

Change-Id: I87420dfe68fcb62a17df4b47dc5ffb6ccd72ba26
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/826524
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>
Auto-Submit: Neal Patel <nealpatel@google.com>
Reviewed-by: Nicholas Husin <husin@google.com>
2026-09-02 11:02:47 -07:00
Nicola Murino a6cdac6084 ssh: drop traffic on undecided channels
A channel in the mux's chanList is not usable until it is established:
an outbound channel has no confirmed remote id until the peer's open
confirmation, and an inbound channel is not serviced by the application
until it is accepted. handlePacket processed any channel message on it,
so a misbehaving peer could flood channel requests and block the mux
read loop on the send to incomingRequests, deadlocking the connection,
or close an outbound channel before confirming it, making the victim
tear down a half-initialized channel and emit a close for remote id 0,
an unrelated channel of the peer.

No such packet can be legitimate: the peer learns an inbound channel's
local id only from the confirmation we have not sent yet, and on an
outbound channel RFC 4254 lets it answer the open request only with a
confirmation or a failure.

Add an established flag, set when the channel becomes usable: for an
outbound channel when the open response is received, for an inbound
channel by Accept before the confirmation is sent. Until then
handlePacket drops every packet other than the open response. The flag
is separate from decided, which Reject also sets: a rejected channel is
decided but must never carry traffic.

Fixes CVE-2026-78662
Fixes golang/go#81316

Change-Id: Ib0983bb216a49808a2db1f4a4d92ee9fe38a3c51
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/826504
Auto-Submit: Gopher Robot <gobot@golang.org>
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: Neal Patel <nealpatel@google.com>
Reviewed-by: Nicholas Husin <husin@google.com>
2026-09-02 10:48:31 -07:00
Nicola Murino 39dc44e69c ssh: don't skip the source-address critical option in CheckCert
CertChecker.CheckCert ignored source-address on the assumption that
serverAuthenticate would enforce it, but that only happens in the
server-side user authentication path. Nothing enforced it in the host key
path, so CheckHostKey accepted CA-signed host certificates carrying
source-address regardless of the server's address, and the same applied to
applications calling CheckCert directly.

Drop the special case: every critical option must be listed in
SupportedCriticalOptions, host and user certificates alike. Authenticate,
the only path where serverAuthenticate does enforce source-address, checks
against a copy of the CertChecker with that option appended.

Fixes golang/go#80872

Change-Id: I3c3554b71ea2a4ce4b17696a9596b973b7d74b00
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/816840
Reviewed-by: David Chase <drchase@google.com>
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: Filippo Valsorda <filippo@golang.org>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
2026-08-30 20:04:51 -07:00
Dmitri Shuralyov afebf4cb4e x509roots/fallback/bundle: make subjectsEqual stricter on Go 1.27+
This gradual step towards removing/inlining subjectsEqual can happen
after Go 1.27.0 is released and the bundle starts being generated
with it.

Change-Id: Ib315bae69c45922c3f0aac5d2c0155fb5d94229f
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/775782
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>
Auto-Submit: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
2026-08-26 07:40:58 -07:00
Gopher Robot 89f4e9bb5b x509roots/fallback: update bundle
This is an automated CL which updates the NSS root bundle.

[git-generate]
go generate ./x509roots

Change-Id: I3be04cd4cb6e44856beaa074fdb62a58ff8ce35b
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/820300
Auto-Submit: Gopher Robot <gobot@golang.org>
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: Roland Shoemaker <roland@golang.org>
2026-08-24 13:54:08 -07:00
Nicola Murino 71488c48c2 ssh/knownhosts: compare only public key portions for revocation
Revocation matching compared full marshaled key blobs, so a @revoked
line containing a plain host key did not revoke a certificate
certifying that key: when the server presented such a certificate,
IsRevoked only matched the whole certificate blob or the CA key, and
verification succeeded even though the underlying host key was revoked.

OpenSSH's check_key_not_revoked compares keys with sshkey_equal_public,
which considers only the public portions and explicitly allows
comparisons between certificates and plain keys. Match that behavior by
normalizing both @revoked entries and lookups to the underlying public
key: for a certificate, the certified key rather than the certificate
blob. This also makes a @revoked line containing a certificate revoke
the plain key it certifies

Change-Id: I3029d59e68fb01f2340763e2eae25cac23c6193d
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/816841
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: David Chase <drchase@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2026-08-23 06:53:19 -07:00
Daniel McCarney 82adefa711 ssh: synchronize unexpected response test
Wait for an ordered channel request after sending the unsolicited
response flood. This ensures that the client mux has discarded the
entire flood before SendRequest opens its response gate, avoiding
confusion between an in-flight unsolicited response and the expected
reply.

This fixes TestChannelUnexpectedResponsesDiscarded from flaking, where
otherwise running 1000000 iterations of the test with GOMAXPROCS=16
produced ~15 distinct failures of the form  "expected success reply".

Change-Id: Ic1125c1f44bd919a5cf32b889d331bbc94c06c25
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/817140
Reviewed-by: Neal Patel <neal@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>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Auto-Submit: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: David Chase <drchase@google.com>
2026-08-19 13:42:46 -07:00
Gopher Robot c757c9851f all: upgrade go directive to at least 1.26.0 [generated]
By now Go 1.27.0 has been released, and Go 1.25 is no longer supported
per the Go Release Policy (see https://go.dev/doc/devel/release#policy).

See https://go.dev/doc/godebug#go-126 for GODEBUG setting changes
relevant to Go 1.26.

For golang/go#69095.

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

Change-Id: I54826e019edd4e12ad821915b1d102de719bfb31
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/817981
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>
Reviewed-by: Carlos Amedee <carlos@golang.org>
Auto-Submit: Gopher Robot <gobot@golang.org>
2026-08-19 10:16:24 -07:00
Damien Miller 593c81af8a ssh: correctly ignore pre-banner lines
Reading the peer's benner in readVersion() was incorrectly counting
lines sent by the server before the actual `SSH-2.0` banner against
the line limit for the banner itself.

This is incorrect per RFC 4253 section 4.2, where the limit of 255
characters is written to apply only to the `SSH-` banner string
itself.

This instead limits pre-banner lines to 255 characters each but
instead allows a maximum of 1024 lines.

Change-Id: Ief014bb3413e26e8d2077d3eb204ceaea9dc9444
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/811320
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: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Carlos Amedee <carlos@golang.org>
2026-08-17 08:34:06 -07:00
Daniel McCarney 46efc8bc62 acme: add crypto.SignMessage test coverage
This commit updates the pre-existing TestJWSEncodeJSONCustom test to
also verify JWS signature production works with a crypto.MessageSigner.

Change-Id: I5156cb4da9a7feee98340ff4fb75848da5827055
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/815480
Auto-Submit: Daniel McCarney <daniel@binaryparadox.net>
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: Carlos Amedee <carlos@golang.org>
2026-08-17 08:22:44 -07:00
Daniel Tang e0a54fdc4b acme: use crypto.SignMessage instead of calling (crypto.Signer).Sign
crypto.SignMessage allows using crypto.Signers that only usefully
implement SignMessage to be used for the ACME account key.

This would be useful for opening up integrations with opinionated
remote signing APIs that don't support pre-hashing.

Fixes golang/go#80877

Change-Id: I86bb76cf5865d3d2b8606a6dbd813cbb26447c86
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/815340
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: Filippo Valsorda <filippo@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: Carlos Amedee <carlos@golang.org>
2026-08-17 08:21:42 -07:00
Gopher Robot f44d03d253 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I6e7a078f1a8ffe71bace5615ad4fc03a12466985
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/813280
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>
Reviewed-by: Mark Freeman <markfreeman@google.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
2026-08-11 10:56:31 -07:00
Julian Zhu 5ed494470b crypto/internal/poly1305: provide optimised assembly for riscv64
goos: linux
goarch: riscv64
pkg: golang.org/x/crypto/internal/poly1305
                   │ sum1305-old  │            sum1305-new              │
                   │    sec/op    │   sec/op     vs base                │
64-4                  195.9n ± 1%   144.8n ± 0%  -26.07% (p=0.000 n=10)
1K-4                  1.853µ ± 0%   1.012µ ± 0%  -45.39% (p=0.000 n=10)
2M-4                  3.627m ± 0%   1.880m ± 0%  -48.17% (p=0.000 n=10)
64Unaligned-4         196.4n ± 1%   174.7n ± 0%  -11.05% (p=0.000 n=10)
1KUnaligned-4         1.853µ ± 0%   1.491µ ± 0%  -19.54% (p=0.000 n=10)
2MUnaligned-4         3.643m ± 0%   2.850m ± 0%  -21.78% (p=0.000 n=10)
Write64-4            126.85n ± 0%   77.40n ± 0%  -38.98% (p=0.000 n=10)
Write1K-4            1784.5n ± 1%   937.2n ± 0%  -47.48% (p=0.000 n=10)
Write2M-4             3.654m ± 2%   1.880m ± 0%  -48.55% (p=0.000 n=10)
Write64Unaligned-4    125.7n ± 0%   107.5n ± 0%  -14.48% (p=0.000 n=10)
Write1KUnaligned-4    1.782µ ± 0%   1.424µ ± 0%  -20.09% (p=0.000 n=10)
Write2MUnaligned-4    3.637m ± 0%   2.850m ± 0%  -21.64% (p=0.000 n=10)
geomean               10.14µ        6.925µ       -31.68%

                   │ sum1305-old  │             sum1305-new-3             │
                   │     B/s      │      B/s       vs base                │
64-4                 311.7Mi ± 1%    421.5Mi ± 0%  +35.25% (p=0.000 n=10)
1K-4                 527.0Mi ± 0%    965.0Mi ± 0%  +83.10% (p=0.000 n=10)
2M-4                 551.4Mi ± 0%   1063.8Mi ± 0%  +92.94% (p=0.000 n=10)
64Unaligned-4        310.8Mi ± 1%    349.3Mi ± 0%  +12.38% (p=0.000 n=10)
1KUnaligned-4        526.9Mi ± 0%    654.9Mi ± 0%  +24.30% (p=0.000 n=10)
2MUnaligned-4        548.9Mi ± 0%    701.8Mi ± 0%  +27.85% (p=0.000 n=10)
Write64-4            481.2Mi ± 0%    788.6Mi ± 0%  +63.89% (p=0.000 n=10)
Write1K-4            547.2Mi ± 1%   1042.0Mi ± 0%  +90.42% (p=0.000 n=10)
Write2M-4            547.4Mi ± 2%   1064.0Mi ± 0%  +94.38% (p=0.000 n=10)
Write64Unaligned-4   485.5Mi ± 0%    567.7Mi ± 0%  +16.94% (p=0.000 n=10)
Write1KUnaligned-4   547.9Mi ± 0%    685.8Mi ± 0%  +25.17% (p=0.000 n=10)
Write2MUnaligned-4   550.0Mi ± 0%    701.9Mi ± 0%  +27.62% (p=0.000 n=10)
geomean              485.5Mi         710.7Mi       +46.37%

Change-Id: I33a3df03382eb42ef062b0366521f02559290482
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/738760
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: Meng Zhuo <mengzhuo1203@gmail.com>
Reviewed-by: Mark Freeman <markfreeman@google.com>
2026-08-03 22:01:12 -07:00
Nicola Murino b07833c067 ssh: return window credit for discarded extended data
handleData subtracts the length of every data packet from the receive
window, but extended data with a type code other than
SSH2_EXTENDED_DATA_STDERR is then silently discarded and, since no API
exists to read it, its window credit was never returned: adjustWindow
only runs as a side effect of reading a stream. A peer sending
extended data with an unknown type code could therefore permanently
shrink the channel window, down to a complete stall of the channel.

Credit the discarded bytes back through adjustWindow. adjustWindow
returns io.EOF if the local side has already sent a channel close;
ignore it like ReadExtended does, since an error returned here would
terminate the mux read loop and tear down the whole connection. For
comparison, OpenSSH rejects extended data with unexpected type codes
outright and never buffers it, so the dropped bytes are simply never
credited back to the misbehaving peer.

Fixes golang/go#80333

Change-Id: Ia311ce3ad008e7c89ce9752f1937c91374a4e74f
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/802901
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: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2026-08-03 14:00:09 -07:00
Brad Fitzpatrick d701c51f7e acme: fix nil pointer dereference in pebble test error reporting
The WaitOrder failure path used errors.Is with a nil *OrderError
target, which never matches and left orderErr nil at the point its
Problem field was dereferenced. Use errors.As to populate the target
instead.

Found by govet's nilness check.

Change-Id: Ieef849fcbf04c85ef32651059db2b5fe162af325
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/803181
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>
2026-07-23 08:25:44 -07:00
Brad Fitzpatrick 999d053994 ssh: fix parsing of GSSAPI payloads offering multiple mechanisms
parseGSSAPIPayload overwrote the remaining payload with the trailing
bytes returned by asn1.Unmarshal after decoding each OID, so any
request offering more than one mechanism failed to parse after the
first one. Track the remaining payload across iterations instead, and
be strict: reject payloads with trailing bytes after an OID or after
the mechanism list.

Add a test with a two-mechanism payload (Kerberos V5 followed by
SPNEGO) that failed before this change.

Change-Id: If0984efcf103da76323d5d03ad7443d8ec9d3aed
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/803180
Reviewed-by: Carlos Amedee <carlos@golang.org>
Reviewed-by: Nicola Murino <nicola.murino@gmail.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-07-23 08:19:57 -07:00
Nicola Murino 90f76b8ffe ssh: reject certificate signature keys before recursing
parseCert parsed a certificate's SignatureKey by calling ParsePublicKey
again, and only afterwards rejected a certificate used as a signing key.
For a chain of nested certificates this recursed once per level, so a key
with enough nesting exhausted the goroutine stack and crashed with a fatal
stack overflow that recover cannot catch.

Reject the signature key by its declared algorithm before parsing it, which
bounds parsing.

Fixes golang/go#80414

Change-Id: Id51401aae15bfbec006c03ab97635a3b68bd6058
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/802145
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Carlos Amedee <carlos@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: Filippo Valsorda <filippo@golang.org>
2026-07-22 10:37:06 -07:00
database64128 b53964a1ca ssh: permit empty but non-nil HostKeyAlgorithms, KeyExchanges, Ciphers, MACs
The documentation of ClientConfig.HostKeyAlgorithms says:

  If empty, a reasonable default is used.

However, if HostKeyAlgorithms is empty but non-nil, the reasonable
default won't be applied, and the SSH handshake will fail. Fix this by
changing the nil check to a length check.

While here, do the same for KeyExchanges, Ciphers, MACs in Config.

Change-Id: I1b3d2d2159f3c7d57a9a690ad04f1f6818b39a5c
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/800080
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: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Carlos Amedee <carlos@golang.org>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
2026-07-22 10:37:01 -07:00
Nicola Murino 626e40fc98 ssh: drain stderr on forwarded TCP and Unix channels
tcpListener.Accept, unixListener.Accept, Client.dial and
Client.dialStreamLocal only read the main stream of the channels they
return. Data sent by the peer on the extended (stderr) stream
accumulates in the extPending buffer and its window credit is only
returned by ReadExtended, which is never called. Since the window is
shared between the two streams, a misbehaving peer can pin up to 2 MiB
per channel and eventually stall it; well-behaved peers never send
stderr on these channel types.

Drain the stderr stream into io.Discard, mirroring CL 783720 which
fixed the same issue in the agent forwarders.

The drain takes precedence over reading Stderr through a type assertion
on the returned net.Conn, which was never a supported use. For
comparison, OpenSSH refuses extended data on these channel types and
drops the payload without buffering it.

Updates golang/go#80333

Change-Id: I4f1445eee9ce1b56ca62cec342812d63cfdd3e13
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/802900
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Carlos Amedee <carlos@golang.org>
Reviewed-by: Cherry Mui <cherryyz@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2026-07-22 10:34:36 -07:00
Gopher Robot 31914c699b x509roots/fallback: update bundle
This is an automated CL which updates the NSS root bundle.

[git-generate]
go generate ./x509roots

Change-Id: Ic89f2ab75500d9b03a76236f2228657508a4d16d
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/803060
Reviewed-by: Carlos Amedee <carlos@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Gopher Robot <gobot@golang.org>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2026-07-21 14:38:23 -07:00
Brad Fitzpatrick f2135b814c all: clean up minor issues found by staticcheck
Use bytes.Equal instead of comparing bytes.Compare results to zero,
avoid Yoda conditions, drop a redundant zero slice capacity, use
strings.ReplaceAll, build acme error strings with a strings.Builder,
and lowercase an error string in ocsp. No behavior changes.

Change-Id: I5d2b3fa5c241adc75e61be0f2d2d7af1eb9e8d66
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/803200
Reviewed-by: Roland Shoemaker <roland@golang.org>
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: Carlos Amedee <carlos@golang.org>
2026-07-21 14:30:59 -07:00
Akira ff03dafdb0 ssh: report verified signature format to callback
VerifiedPublicKeyCallback currently receives the public-key algorithm
declared in the outer authentication request. For RSA authentication,
that value can differ from the format of the signature that was
successfully verified because compatible RSA algorithm combinations are
accepted.

This can cause post-verification policy or audit decisions to use the
request algorithm instead of the signature format actually verified.

Pass sig.Format to VerifiedPublicKeyCallback so signatureAlgorithm
identifies the successfully verified signature format. Clarify the
callback documentation and add a regression test covering compatible
but different RSA request algorithms and signature formats.

Fixes golang/go#80411

Change-Id: Ib405378d75367a90536e0814c9d26d4dec9aaa25
GitHub-Last-Rev: 1a4acd4e639361be1f2948a4aef1013436a75ecf
GitHub-Pull-Request: golang/crypto#364
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/800740
Reviewed-by: Michael Pratt <mpratt@google.com>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: David Chase <drchase@google.com>
Auto-Submit: Michael Pratt <mpratt@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2026-07-17 15:41:46 -07:00
Nicola Murino 10b54ffa51 ssh: raise the RSA modulus limit to 16384 bits
the fix for CVE-2026-39829 capped the accepted RSA modulus at 8192 bits,
matching crypto/tls, to bound the CPU cost of verifying an
attacker-supplied key. That rejected keys OpenSSH generates: ssh-keygen
allows -b up to 16384. Raise the limit to 16384 so those keys interoperate,
both in the public key parser and the OpenSSH private key parser, and
correspondingly raise the prime-factor bound to 8192 bits (each prime is
about half the modulus). The agent's checkRSAKeyParams is updated to match.

Verifying a 16384-bit key costs roughly 3x an 8192-bit one.

Fixes golang/go#80075

Change-Id: Ib08ddd7b48552e692c48dbdf105bbc8579120bbc
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/795421
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: Filippo Valsorda <filippo@golang.org>
Reviewed-by: David Chase <drchase@google.com>
2026-07-13 20:33:21 -07:00
Nicholas S. Husin 0f039f3a4a ssh: sanitize various error messages
Similar to CL 780180, sanitize other error messages that are controlled
by the remote peer, to avoid potential injection of control characters.

Also remove sanitizeString usage as it is not strictly needed to escape
error messages safely, and for consistency with how we sanitize other
error messages throughout the codebase.

BannerDisplayStderr is left unsanitized for now, as it is one instance
where we might actually want control characters for valid reasons (see
golang/go#80302).

Updates golang/go#80302
Fixes golang/go#80301

Change-Id: Ie40f4ac2f76afed740dceb548a4b0fa96a6a6964
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/798420
Auto-Submit: Nicholas Husin <nsh@golang.org>
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>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Nicholas Husin <husin@google.com>
2026-07-13 12:23:17 -07:00
Nicola Murino b27e1504e3 ssh: don't close the connection on an unparseable public key
In the server's publickey authentication path, a public key blob that
ParsePublicKey could not decode caused serverAuthenticate to return an
error, tearing down the whole connection. A key we cannot parse is part
of an individual authentication attempt, not a transport-level framing
error, so it must fail only that attempt. This lets the client fall
back to other keys or authentication methods.

Updates golang/go#80075

Change-Id: I8d882d08bb50eb33e0054d9d9c2bd9e0b3039443
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/795420
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: Michael Pratt <mpratt@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
2026-07-13 12:20:29 -07:00
Nicola Murino c1a3b97d70 ssh: document and test source-address behavior for non-IP transports
The source-address critical option is a comma-separated list of IP
addresses and CIDR blocks, so it can never match a connection whose
remote address is not IP-based, such as a Unix domain socket.

Change-Id: I45e09fe5c8c13922cb0735278acf33320857322c
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/797042
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>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
2026-07-12 08:19:47 -07:00
Nicola Murino b9229ecc70 ssh: reject a present but empty source-address critical option
checkSourceAddressCriticalOption treated a source-address critical
option with an empty value as if the option was absent, allowing
authentication from any address. A callback (or certificate authority)
building the value dynamically from an empty allowlist would intend to
deny all sources, not to lift the restriction. This also contradicts
the documented contract that the option is validated whenever it is
present, and differs from OpenSSH, where an empty address list matches
nothing.

Change-Id: I1c0de27cbcab8817a7ff446019c25cd19957a7d7
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/797041
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-07-12 08:19:43 -07:00
Nicola Murino e557b08ec2 ssh: enforce the source-address critical option for all auth callbacks
CVE-2026-46595 extended source-address validation, historically applied
only to the Permissions returned by PublicKeyCallback, to the ones
returned by VerifiedPublicKeyCallback. The documented contract of
Permissions.CriticalOptions does not restrict enforcement to a specific
authentication method, so move the check to a single point at the end of
each authentication attempt, where it covers the Permissions returned by
any callback (password, keyboard-interactive, none and GSSAPI included).

The check at public key cache insertion time is kept: it remains
authoritative for the Permissions returned by PublicKeyCallback, which
VerifiedPublicKeyCallback may replace before the check at the end of the
authentication attempt runs and which are not re-checked on partial
success. It also still makes public key queries fail before the client
produces a signature when PublicKeyCallback supplies the restriction.

Fixes CVE-2026-56854
Fixes golang/go#80213

Change-Id: Ibd612a8e4240bd710e33754f3ceb95bb29169d9a
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/797040
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>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: David Chase <drchase@google.com>
2026-07-12 08:19:37 -07:00
Nicola Murino 4044611da8 ssh: fix data race in the doClientServerAuth test helper
The helper returned the auth errors collected via AuthLogCallback
without waiting for the server goroutine that appends to them. Close
the client side of the connection on handshake failure, to unblock a
server still reading from it, and join the server goroutine before
returning.

Change-Id: Ibe8c3b236491769f3433f7457d4f2b9a07a65be0
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/797043
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>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: David Chase <drchase@google.com>
2026-07-12 08:19:29 -07:00
Nicola Murino e8ad5cb7aa ssh: initialize new channels fully before adding them to chanList
newChannel published the channel into the mux's chanList (via
chanList.add) before assigning its localId, and openChannel/Accept set
maxIncomingPayload only after newChannel returned. For an outbound
channel, whose newChannel runs on an application goroutine, the mux
loop could observe the channel through getChan before those fields
were initialized, reading a zero localId or maxIncomingPayload with no
happens-before relationship.

Assign localId inside add while the chanList lock is held, and set
maxIncomingPayload (always channelMaxPacket) in newChannel itself, so
a channel returned by getChan is always fully initialized.

Change-Id: Ib54a5d10dcb5c1ad8ed4dabe5d8d2790778be298
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/797061
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: David Chase <drchase@google.com>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
2026-07-12 08:19:12 -07:00
Nicola Murino fe1af3a418 ssh: make channel.close idempotent
channel.close closes the internal Go channels (msg, incomingRequests);
calling it twice panics with "close of closed channel". Both current
callers run on the mux loop and are serialized, so the panic is not
reachable today. Harden close by guarding it with sync.Once, so that
the connection does not become fragile to any future bug that reaches
close twice.

Change-Id: I5d8d948367538ea5561724033c4ee4daa668e221
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/797060
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>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
2026-07-12 08:19:06 -07:00
Daniel McCarney 243e02a382 ocsp: update ParseRequest docs & error conditions
ParseRequest was documented as erroring for inputs that contained
an optional request signature, and as only supporting requests for
a single certificate.

However, prior to this commit DER inputs that contained a signature
succeeded without verifying the signature, and inputs that contained
multiple certificate identifiers succeeded but only the first
certificate identifier was unmarshalled.

This commit updates the function behaviour to return an error for the
signature case as described in the docs, and to clarify the
documentation for inputs with multiple certificate identifiers.

Fixes golang/go#80300

Change-Id: I7446422d6c98bd406b8c43e55fea9a16ace9d4a6
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/798220
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Daniel McCarney <daniel@binaryparadox.net>
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: Nicholas Husin <husin@google.com>
2026-07-09 11:40:58 -07:00
Gopher Robot cdce021fa6 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I431b878ec8830bf1894ae19176b5984b00954557
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/798280
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: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
2026-07-08 11:22:26 -07:00
Roland Shoemaker d9474cc485 openpgp: make the deprecation message more explicit
The package is unmaintained, unsafe at any speed, and does not receive
security fixes. Document that, and point at the ProtonMail fork for
those that _must_ still use OpenPGP.

Change-Id: Ia602eaaf9e08bd25389400ebe7f346b60bdb9d99
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/794200
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: Damien Neil <dneil@google.com>
2026-07-07 10:06:58 -07:00
Nicola Murino 7626c50256 ssh: verify declared key type matches decoded key in authorized_keys
ParseAuthorizedKey and ParseKnownHosts previously ignored the key type
field (e.g. "ssh-rsa") in each entry, relying solely on the type
information embedded within the base64-encoded key blob.

For ParseAuthorizedKey this also caused a single-token option to be
silently dropped: a line such as "restrict <key>" (with the key type
omitted) was parsed as an unrestricted key, because the option token
landed in the key type position and was discarded together with its
meaning. The same happens for no-pty, no-port-forwarding and the other
single-word options. OpenSSH's sshkey_read rejects such lines outright,
as the option token cannot be read as a key type.

OpenSSH's sshkey_read also 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, in both functions, a check that the declared key type
matches the decoded key's type, returning an error for malformed lines
where they diverge. This mirrors the fix already applied to the
ssh/knownhosts package in CL 782427.

Change-Id: I9163108d964de4be8a415fe0efd68e6b71f77990
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/792840
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>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Neal Patel <nealpatel@google.com>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
2026-06-30 10:24:32 -07:00
Nicola Murino 0471e7969e ssh/agent: enforce strict limits on DSA key parameters
The parseDSAKey function constructed a *dsa.PrivateKey directly from the
add-identity request without validating the key parameters. Unlike DSA
certificates, whose parameters are checked by the ssh package when the
certificate's public key is parsed, raw DSA keys added to the agent were
not validated at all.

Align the raw DSA key parsing with the validation already performed by
the main ssh package.

Fixes golang/go#79725

Change-Id: I537cc2175d35c19848c90c68739cf94ba7b50e10
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/795422
Reviewed-by: Roland Shoemaker <roland@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-30 10:06:28 -07:00
Neal Patel 6435c37ab6 ssh: sanitize client disconnect messages
A malicious peer can send control characters
and escape sequences in SSH_MSG_DISCONNECT;
strip these characters and %q escape it.

Change-Id: I266f78630a7a816a79ce4dda568ce57d7c3f6fb0
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/780180
Commit-Queue: 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: Neal Patel <nealpatel@google.com>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
2026-06-29 10:23:17 -07:00
Nicola Murino 7d695da948 ssh/agent: drain channel stderr in agent forwarders
ForwardToAgent and ForwardToRemote only read the main stream of the
auth-agent@openssh.com channels they accept. If a peer sends data on
the channel's extended (stderr) stream the bytes accumulate in the
client-side extPending buffer and the receive window is never
replenished, because the window is only adjusted as a side effect of
ReadExtended. That can pin up to channelWindowSize (2 MiB) of memory
per channel and silently stalls any stderr traffic once the window is
exhausted.

The auth-agent protocol does not use stderr, so a well-behaved peer
never sends anything on it. To stay tolerant of misbehaving peers
without leaving the channel half-stuck, drain the stderr stream into
io.Discard, mirroring the existing DiscardRequests pattern. The
goroutine exits when the channel is closed because Stderr().Read
returns io.EOF.

Add a regression test that opens an agent-forwarding channel and
writes more than the default window on the stderr stream from the
server side. Without the fix the write blocks once the remote window
is exhausted; with the fix the bytes are drained and the agent stream
remains usable.

Change-Id: Iadf8ea6ca726c058421bbc39f92e0100579fda17
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/783720
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Carlos Amedee <carlos@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>
2026-06-29 06:36:26 -07:00
Daniel McCarney 5b7f841599 acme/autocert: fix data race in Manager.createCert
Previously Manager.createCert() read state.locked without holding any
lock, while the owner goroutine wrote state.locked = false under the
state's write lock. Concurrent goroutines for the same domain raced on
that field.

We fix the issue by removing the certState.locked field and instead
having Manager.certState() return an additional owner bool computed
under the m.stateMu lock. This allows the Manager.createCert() caller to
know whether it must block on the read lock and return the state handled
by another goroutine, or instead do the work itself and release the
write lock.

A regression unit test is included that fails under -race without the
fix, and passes with the fix in-place.

Fixes golang/go#80119

Change-Id: I0f4c5c98f7e6bcf1ab71a3c0707bb0c7ce73415b
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/793840
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: Daniel McCarney <daniel@binaryparadox.net>
2026-06-26 08:59:20 -07:00
harjoth 0b316e7ee4 argon2: update RFC 9106 parameter recommendations
Update the IDKey example to use RFC 9106's first recommended Argon2id
option and clarify the relationship between the first and second
recommended options.

Fixes golang/go#79823

Change-Id: If44a86a5a8112b02fab97b4d5e325fe91d6049ee
GitHub-Last-Rev: a764ae65875f12d7422865c4e83f345a8a4f246e
GitHub-Pull-Request: golang/crypto#357
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/789020
Reviewed-by: 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>
2026-06-18 09:22:19 -07:00
Gopher Robot 55aec0a86b x509roots/fallback: update bundle
This is an automated CL which updates the NSS root bundle.

[git-generate]
go generate ./x509roots

Change-Id: I448f9962a67bf042b04a2e34f16ae02a004d6edd
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/791040
Auto-Submit: Gopher Robot <gobot@golang.org>
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>
2026-06-15 14:38:55 -07:00
Daniel McCarney 5f2de1a9f1 internal: remove wycheproof tests
Equivalent coverage using newer Wycheproof vectors has been added to the
standard library, alongside the implementations under test.

In the case where the algorithm doesn't exist in the stdlib, but is
intended to be supported there one day (e.g. chacha20poly1305) we flip
the relationship and run the Wycheproof tests from the stdlib on the
vendored /x/crypto. As a result the legacy Wycheproof coverage in this
repo can be removed.

Change-Id: Ic07d559e42599b715906f5bcc39be10944a8dde4
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/758420
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>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Auto-Submit: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2026-06-09 11:23:32 -07:00
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
Gopher Robot 506e022208 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I47041f06d6a0c92919eaac5d727cbc41551ed2e1
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/734461
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2026-01-12 07:56:02 -08:00
Filippo Valsorda 7dacc380ba chacha20poly1305: error out in fips140=only mode
We don't guarantee fips140=only support in x/crypto, but
chacha20poly1305 is special in that it's vendored into the standard
library. We could wrap all the callsites, but it's more robust to
just error out at construction time.

Change-Id: I4b1e451bd250429c4c5c5b61c8b2141c6a6a6964
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/728480
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: David Chase <drchase@google.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
2025-12-10 06:07:36 -08:00
Gopher Robot 19acf81bd7 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I81158fb078bccce57d8d46cac0cb87e6c4f8cff9
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/728181
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: David Chase <drchase@google.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-12-08 10:34:26 -08:00
Gopher Robot 3a1c6b4b61 x509roots/fallback: update bundle
This is an automated CL which updates the NSS root bundle.

[git-generate]
go generate ./x509roots

Change-Id: Icde363f2fa61d1cb85552e57d4cae30b33ec96ed
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/723803
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>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2025-12-03 12:57:53 -08:00
Michael Stapelberg f4602e4040 ssh/agent: fix flaky test by ensuring a writeable home directory
This fixes flakiness observed inside Google (b/465393996).

Change-Id: Ic3decc3206b470cddf22c441b0cf92bb2bebb075
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/724002
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-12-02 08:08:01 -08:00
Gopher Robot 4e0068c009 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I3923d98d88595230b12db261c48168b863dc2ce9
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/722000
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Neal Patel <nealpatel@google.com>
2025-11-19 11:55:48 -08:00
Neal Patel e79546e28b ssh: curb GSSAPI DoS risk by limiting number of specified OIDs
Previously, an attacker could specify an integer up to 0xFFFFFFFF
that would directly allocate memory despite the observability of
the rest of the payload. This change places a hard cap on the
amount of mechanisms that can be specified and encoded in the
payload. Additionally, it performs a small sanity check to deny
payloads whose stated size is contradictory to the observed payload.

Thank you to Jakub Ciolek for reporting this issue.

Fixes CVE-2025-58181
Fixes golang/go#76363

Change-Id: I0307ab3e906a3f2ae763b5f9f0310f7073f84485
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/721961
Auto-Submit: Roland Shoemaker <roland@golang.org>
Reviewed-by: Damien Neil <dneil@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-11-19 11:28:37 -08:00
Neal Patel f91f7a7c31 ssh/agent: prevent panic on malformed constraint
An attacker could supply a malformed Constraint that
would trigger a panic in a serving agent, effectively
causing denial of service.

Thank you to Jakub Ciolek for reporting this issue.

Fixes CVE-2025-47914
Fixes golang/go#76364

Change-Id: I195bbc68b1560d4f04897722a6a653a7cbf086eb
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/721960
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Roland Shoemaker <roland@golang.org>
Reviewed-by: Damien Neil <dneil@google.com>
2025-11-19 11:28:34 -08:00
Sean Liao 2df4153a03 acme/autocert: let automatic renewal work with short lifetime certs
Fixes golang/go#64997
Fixes golang/go#36548

Change-Id: Idb7a426ad3bfa6ac3b796f4b466da6e3154f1ffa
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/719080
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Mark Freeman <markfreeman@google.com>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-11-17 10:17:16 -08:00
Sean Liao bcf6a849ef acme: pass context to request
Fixes golang/go#30183

Change-Id: Ic02b34bc87b9465f5c05b2ef5bec157c58809a91
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/719002
Reviewed-by: Junyang Shao <shaojunyang@google.com>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-11-12 10:48:32 -08:00
Santhanam b4f2b62076 ssh: fix error message on unsupported cipher
Until now, when ssh keys using one of these[1] ciphers were passed, we were
giving a parse error "ssh: parse error in message type 0".

With this fix, we parse it successfully and return the correct error message.

[1] aes{128,256}-gcm@openssh.com and chacha20-poly1305@openssh.com

Fixes golang/go#52135

Change-Id: I3010fff43c48f29f21edb8d63f44e167861a054e
GitHub-Last-Rev: 14ac7e97306d41cba48053b9c60f2ffc7caded45
GitHub-Pull-Request: golang/crypto#324
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/709275
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-11-12 10:42:48 -08:00
Nicola Murino 79ec3a51fc ssh: allow to bind to a hostname in remote forwarding
To avoid breaking backwards compatibility, we fix Listen, which
receives the address as a string, while ListenTCP can still only
be used with IP addresses.

Fixes golang/go#33227
Fixes golang/go#37239

Change-Id: I4d45b40fdcb0d6012ed8da59a02149fa37e7db50
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/599995
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
Reviewed-by: Bishakh Ghosh <ghoshbishakh@gmail.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
2025-11-12 10:42:45 -08:00
Gopher Robot 122a78f140 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I0f64669e7c813611f71b1381d9e6fdaba1a39712
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/719641
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: David Chase <drchase@google.com>
2025-11-11 10:21:23 -08:00
Sean Liao c0531f9c34 all: eliminate vet diagnostics
For golang/go#74011

Change-Id: I189c5aba554a578bee1fd351edc30cd5cf4d0ed6
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/714960
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: David Chase <drchase@google.com>
2025-10-28 06:00:51 -07:00
cuishuang 0997000b45 all: fix some comments
Change-Id: I0395c5db6edd7d90f9ec1dadbe881a77c906c732
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/713120
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: David Chase <drchase@google.com>
Auto-Submit: Sean Liao <sean@liao.dev>
Reviewed-by: Sean Liao <sean@liao.dev>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
2025-10-27 09:33:07 -07:00
Sean Liao 017a1aaa2d chacha20poly1305: panic on dst and additionalData overlap
The cipher.AEAD interface specifies that these should not overlap.
This mirrors the check that the GCM implementation does.

Fixes golang/go#75968
Updates golang/go#21624

Change-Id: If5fbb8611ff6c0aae44d50079bad29f56ce00f5b
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/712860
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-10-22 18:37:21 -07:00
Filippo Valsorda cf29fa96f8 sha3: make it mostly a wrapper around crypto/sha3
crypto/sha3 was introduced in Go 1.24, which is now the minimum Go
version of this module.

Made the hashes go:fix inline wrappers, since the new types can be used
as hash.Hash directly.

The SHAKE instances need a wrapper for the methods we dropped from
crypto.XOF, so no go:fix inline there.

Kept the generic implementation for the legacy Keccak hashes we did not
bring to the standard library. We need to keep them working, but they
don't need to be fast.

Fixes golang/go#73681
Updates golang/go#65269

Change-Id: I6a6a69648b6353b153c70a2cec84864e64dcd61b
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/710115
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2025-10-22 18:01:01 -07:00
cuishuang 0b7aa0cfb0 ssh: use reflect.TypeFor instead of reflect.TypeOf
For golang/go#60088.

Change-Id: I58994c469a2793516214ab1a0072fb6137afc46e
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/709156
Auto-Submit: Sean Liao <sean@liao.dev>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
Reviewed-by: Sean Liao <sean@liao.dev>
2025-10-09 11:10:29 -07:00
cuishuang 1faea2975c all: fix some typos in comment
Change-Id: Ia209f0a6d9b19d14e655c65d1287a1416b48c487
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/707535
Reviewed-by: Carlos Amedee <carlos@golang.org>
Reviewed-by: Michael Pratt <mpratt@google.com>
Auto-Submit: Sean Liao <sean@liao.dev>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Sean Liao <sean@liao.dev>
2025-10-08 13:58:26 -07:00
Gopher Robot 627cb894b6 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: Icf986acf9290649488777328f470200bf9e11442
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/710098
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
2025-10-08 10:40:45 -07:00
Daniel McCarney dca4914afe acme: fix autocert TestHTTPHandlerDefaultFallback
The Go 1.25.2 release made net/url stricter about parsing bracketed IPv6
hostnames, and is rejecting some test URLs used in the autocert
TestHTTPHandlerDefaultFallback test with an error about the
colon-separated fields requiring at least one hex digit.

This commit replaces the invalid `xxxx` portion of some test URLS with
valid hex digits, fixing the test regression.

Change-Id: I84c192b1cd6daf53ef4199f7987437fd825f7041
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/710155
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-10-08 09:52:31 -07:00
Gopher Robot 1336e21bd6 x509roots/fallback: update bundle
This is an automated CL which updates the NSS root bundle.

[git-generate]
go generate ./x509roots

Change-Id: I9ab454c977013b2f6a42bc93fb0649612c54c6c0
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/709475
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Gopher Robot <gobot@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2025-10-08 08:14:13 -07:00
Nicola Murino 2beaa59a3c ssh: add VerifiedPublicKeyCallback
Fixes golang/go#70795

Change-Id: I9b7c91f35f89495d1e9b5f6ec0c036c02a61d774
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/636335
Reviewed-by: Michael Knyszek <mknyszek@google.com>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
Reviewed-by: Ilia Mirkin <imirkin@alum.mit.edu>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Jorge Hernández <jorgehcrda39@gmail.com>
2025-09-27 12:43:41 -07:00
Nicola Murino 66c3d8ce71 ssh: add support for FIPS mode
Unsupported algoritms are silently ignored and not negotiated, or
rejected

Fixes golang/go#75061

Change-Id: I08d50d10a97c08e78aedead89ca61beceff88918
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/698795
Reviewed-by: Mio Mio <miomio0086@gmail.com>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-09-27 12:36:52 -07:00
Nicola Murino ddb4e80c6a ssh: remove custom contains, use slices.Contains
Change-Id: If4784469e7285675bdd51399a76bdc16f0036a2e
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/703635
Reviewed-by: Mark Freeman <markfreeman@google.com>
Reviewed-by: Sean Liao <sean@liao.dev>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-09-15 23:33:16 -07:00
Nicola Murino f4d47b0db5 ssh: return clearer error when signature algorithm is used as key format
ParsePublicKey now returns a more specific error when a signature
algorithm like rsa-sha2-256 is mistakenly provided as a key format

Change-Id: Ic08286a5b2b326e99dd3e61594919203f0c36791
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/695075
Reviewed-by: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Mark Freeman <markfreeman@google.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
2025-09-15 23:32:56 -07:00
Michael Stapelberg 96dc232fbd x509roots/fallback/bundle: add bundle package to export root certs
Fixes golang/go#69898

Change-Id: Idbb1bbe48016a622414c84a56fe26f48bfe712c8
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/687155
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Roland Shoemaker <roland@golang.org>
Reviewed-by: Mateusz Poliwczak <mpoliwczak34@gmail.com>
2025-09-11 08:14:50 -07:00
Filippo Valsorda 8c9ba31836 all: freeze and deprecate more packages
Fixes golang/go#65250

Change-Id: I6a6a6964a2c87e529be50dd67fec462483b07b75
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/701535
Reviewed-by: Mark Freeman <markfreeman@google.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
2025-09-09 12:19:31 -07:00
Nicola Murino 559e062ce8 ssh/agent: return an error for unexpected message types
Previously, receiving an unexpected message type in response to a key
listing or a signing request could cause a panic due to a failed type
assertion.

This change adds a default case to the type switch in order to detect
and explicitly handle unknown or invalid message types, returning a
descriptive error instead of crashing.

Fixes golang/go#75178

Change-Id: Icbc3432adc79fe3c56b1ff23c6724d7a6f710f3a
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/700295
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
Reviewed-by: Jakub Ciolek <jakub@ciolek.dev>
2025-09-09 02:56:19 -07:00
Gopher Robot 5307a0ce6d go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I75e16a930bfe42cc082df82ab67802c42ad56a97
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/701303
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
2025-09-08 08:14:28 -07:00
Daniel McCarney 9d779377cf acme: include order problem in OrderError
If client.WaitOrder or client.CreateOrderCert return an acme.OrderError
it's helpful to include the order's problem field (if available). This
will often have detailed information about why a particular order
became invalid that's invaluable for debugging (e.g. a challenge
response was incorrect, a name couldn't be resolved, etc).

While it's possible for a consumer to poll the order themselves as part
of handling the order to extract a fresh Order.Error field value, it
would take an extra round-trip network request. Since we have the
underlying error in-hand when we produce the OrderError we might as well
include it directly.

Since this field is a structured object with a number of sub-fields the
OrderError.Error() function isn't updated to include the order problem
error in the String description. Interested callers should instead use
errors.Is to extract the problem information directly.

Resolves golang/go#74430

Cq-Include-Trybots: luci.golang.try:x_crypto-gotip-linux-amd64-longtest
Change-Id: I3158f064793bbfdc292dd6b5e1a6bfd7729bd980
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/681037
Auto-Submit: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Michael Pratt <mpratt@google.com>
Reviewed-by: Ian Stapleton Cordasco <graffatcolmingov@gmail.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-09-04 07:39:59 -07:00
Nicola Murino 8f580defa0 ssh: remove Go 1.24 build tag for ML-KEM kex
Change-Id: Ia77ad1b6fef9919ab100fb10c42231725eb81c12
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/698775
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2025-08-26 00:42:33 -07:00
Nicola Murino a4d1237429 ssh/knownhosts: improve IPv6 support in Normalize
Correctly converts bracketed IPv6:

- [abcd::abcd:abcd:abcd] => abcd::abcd:abcd:abcd
- [abcd::abcd:abcd:abcd]:22 => abcd::abcd:abcd:abcd
- [abcd::abcd:abcd:abcd]:23 => [abcd::abcd:abcd:abcd]:23

Fixes golang/go#53463

Change-Id: Id0a7460d8448a72e2a8c6d46137245bead9ecf9f
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/694575
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
2025-08-19 13:12:03 -07:00
Filippo Valsorda b8d8dae13d curve25519: include potential fips140=only error in panic message
Updates golang/go#75061

Change-Id: I6a6a696474122a12c12696d8a2efec902572327d
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/696996
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
2025-08-19 10:40:36 -07:00
Filippo Valsorda f5a2eabcab ssh: use curve25519.X25519 instead of curve25519.ScalarMult
This lets us surface an error message instead of panicking if running
in fips140=only mode, where ECDH on X25519 returns an error.

Updates golang/go#75061

Change-Id: I6a6a6964c0591f3dca2dc946c99d44364314a3ab
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/696995
Reviewed-by: Carlos Amedee <carlos@golang.org>
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
2025-08-19 10:38:43 -07:00
Gopher Robot 44ecf3af99 all: upgrade go directive to at least 1.24.0 [generated]
By now Go 1.25.0 has been released, and Go 1.23 is no longer supported
per the Go Release Policy (see https://go.dev/doc/devel/release#policy).

For golang/go#69095.

[git-generate]
(cd . && go get go@1.24.0 && go mod tidy && go fix ./... && go mod edit -toolchain=none)
(cd x509roots/fallback && go get go@1.24.0 && go mod tidy && go fix ./... && go mod edit -toolchain=none)

Change-Id: Ia4c201e9611a2c13489e16d4ae81d7e3e32bf455
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/695715
Auto-Submit: Gopher Robot <gobot@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: David Chase <drchase@google.com>
2025-08-13 08:00:22 -07:00
Gopher Robot ef5341b706 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I93de641462a54b0ae565bb60e2a0e6e7c2c3b883
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/693999
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: David Chase <drchase@google.com>
2025-08-07 10:21:04 -07:00
Daniel McCarney b999374650 acme: fix pebble subprocess output data race
Wait for process completion before reading stdout/stderr buffers
to eliminate race between I/O Go routines and test cleanup.

Updates golang/go#74437

Cq-Include-Trybots: luci.golang.try:x_crypto-gotip-linux-amd64-longtest-race
Change-Id: I2e650c04db5be0d7a1e858ce40e25f13ad12223c
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/693596
Auto-Submit: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-08-06 13:33:03 -07:00
Mateusz Poliwczak c247dead11 x509roots/fallback: store bundle certs directly in DER
goos: linux
goarch: amd64
pkg: golang.org/x/crypto/x509roots/fallback
cpu: AMD Ryzen 5 4600G with Radeon Graphics
            │ /tmp/before │             /tmp/after              │
            │   sec/op    │   sec/op     vs base                │
InitTime-12   1.726m ± 0%   1.101m ± 1%  -36.20% (p=0.000 n=30)

            │  /tmp/before  │              /tmp/after              │
            │     B/op      │     B/op      vs base                │
InitTime-12   1178.2Ki ± 0%   779.8Ki ± 0%  -33.81% (p=0.000 n=30)

            │ /tmp/before │             /tmp/after             │
            │  allocs/op  │  allocs/op   vs base               │
InitTime-12   11.35k ± 0%   10.64k ± 0%  -6.32% (p=0.000 n=30)

Updates golang/go#73691

Change-Id: Ic33f2fdfc65001c41afeb3b6af8a383288d10de6
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/676217
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Mark Freeman <mark@golang.org>
2025-08-03 12:47:17 -07:00
Daniel McCarney 1fda73153f acme: increase pebble test waitForServer attempts
In CI it seems that occasionally we can't connect to the test servers
within 10 tries, and the test flakes. Let's give the process more
attempts.

Updates golang/go#74437

Change-Id: I74d6cea83468a3a572ec4b52ff7314c778c664cf
Cq-Include-Trybots: luci.golang.try:x_crypto-gotip-linux-amd64-longtest
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/692075
Auto-Submit: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Mark Freeman <mark@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-08-01 08:44:22 -07:00
Gopher Robot 1b4c3d2e8c x509roots/fallback: update bundle
This is an automated CL which updates the NSS root bundle.

[git-generate]
go generate ./x509roots

Change-Id: Ib30b702d41dedacce835628a9dab456098be0703
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/687895
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
2025-07-30 16:29:44 -07:00
Daniel McCarney b903b535d3 acme: capture pebble test subprocess stdout/stderr
When spawning the pebble and pebble-challtestserv processes redirect
stdout/stderr to bytes.Buffer instances and print their content at test
end as appropriate.

The stdout/stderr content for each process is printed if the test
failed, or if testing is being done in verbose mode. Otherwise the
output is swallowed.

This makes debugging test failures much easier as output from the
subprocesses from independent tests isn't intermingled.

Updates golang/go#74437

Cq-Include-Trybots: luci.golang.try:x_crypto-gotip-linux-amd64-longtest
Change-Id: Ia79a3609ce3522ef6248442de247554c39367162
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/686935
Auto-Submit: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Carlos Amedee <carlos@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-07-11 12:27:10 -07:00
Gopher Robot 459a9db11b go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I3a89b1890ad2f7d2b2c23e1efce60c19e43dd381
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/687017
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: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: David Chase <drchase@google.com>
2025-07-10 10:21:43 -07:00
Nicola Murino 74e709ad8a ssh: add AlgorithmNegotiationError
Fixes golang/go#61536

Change-Id: Id38cc6d46879dbe2bdea04dec061596387ec6cfe
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/559056
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: David Chase <drchase@google.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
2025-07-09 08:43:26 -07:00
Daniel McCarney b3790b8d91 acme: fix TLSALPN01ChallengeCert for IP address identifiers
When creating a TLS-ALPN-01 challenge response certificate for an IP
address identifier we need to configure the template IPAddresses field,
not the DNSNames/Subject.CommonName.

Along the way we can do some small tidying:
* Updating the draft TLS-ALPN-01 reference to the finalized RFC
* Adding a reference to the IP address identifier ACME RFC
* Adding a mention of the form the challenge validation request's SNI
  will take when verifying an IP address identifier
* Tidying the private tlsChallengeCert() function to take a single
  identifier as arg since the only call-sites provide singular values
  since the removal of the TLS-SNI-[01|02] challenge helpers.

This allows enabling an IP address identifier in the Pebble integration
tests that otherwise caused a validation failure for TLS-ALPN-01
challenge types because the IP address was used as a DNS SAN.

Updates golang/go#73914

Cq-Include-Trybots: luci.golang.try:x_crypto-gotip-linux-amd64-longtest
Change-Id: Ic671e41b585f424f821db65206c7ffcc6dd386a0
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/677576
Reviewed-by: Ian Stapleton Cordasco <graffatcolmingov@gmail.com>
Auto-Submit: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2025-06-30 12:50:50 -07:00
Daniel McCarney 1dc4269656 acme: add Pebble integration testing
This commit adds integration test coverage for a complete TLS-ALPN-01
and HTTP-01 based issuance flow.

For each tested challenge type we:

* Spin up a pebble/pebble-challtestsrv environment
* Spin up a small challenge response server
* Create an ACME account
* Create an order for multiple DNS type identifiers
* Provision challenge responses based on the challenge type under test
* Wait for the order to become ready for issuance
* Finalize the order, issuing a certificate
* Check the newly issued certificate chain validates with the Pebble
  trust anchor, and that the certificate is valid for each of the names
  from our initial order

These tests are skipped in short mode (Pebble has variable delays for
validation requests).

The Pebble source is fetched through the Go module proxy (unless
a local directory is specified to aid development), similar to how the
stdlib crypto packages fetch BoGo tooling.

More test coverage for various other parts of the protocol (key
rollover, account/authz deactivation, revocation, etc) can be added as
follow-up work now that the groundwork for integration testing is laid.

Fixes golang/go#73914

Cq-Include-Trybots: luci.golang.try:x_crypto-gotip-linux-amd64-longtest
Change-Id: I4e79f4858f31ef290a0c91d345e15fbdc510e9ab
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/677575
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: Ian Stapleton Cordasco <graffatcolmingov@gmail.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-06-30 09:51:57 -07:00
qiulaidongfeng 97bf787255 blake2b: implement hash.XOF
Fixes golang/go#69518

Change-Id: Id9989ac9b28262df77017e97f985f67c1571c3ce
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/644255
Reviewed-by: Austin Clements <austin@google.com>
Auto-Submit: Austin Clements <austin@google.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-06-30 09:39:26 -07:00
Gopher Robot 952517d181 x509roots/fallback: update bundle
This is an automated CL which updates the NSS root bundle.

[git-generate]
go generate ./x509roots

Change-Id: Icb71f9f7c509dc6f49ad4385aa287bd6a8966523
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/681915
Auto-Submit: Gopher Robot <gobot@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2025-06-30 09:08:05 -07:00
Nicola Murino c6fce02826 ssh: refuse to parse certificates that use a certificate as signing key
According to draft-miller-ssh-cert-01, Section 2.1.1, certificates with
certificate keys as signature keys are invalid

Change-Id: I474524ea444deb78f2fa7c2682e47c0fd057f0b8
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/678716
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: David Chase <drchase@google.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
2025-06-30 09:02:50 -07:00
Nicola Murino 0ae49b8145 ssh: reject certificate keys used as signature keys for SSH certs
As specified in draft-miller-ssh-cert-01, Section 2.1.1:
Implementations MUST NOT accept certificate keys as CA keys.

Change-Id: I2e559a8a58b7bceccd0d8c6b80803abdbe281067
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/678715
Reviewed-by: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: David Chase <drchase@google.com>
2025-06-30 09:02:45 -07:00
Nicola Murino 3bf9d2afd4 ssh/test: skip KEX test if unsupported by system SSH client
Skip the key exchange test when using the system's ssh CLI if the
required KEX algorithm (e.g., mlkem768x25519-sha256) is not supported.
This is determined by running ssh -Q kex and checking for the presence
of the target algorithm.
Prevents false test failures in CI environments with older or limited
SSH implementations.

Cq-Include-Trybots: luci.golang.try:x_crypto-gotip-darwin-amd64-longtest,x_crypto-gotip-linux-amd64-longtest,x_crypto-gotip-windows-amd64-longtest
Change-Id: I3fac703ec70559e18b30d5fff88274335a7c3952
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/679195
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
2025-06-05 10:42:09 -07:00
Gopher Robot 9bab96736c go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: Icbe0bf922207aefa5ee047a35dfb71843ec75306
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/679135
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
2025-06-05 08:51:54 -07:00
Mateusz Poliwczak 4f9f0ca9fc x509roots/fallback: add init time benchmark
goos: linux
goarch: amd64
pkg: golang.org/x/crypto/x509roots/fallback
cpu: AMD Ryzen 5 4600G with Radeon Graphics
            │ /tmp/before │
            │   sec/op    │
InitTime-12   1.726m ± 0%

            │ /tmp/before  │
            │     B/op     │
InitTime-12   1.151Mi ± 0%

            │ /tmp/before │
            │  allocs/op  │
InitTime-12   11.35k ± 0%

For golang/go#73691

Change-Id: Ic932bd7835e50dd5c6adbdf684644afa49bddebc
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/676216
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Sean Liao <sean@liao.dev>
Auto-Submit: Sean Liao <sean@liao.dev>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
2025-05-31 02:59:11 -07:00
Mateusz Poliwczak eac7cf0d78 x509roots/fallback: move parsing code to a non-generated file
For golang/go#73691

Change-Id: I3e2b09055c39286d863fe70ca3bd72a839e25d0a
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/676215
Reviewed-by: Michael Knyszek <mknyszek@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Sean Liao <sean@liao.dev>
Auto-Submit: Sean Liao <sean@liao.dev>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-05-31 02:59:06 -07:00
Daniel McCarney 18228cd6f1 acme: return err from deprecated TLS-SNI-[01|02] functions
The TLSSNI01ChallengeCert and TLSSNI02ChallengeCert functions have been
marked deprecated since 2022. The package documentation indicates
pre-RFC 8555 functionality is retained for compilation success, but will
return errors. This commit makes these two deprecated functions match
that description.

No meaningful support for these draft standard challenge types exists
in the ACME ecosystem, and they are insecure for use in shared hosting
environments.

Change-Id: I1c17980a0630092c70eb971b3453a0f115834be0
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/676835
Auto-Submit: Daniel McCarney <daniel@binaryparadox.net>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
2025-05-29 10:16:04 -07:00
Daniel McCarney 73f6362471 acme: remove dead code
The private encodePem() and unique() functions under the acme package
had no call-sites and so can be removed.

Change-Id: Ic617392e7cc9b9e795456626a623ba02df108694
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/676875
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
2025-05-28 10:23:52 -07:00
Nicola Murino ebc8e46315 ssh: add server side support for Diffie Hellman Group Exchange
We add this support for the following reasons:

- We are planning to expose recommended (secure) vs. supported (works,
  not necessarily recommended) algorithms. The DHGEX kex is currently
  only exposed as a client-side kex. To simplify the calling convention
  for this follow-on, we expose the server side too.
- Some clients are quite inflexible with reference to kex algorithms
  choice, for example they offer:

  diffie-hellman-group-exchange-sha256, diffie-hellman-group-exchange-sha1,
  diffie-hellman-group14-sha1, diffie-hellman-group1-sha1

  therefore DHGEX helps interoperability.

We do not recommend the DHGEX kex as a whole:

- the negotiation requires an extra round trip
- the server must generate parameters (slow) or hardcode them, which
  defeats the security benefit over traditional DH.

In this implementation we hardcode sending Oakley Group 14, Oakley
Group 15 or Oakley Group 16 based on the requested max size.

Users that are concerned with security of classical DH kex should
migrate to kex based on EC or Ed25519.

Fixes golang/go#54743

Change-Id: I127822e90efc36821af4aca679931f40a2023021
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/532415
Reviewed-by: Michael Knyszek <mknyszek@google.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Han-Wen Nienhuys <hanwen@google.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-05-15 10:47:05 -07:00
Nicola Murino e944286e33 ssh: expose negotiated algorithms
Fixes golang/go#58523
Fixes golang/go#46638

Change-Id: Ic64bd2fdd6e9ec96acac3ed4be842e2fbb15231d
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/538235
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-05-15 10:44:04 -07:00
Nicola Murino 78a1fd7893 ssh: automatically add curve25519-sha256@libssh.org KEX alias
If the key exchange method curve25519-sha256 is configured, automatically
add the curve25519-sha256@libssh.org alias to ensure compatibility with
OpenSSH versions up to 7.2, which recognize only the older vendor-specific
name.

Change-Id: If50ab2c49179db949ba1b986f7bb0e153cc7f897
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/669716
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-05-15 10:43:39 -07:00
Nicola Murino ac58737d25 ssh: export supported algorithms
Fixes golang/go#61537

Change-Id: If3478121e3ae445391e3faeceeb889d75e9e3214
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/531935
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
2025-05-15 10:43:30 -07:00
redwrasse 9dbbcf002b bcrypt: update InvalidCostError message to describe cost range inclusive
Change InvalidCostError string to explicitly state cost bounds
range as inclusive, rather than using parentheses that might
imply an exclusive range.

Change-Id: Ie5e7d53ef4217c8560e6a7fe23e3d65ecc24a2a3
GitHub-Last-Rev: b49002b6b2cff0939858553a28e3f255bde397b6
GitHub-Pull-Request: golang/crypto#300
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/609455
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
2025-05-12 11:46:18 -07:00
Gopher Robot 9f6bf8449a x509roots/fallback: update bundle
This is an automated CL which updates the NSS root bundle.

[git-generate]
go generate ./x509roots

Change-Id: If1970af8da68ead595dc3fa7dd79a8555a5f09c5
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/668576
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
2025-05-12 08:41:11 -07:00
Gopher Robot aae6e61070 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I06b2bb01f1557af02a8bf172ee85973695506906
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/670095
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: David Chase <drchase@google.com>
2025-05-05 11:47:08 -07:00
Nicola Murino 9c1aa6af88 ssh/test: reset the random source before capturing a recording
If a recording file exists but is invalid for any reason, the random
source may have already been used, resulting in a recording that
cannot be replayed.

Change-Id: Ib81aaf163f5783fede2c14a0ac10a8d2af6019c6
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/664917
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
2025-04-18 04:19:36 -07:00
Nicola Murino 88199028d7 ssh/test: enable Diffie-Hellman key exchange algorithms
starting with OpenSSH 10, all Diffie-Hellman key exchange algorithms
are disabled by default. To generate recordings, we must explicitly
enable them.

Change-Id: Icfbf46b30478f36d7040991e0f6324b9b4766aaf
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/665115
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
2025-04-18 04:18:34 -07:00
Ian Stapleton Cordasco 3f311e442e acme: return error from pre-authorization when unsupported
Check the directory's AuthzURL to see if the server supports
pre-authorization. If it's empty, then the server is not advertising
support and we can encounter other bugs. Better to return early and give
a clear error to the caller.

From https://www.rfc-editor.org/rfc/rfc8555#section-7.4.1

    If a CA wishes to allow pre-authorization within ACME, it can offer a
    "new authorization" resource in its directory by adding the field
    "newAuthz" with a URL for the newAuthz resource.

Fixes golang/go#40839

Change-Id: Id3e92e8e2ae3c57285183d37544dd59b4988b3be
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/661675
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
2025-04-17 11:16:57 -07:00
Nicola Murino 1f7c62cd66 ssh/test: skip unsupported tests on js/wasm
This fixes the build on the js/wasm builder.

Change-Id: Icd891cd38b9da07279b9afaa168f7c64c81e13fe
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/665095
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2025-04-16 08:28:17 -07:00
Alberto Bertogli a5f804889e acme/autocert: use standard functions to pick the cache directory
acme/autocert currently has ad-hoc logic to find a reasonable default
for a cache directory.

Since that logic was written (in 2017), new functions were added to the
os package to provide that functionality (in Go 1.13, 2019-09):
`os.UserCacheDir` and `os.UserHomeDir`.

This patch replaces the ad-hoc logic with a call to `os.UserCacheDir`.

The fallback to `/` is kept, since it may be relied upon in some
environments.

Change-Id: I3bf692ca670b87bf3d329e5d3684eee15ed374aa
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/440195
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Sean Liao <sean@liao.dev>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Sean Liao <sean@liao.dev>
2025-04-16 08:16:13 -07:00
Michael Pratt 958cde86ef Revert "chacha20: add loong64 SIMD implementation"
This reverts CL 636257.

Reason for revert: Does not build on 1.23 or 1.24

For golang/go#73354.

Change-Id: Ie28d5c45930a8eacd5cabed64390ef674b3fb446
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/665536
Reviewed-by: abner chenc <chenguoqi@loongson.cn>
Auto-Submit: Michael Pratt <mpratt@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-04-16 06:50:31 -07:00
Michael Pratt 51f005cfd4 Revert "salsa20: add loong64 SIMD implementation"
This reverts CL 663375.

Reason for revert: Does not build on 1.23 or 1.24

For golang/go#73354.

Change-Id: I251d598423b83c01cc2e04ddf6f49ae14095fa7c
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/665535
Auto-Submit: Michael Pratt <mpratt@google.com>
Reviewed-by: abner chenc <chenguoqi@loongson.cn>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-04-16 06:50:29 -07:00
Michael Pratt 7c358664da Revert "argon2: add loong64 SIMD implementation"
This reverts CL 657795.

Reason for revert: Does not build on 1.23 or 1.24

For golang/go#73354.

Change-Id: I69498f24b57bd6650c9d1f4c755922cfaaba4a84
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/665555
Reviewed-by: abner chenc <chenguoqi@loongson.cn>
Auto-Submit: Michael Pratt <mpratt@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2025-04-16 06:49:50 -07:00
Michael Pratt 0091fc8e7c Revert "blake2s: add loong64 SIMD implementation"
This reverts CL 661215.

Reason for revert: Does not build on 1.23 or 1.24

Fixes #73354.

Change-Id: I90abd8a3dabf5c0d9fd1062de3ba3e78ecb2f2e8
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/664796
Reviewed-by: Carlos Amedee <carlos@golang.org>
Auto-Submit: Michael Pratt <mpratt@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-04-14 04:06:44 -07:00
Xiaolin Zhao 388684e50b argon2: add loong64 SIMD implementation
The performance gains on Loongson 3A6000 and 3A5000 are as follows:

goos: linux
goarch: loong64
pkg: golang.org/x/crypto/argon2
cpu: Loongson-3A6000-HV @ 2500.00MHz
                                             |  bench.old   |              bench.new              |
                                             |    sec/op    |   sec/op     vs base                |
Argon2i/_Time:_3_Memory:_32_MB,_Threads:_1     131.23m ± 0%   67.56m ± 1%  -48.52% (p=0.000 n=10)
Argon2i/_Time:_4_Memory:_32_MB,_Threads:_1     171.28m ± 2%   90.20m ± 0%  -47.34% (p=0.000 n=10)
Argon2i/_Time:_5_Memory:_32_MB,_Threads:_1      213.3m ± 0%   112.6m ± 0%  -47.21% (p=0.000 n=10)
Argon2i/_Time:_3_Memory:_64_MB,_Threads:_4      269.5m ± 0%   147.2m ± 0%  -45.37% (p=0.000 n=10)
Argon2i/_Time:_4_Memory:_64_MB,_Threads:_4      357.7m ± 0%   195.4m ± 0%  -45.36% (p=0.000 n=10)
Argon2i/_Time:_5_Memory:_64_MB,_Threads:_4      449.8m ± 0%   243.8m ± 0%  -45.79% (p=0.000 n=10)
Argon2d/_Time:_3,_Memory:_32_MB,_Threads:_1    126.56m ± 0%   67.43m ± 0%  -46.72% (p=0.000 n=10)
Argon2d/_Time:_4,_Memory:_32_MB,_Threads:_1    168.57m ± 0%   90.04m ± 0%  -46.58% (p=0.000 n=10)
Argon2d/_Time:_5,_Memory:_32_MB,_Threads:_1     210.5m ± 0%   112.7m ± 0%  -46.45% (p=0.000 n=10)
Argon2d/_Time:_3,_Memory:_64_MB,_Threads:_4     264.8m ± 0%   145.0m ± 1%  -45.23% (p=0.000 n=10)
Argon2d/_Time:_4,_Memory:_64_MB,_Threads:_4     353.8m ± 0%   193.7m ± 0%  -45.26% (p=0.000 n=10)
Argon2d/_Time:_5,_Memory:_64_MB,_Threads:_4     444.4m ± 0%   242.3m ± 0%  -45.49% (p=0.000 n=10)
Argon2id/_Time:_3,_Memory:_32_MB,_Threads:_1   126.89m ± 0%   66.62m ± 0%  -47.50% (p=0.000 n=10)
Argon2id/_Time:_4,_Memory:_32_MB,_Threads:_1   169.02m ± 0%   89.07m ± 0%  -47.30% (p=0.000 n=10)
Argon2id/_Time:_5,_Memory:_32_MB,_Threads:_1    210.7m ± 0%   111.0m ± 0%  -47.34% (p=0.000 n=10)
Argon2id/_Time:_3,_Memory:_64_MB,_Threads:_4    267.6m ± 1%   145.8m ± 0%  -45.51% (p=0.000 n=10)
Argon2id/_Time:_4,_Memory:_64_MB,_Threads:_4    355.1m ± 0%   194.1m ± 0%  -45.34% (p=0.000 n=10)
Argon2id/_Time:_5,_Memory:_64_MB,_Threads:_4    443.6m ± 0%   242.5m ± 0%  -45.33% (p=0.000 n=10)
geomean                                         240.8m        129.3m       -46.32%

goos: linux
goarch: loong64
pkg: golang.org/x/crypto/argon2
cpu: Loongson-3A5000 @ 2500.00MHz
                                             |  bench.old  |              bench.new              |
                                             |   sec/op    |   sec/op     vs base                |
Argon2i/_Time:_3_Memory:_32_MB,_Threads:_1     209.9m ± 1%   109.7m ± 2%  -47.75% (p=0.000 n=10)
Argon2i/_Time:_4_Memory:_32_MB,_Threads:_1     278.1m ± 0%   143.7m ± 0%  -48.34% (p=0.000 n=10)
Argon2i/_Time:_5_Memory:_32_MB,_Threads:_1     346.7m ± 0%   178.1m ± 0%  -48.63% (p=0.000 n=10)
Argon2i/_Time:_3_Memory:_64_MB,_Threads:_4     455.3m ± 0%   240.8m ± 0%  -47.12% (p=0.000 n=10)
Argon2i/_Time:_4_Memory:_64_MB,_Threads:_4     604.6m ± 0%   317.7m ± 0%  -47.45% (p=0.000 n=10)
Argon2i/_Time:_5_Memory:_64_MB,_Threads:_4     754.8m ± 0%   395.4m ± 0%  -47.61% (p=0.000 n=10)
Argon2d/_Time:_3,_Memory:_32_MB,_Threads:_1    206.9m ± 1%   107.6m ± 0%  -48.00% (p=0.000 n=10)
Argon2d/_Time:_4,_Memory:_32_MB,_Threads:_1    274.3m ± 0%   141.8m ± 1%  -48.32% (p=0.000 n=10)
Argon2d/_Time:_5,_Memory:_32_MB,_Threads:_1    342.4m ± 0%   175.6m ± 0%  -48.71% (p=0.000 n=10)
Argon2d/_Time:_3,_Memory:_64_MB,_Threads:_4    450.2m ± 0%   237.9m ± 0%  -47.15% (p=0.000 n=10)
Argon2d/_Time:_4,_Memory:_64_MB,_Threads:_4    597.7m ± 0%   314.0m ± 0%  -47.46% (p=0.000 n=10)
Argon2d/_Time:_5,_Memory:_64_MB,_Threads:_4    745.8m ± 0%   390.7m ± 1%  -47.61% (p=0.000 n=10)
Argon2id/_Time:_3,_Memory:_32_MB,_Threads:_1   207.6m ± 0%   107.9m ± 0%  -48.05% (p=0.000 n=10)
Argon2id/_Time:_4,_Memory:_32_MB,_Threads:_1   275.0m ± 0%   142.0m ± 0%  -48.34% (p=0.000 n=10)
Argon2id/_Time:_5,_Memory:_32_MB,_Threads:_1   342.9m ± 1%   176.0m ± 0%  -48.66% (p=0.000 n=10)
Argon2id/_Time:_3,_Memory:_64_MB,_Threads:_4   450.6m ± 1%   238.5m ± 0%  -47.07% (p=0.000 n=10)
Argon2id/_Time:_4,_Memory:_64_MB,_Threads:_4   598.5m ± 1%   314.6m ± 0%  -47.44% (p=0.000 n=10)
Argon2id/_Time:_5,_Memory:_64_MB,_Threads:_4   746.4m ± 0%   391.0m ± 0%  -47.61% (p=0.000 n=10)
geomean                                        398.6m        207.9m       -47.86%

Change-Id: Iaa9d134d68dd2f0972fc5768d7e66f7b1ff0ebd3
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/657795
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: abner chenc <chenguoqi@loongson.cn>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
2025-04-13 20:23:35 -07:00
Xiaolin Zhao 953e809589 chacha20: add loong64 SIMD implementation
The performance of chacha20 has been greatly improved on 3A6000 and 3A5000.

goos: linux
goarch: loong64
pkg: golang.org/x/crypto/chacha20
cpu: Loongson-3A6000 @ 2500.00MHz
                 |  bench.old   |              bench.new              |
                 |    sec/op    |   sec/op     vs base                |
ChaCha20/64         171.9n ± 0%   159.3n ± 0%   -7.33% (p=0.000 n=20)
ChaCha20/256        592.2n ± 0%   142.8n ± 0%  -75.89% (p=0.000 n=20)
ChaCha20/10x25      981.5n ± 0%   518.8n ± 0%  -47.14% (p=0.000 n=20)
ChaCha20/4096       8.991µ ± 0%   1.732µ ± 0%  -80.74% (p=0.000 n=20)
ChaCha20/100x40    10.651µ ± 0%   5.135µ ± 0%  -51.79% (p=0.000 n=20)
ChaCha20/65536     143.43µ ± 0%   28.76µ ± 0%  -79.95% (p=0.000 n=20)
ChaCha20/1000x65   146.17µ ± 0%   37.13µ ± 0%  -74.60% (p=0.000 n=20)
geomean             5.721µ        1.962µ       -65.70%

                 |  bench.old   |               bench.new                |
                 |     B/s      |      B/s       vs base                 |
ChaCha20/64        355.1Mi ± 0%    383.1Mi ± 0%    +7.89% (p=0.000 n=20)
ChaCha20/256       412.2Mi ± 0%   1710.2Mi ± 0%  +314.86% (p=0.000 n=20)
ChaCha20/10x25     242.9Mi ± 0%    459.6Mi ± 0%   +89.19% (p=0.000 n=20)
ChaCha20/4096      434.5Mi ± 0%   2255.8Mi ± 0%  +419.22% (p=0.000 n=20)
ChaCha20/100x40    358.1Mi ± 0%    742.9Mi ± 0%  +107.44% (p=0.000 n=20)
ChaCha20/65536     435.8Mi ± 0%   2173.2Mi ± 0%  +398.72% (p=0.000 n=20)
ChaCha20/1000x65   424.1Mi ± 0%   1669.4Mi ± 0%  +293.64% (p=0.000 n=20)
geomean            373.9Mi         1.065Gi       +191.55%

goos: linux
goarch: loong64
pkg: golang.org/x/crypto/chacha20
cpu: Loongson-3A5000 @ 2500.00MHz
                 |  bench.old   |              bench.new              |
                 |    sec/op    |   sec/op     vs base                |
ChaCha20/64         234.5n ± 0%   295.8n ± 0%  +26.14% (p=0.000 n=20)
ChaCha20/256        782.0n ± 0%   274.6n ± 0%  -64.88% (p=0.000 n=20)
ChaCha20/10x25     1340.0n ± 0%   752.7n ± 0%  -43.83% (p=0.000 n=20)
ChaCha20/4096      11.744µ ± 0%   3.455µ ± 0%  -70.58% (p=0.000 n=20)
ChaCha20/100x40    14.151µ ± 0%   7.435µ ± 0%  -47.46% (p=0.000 n=20)
ChaCha20/65536     188.05µ ± 0%   54.33µ ± 0%  -71.11% (p=0.000 n=20)
ChaCha20/1000x65   191.44µ ± 0%   66.29µ ± 0%  -65.37% (p=0.000 n=20)
geomean             7.604µ        3.436µ       -54.81%

                 |  bench.old   |               bench.new                |
                 |     B/s      |      B/s       vs base                 |
ChaCha20/64        260.3Mi ± 0%    206.3Mi ± 0%   -20.73% (p=0.000 n=20)
ChaCha20/256       312.2Mi ± 0%    888.9Mi ± 0%  +184.75% (p=0.000 n=20)
ChaCha20/10x25     177.9Mi ± 0%    316.8Mi ± 0%   +78.08% (p=0.000 n=20)
ChaCha20/4096      332.6Mi ± 0%   1130.8Mi ± 0%  +239.95% (p=0.000 n=20)
ChaCha20/100x40    269.6Mi ± 0%    513.1Mi ± 0%   +90.34% (p=0.000 n=20)
ChaCha20/65536     332.4Mi ± 0%   1150.5Mi ± 0%  +246.16% (p=0.000 n=20)
ChaCha20/1000x65   323.8Mi ± 0%    935.2Mi ± 0%  +188.81% (p=0.000 n=20)
geomean            281.3Mi         622.6Mi       +121.31%

Change-Id: I5386f2029122076c1d22a04610567e3df23877cd
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/636257
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: abner chenc <chenguoqi@loongson.cn>
Reviewed-by: Carlos Amedee <carlos@golang.org>
2025-04-13 20:23:16 -07:00
Xiaolin Zhao 18f770732f salsa20: add loong64 SIMD implementation
The performance gains on Loongson 3A6000 and 3A5000 are as follows:

goos: linux
goarch: loong64
pkg: golang.org/x/crypto/salsa20
cpu: Loongson-3A6000-HV @ 2500.00MHz
      |  bench.old   |              bench.new              |
      |    sec/op    |   sec/op     vs base                |
XOR1K   3175.0n ± 0%   435.4n ± 0%  -86.29% (p=0.000 n=20)

      |  bench.old   |               bench.new                |
      |     B/s      |      B/s       vs base                 |
XOR1K   307.6Mi ± 0%   2242.7Mi ± 0%  +629.13% (p=0.000 n=20)

goos: linux
goarch: loong64
pkg: golang.org/x/crypto/salsa20
cpu: Loongson-3A5000 @ 2500.00MHz
      |  bench.old   |              bench.new              |
      |    sec/op    |   sec/op     vs base                |
XOR1K   4125.0n ± 0%   864.0n ± 0%  -79.05% (p=0.000 n=20)

      |  bench.old   |               bench.new                |
      |     B/s      |      B/s       vs base                 |
XOR1K   236.7Mi ± 0%   1130.3Mi ± 0%  +377.41% (p=0.000 n=20)

Change-Id: Ib37f603e6654f1e3837985fad4b6dee10b5af993
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/663375
Reviewed-by: Carlos Amedee <carlos@golang.org>
Reviewed-by: abner chenc <chenguoqi@loongson.cn>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Carlos Amedee <carlos@golang.org>
2025-04-11 13:55:20 -07:00
Xiaolin Zhao 2ebaafcdf5 blake2s: add loong64 SIMD implementation
The performance gains on Loongson 3A6000 and 3A5000 are as follows:

goos: linux
goarch: loong64
pkg: golang.org/x/crypto/blake2s
cpu: Loongson-3A6000-HV @ 2500.00MHz
        |  bench.old  |              bench.new              |
        |   sec/op    |   sec/op     vs base                |
Write64   277.8n ± 0%   113.5n ± 0%  -59.14% (p=0.000 n=10)
Write1K   4.246µ ± 0%   1.736µ ± 0%  -59.11% (p=0.000 n=10)
Sum64     289.9n ± 0%   137.7n ± 0%  -52.51% (p=0.000 n=10)
Sum1K     4.265µ ± 0%   1.758µ ± 0%  -58.78% (p=0.000 n=10)
geomean   1.099µ        467.3n       -57.48%

        |  bench.old   |               bench.new               |
        |     B/s      |     B/s       vs base                 |
Write64   219.7Mi ± 0%   537.9Mi ± 0%  +144.86% (p=0.000 n=10)
Write1K   230.0Mi ± 0%   562.6Mi ± 0%  +144.62% (p=0.000 n=10)
Sum64     210.5Mi ± 0%   443.3Mi ± 0%  +110.59% (p=0.000 n=10)
Sum1K     229.0Mi ± 0%   555.5Mi ± 0%  +142.64% (p=0.000 n=10)
geomean   222.1Mi        522.5Mi       +135.21%

goos: linux
goarch: loong64
pkg: golang.org/x/crypto/blake2s
cpu: Loongson-3A5000 @ 2500.00MHz
        |  bench.old  |              bench.new              |
        |   sec/op    |   sec/op     vs base                |
Write64   373.8n ± 0%   175.0n ± 0%  -53.18% (p=0.000 n=10)
Write1K   5.763µ ± 0%   2.595µ ± 0%  -54.97% (p=0.000 n=10)
Sum64     397.8n ± 0%   205.7n ± 0%  -48.29% (p=0.000 n=10)
Sum1K     5.787µ ± 0%   2.627µ ± 0%  -54.61% (p=0.000 n=10)
geomean   1.492µ        703.8n       -52.83%

        |  bench.old   |               bench.new               |
        |     B/s      |     B/s       vs base                 |
Write64   163.3Mi ± 0%   348.9Mi ± 0%  +113.62% (p=0.000 n=10)
Write1K   169.5Mi ± 0%   376.3Mi ± 0%  +122.09% (p=0.000 n=10)
Sum64     153.4Mi ± 0%   296.7Mi ± 0%   +93.37% (p=0.000 n=10)
Sum1K     168.7Mi ± 0%   371.8Mi ± 0%  +120.33% (p=0.000 n=10)
geomean   163.6Mi        346.9Mi       +112.03%

Change-Id: Id91ffbefc538bce294875d72e6cde72fea43afbf
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/661215
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
Auto-Submit: Carlos Amedee <carlos@golang.org>
Reviewed-by: abner chenc <chenguoqi@loongson.cn>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-04-11 13:55:16 -07:00
cuishuang 4bc0711281 acme: use built-in max/min to simplify the code
Change-Id: I6ba8d07b9e53b01f25f4c1c8eac629aaa47de3a1
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/664836
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2025-04-11 09:06:14 -07:00
Nicola MurinoandDamien Miller c96bba2ced ssh: add mlkem768x25519-sha256 Key Exchange algorithm
mlkem768x25519-sha256 requires the crypto/mlkem package introduced in
Go 1.24.

Thanks to Damien Miller for posting an early version to the OpenSSH
mailing list.

Co-authored-by: Damien Miller <djm@mindrot.org>
Change-Id: I4235cf906903524a9a97283834cc8f43b5f76f91
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/646075
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-04-11 07:39:49 -07:00
Nicola Murino 6b13eef40b ssh: add integration tests against a reference implementation
As in crypto/tls, we record the connection against a reference
implementation, OpenSSH in our case, and run part of our integration
tests by replaying these recorded SSH connections.

Change-Id: If042b5f650b267bd3ede34a05ec3a6fa6d1a86b3
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/644436
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
2025-04-11 07:29:06 -07:00
Gopher Robot 959f8f3db0 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I1e9480e5897a08cac746309acdc8bbdf0bce8060
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/663256
Reviewed-by: David Chase <drchase@google.com>
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>
2025-04-06 09:04:20 -07:00
Nicola Murino 769bcd6997 ssh: use the configured rand in kex init
Change-Id: I4f89c395886b9dd07b584d1fcf1a0f2df215b91b
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/644435
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Carlos Amedee <carlos@golang.org>
Reviewed-by: Carlos Amedee <carlos@golang.org>
2025-04-03 13:05:29 -07:00
Simon Josefsson d0a798f774 cryptobyte: fix typo 'octects' into 'octets' for asn1.go
This typo ends up into lots of executables that trigger 'codespell'-style linter checks.

Change-Id: I2a7e3a6597272ca7c97ebddc54c5eef4cb5cab88
GitHub-Last-Rev: e42f734f00aa575030b72dd1e328d2acefb02625
GitHub-Pull-Request: golang/crypto#310
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/646375
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2025-03-17 08:22:34 -07:00
Mateusz Poliwczak acbcbef23f acme: remove unnecessary []byte conversion
Change-Id: Iddbe6bcb7a5487678c48df65903571b4625fc9f9
GitHub-Last-Rev: 2552a8d99c7472f029d7da270fa814398793b564
GitHub-Pull-Request: golang/crypto#243
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/456438
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Sean Liao <sean@liao.dev>
Auto-Submit: Sean Liao <sean@liao.dev>
2025-03-17 08:22:03 -07:00
Roland Shoemaker 376eb14006 x509roots: support constrained roots
Adds support for roots with the distrust-after bit set. The constraint
function construction is a little funky, but I couldn't think of an
obvious better way to do it.

Fixes golang/go#70777
Fixes golang/go#70623

Change-Id: I780f866416b626360eaee9368185768da7bc75ef
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/652996
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-03-13 16:44:06 -07:00
Xiaolin Zhao b369b723c8 crypto/internal/poly1305: implement function update in assembly on loong64
The performance improvements on Loongson-3A5000 and Loongson-3A6000 are as follows:

goos: linux
goarch: loong64
pkg: golang.org/x/crypto/internal/poly1305
cpu: Loongson-3A5000 @ 2500.00MHz
                 |  bench.old   |              bench.new              |
                 |    sec/op    |   sec/op     vs base                |
64                  122.8n ± 0%   100.0n ± 0%  -18.57% (p=0.000 n=10)
1K                 1152.0n ± 0%   732.2n ± 0%  -36.44% (p=0.000 n=10)
2M                  2.356m ± 0%   1.443m ± 0%  -38.74% (p=0.000 n=10)
64Unaligned         122.7n ± 0%   101.5n ± 0%  -17.24% (p=0.000 n=10)
1KUnaligned        1152.0n ± 0%   745.4n ± 0%  -35.30% (p=0.000 n=10)
2MUnaligned         2.336m ± 0%   1.473m ± 0%  -36.94% (p=0.000 n=10)
Write64             77.92n ± 0%   54.88n ± 0%  -29.57% (p=0.000 n=10)
Write1K            1106.0n ± 0%   683.3n ± 0%  -38.22% (p=0.000 n=10)
Write2M             2.356m ± 0%   1.444m ± 0%  -38.72% (p=0.000 n=10)
Write64Unaligned    77.87n ± 0%   55.69n ± 0%  -28.49% (p=0.000 n=10)
Write1KUnaligned   1106.0n ± 0%   708.1n ± 0%  -35.97% (p=0.000 n=10)
Write2MUnaligned    2.335m ± 0%   1.471m ± 0%  -37.01% (p=0.000 n=10)
geomean             6.373µ        4.272µ       -32.96%

                 |  bench.old   |               bench.new               |
                 |     B/s      |      B/s       vs base                |
64                 497.1Mi ± 0%    610.3Mi ± 0%  +22.78% (p=0.000 n=10)
1K                 847.6Mi ± 0%   1333.7Mi ± 0%  +57.35% (p=0.000 n=10)
2M                 849.0Mi ± 0%   1385.9Mi ± 0%  +63.24% (p=0.000 n=10)
64Unaligned        497.4Mi ± 0%    600.9Mi ± 0%  +20.81% (p=0.000 n=10)
1KUnaligned        847.6Mi ± 0%   1310.1Mi ± 0%  +54.57% (p=0.000 n=10)
2MUnaligned        856.3Mi ± 0%   1357.9Mi ± 0%  +58.58% (p=0.000 n=10)
Write64            783.3Mi ± 0%   1112.2Mi ± 0%  +41.99% (p=0.000 n=10)
Write1K            882.8Mi ± 0%   1429.1Mi ± 0%  +61.88% (p=0.000 n=10)
Write2M            849.0Mi ± 0%   1385.4Mi ± 0%  +63.18% (p=0.000 n=10)
Write64Unaligned   783.8Mi ± 0%   1096.1Mi ± 0%  +39.85% (p=0.000 n=10)
Write1KUnaligned   882.8Mi ± 0%   1379.0Mi ± 0%  +56.20% (p=0.000 n=10)
Write2MUnaligned   856.5Mi ± 0%   1359.9Mi ± 0%  +58.76% (p=0.000 n=10)
geomean            772.2Mi         1.125Gi       +49.18%

goos: linux
goarch: loong64
pkg: golang.org/x/crypto/internal/poly1305
cpu: Loongson-3A6000-HV @ 2500.00MHz
                 |  bench.old  |              bench.new              |
                 |   sec/op    |   sec/op     vs base                |
64                 92.06n ± 0%   71.55n ± 0%  -22.28% (p=0.000 n=10)
1K                 998.4n ± 0%   607.7n ± 0%  -39.13% (p=0.000 n=10)
2M                 1.976m ± 0%   1.165m ± 0%  -41.07% (p=0.000 n=10)
64Unaligned        92.05n ± 0%   71.55n ± 0%  -22.27% (p=0.000 n=10)
1KUnaligned        998.3n ± 0%   607.6n ± 0%  -39.13% (p=0.000 n=10)
2MUnaligned        1.975m ± 0%   1.222m ± 0%  -38.11% (p=0.000 n=10)
Write64            65.24n ± 0%   45.23n ± 0%  -30.67% (p=0.000 n=10)
Write1K            970.8n ± 0%   577.6n ± 0%  -40.51% (p=0.000 n=10)
Write2M            1.965m ± 0%   1.163m ± 0%  -40.81% (p=0.000 n=10)
Write64Unaligned   65.24n ± 0%   45.24n ± 0%  -30.66% (p=0.000 n=10)
Write1KUnaligned   970.8n ± 0%   577.6n ± 0%  -40.50% (p=0.000 n=10)
Write2MUnaligned   1.965m ± 0%   1.222m ± 0%  -37.81% (p=0.000 n=10)
geomean            5.317µ        3.426µ       -35.58%

                 |   bench.old   |               bench.new               |
                 |      B/s      |      B/s       vs base                |
64                  663.0Mi ± 0%    853.1Mi ± 0%  +28.67% (p=0.000 n=10)
1K                  978.1Mi ± 0%   1606.9Mi ± 0%  +64.28% (p=0.000 n=10)
2M                 1012.0Mi ± 0%   1717.4Mi ± 0%  +69.70% (p=0.000 n=10)
64Unaligned         663.1Mi ± 0%    853.1Mi ± 0%  +28.65% (p=0.000 n=10)
1KUnaligned         978.2Mi ± 0%   1607.1Mi ± 0%  +64.29% (p=0.000 n=10)
2MUnaligned        1012.6Mi ± 0%   1636.2Mi ± 0%  +61.58% (p=0.000 n=10)
Write64             935.5Mi ± 0%   1349.3Mi ± 0%  +44.23% (p=0.000 n=10)
Write1K            1005.9Mi ± 0%   1690.9Mi ± 0%  +68.09% (p=0.000 n=10)
Write2M            1017.7Mi ± 0%   1719.5Mi ± 0%  +68.95% (p=0.000 n=10)
Write64Unaligned    935.6Mi ± 0%   1349.3Mi ± 0%  +44.22% (p=0.000 n=10)
Write1KUnaligned   1006.0Mi ± 0%   1690.9Mi ± 0%  +68.08% (p=0.000 n=10)
Write2MUnaligned   1017.7Mi ± 0%   1636.4Mi ± 0%  +60.80% (p=0.000 n=10)
geomean             925.6Mi         1.403Gi       +55.22%

Change-Id: If05a8bfc868b3e6f903ff169eed7a894af741f9b
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/638455
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
Reviewed-by: abner chenc <chenguoqi@loongson.cn>
2025-03-11 17:59:26 -07:00
Carlos A Becker 6b853fbea3 ssh/knownhosts: check more than one key
I believe this fixes https://github.com/golang/go/issues/36126 .

The problem was that it was keeping only the first known key of each
type found.
If you have a server advertising multiple keys of the same type,
you might get a missmatch key error.

Per sshd(8) man page, it should allow reapeatable hosts with
different host keys, although it don't specify anything about
hosts being from different types:

"It is permissible (but not recommended) to have several lines or
different host keys for the same names.  This will inevitably happen when
short forms of host names from different domains are put in the file.  It
is possible that the files contain conflicting information;
authentication is accepted if valid information can be found from either
file."

So, this changes knownhosts behavior to accept any of the keys for a
given host, regardless of type.

Fixes #36126

Change-Id: I3450ff954259a403f2471082d013a5f79def0e16
GitHub-Last-Rev: 361bd2bcd20348956aaf114ef159a5350397eaf4
GitHub-Pull-Request: golang/crypto#254
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/478535
Reviewed-by: Junyang Shao <shaojunyang@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
2025-03-06 10:51:46 -08:00
Gopher Robot 49bf5b80c8 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: Ieae7a2d210a65d5cd2cb7e2670d283176922c767
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/655018
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: David Chase <drchase@google.com>
2025-03-05 09:04:21 -08:00
Ilia Mirkin 24852b6b3f ssh: add decode support for banners
These banners can be printed when enabling debugHandshake, add decode
support so that they're not printed as unknown messages.

Change-Id: Ic8d56079d8225c35aac843accdbc80a642dd6249
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/650635
Reviewed-by: Junyang Shao <shaojunyang@google.com>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2025-03-03 11:16:37 -08:00
cuishuang bbc689cf5c ssh: use a more straightforward return value
Change-Id: Ie5ee95efe4924f75719087c6fe8d4867607934bf
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/653198
Reviewed-by: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
2025-02-28 12:03:19 -08:00
Nicola Murino 7292932d45 ssh: limit the size of the internal packet queue while waiting for KEX
In the SSH protocol, clients and servers execute the key exchange to
generate one-time session keys used for encryption and authentication.
The key exchange is performed initially after the connection is
established and then periodically after a configurable amount of data.
While a key exchange is in progress, we add the received packets to an
internal queue until we receive SSH_MSG_KEXINIT from the other side.
This can result in high memory usage if the other party is slow to
respond to the SSH_MSG_KEXINIT packet, or memory exhaustion if a
malicious client never responds to an SSH_MSG_KEXINIT packet during a
large file transfer.
We now limit the internal queue to 64 packets: this means 2MB with the
typical 32KB packet size.
When the internal queue is full we block further writes until the
pending key exchange is completed or there is a read or write error.

Thanks to Yuichi Watanabe for reporting this issue.

Change-Id: I1ce2214cc16e08b838d4bc346c74c72addafaeec
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/652135
Reviewed-by: Neal Patel <nealpatel@google.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-02-24 09:39:25 -08:00
Roland Shoemaker f66f74b0a4 acme/autocert: check host policy before probing the cache
Avoid unnessecary cache probes for names that don't match the host
policy.

Fixes golang/go#71199

Change-Id: I11e8465b0416e960a549b0c0d74a622026c39931
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/651296
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2025-02-21 16:31:38 -08:00
Dmitri Shuralyov b0784b7bfb x509roots/fallback: drop obsolete build constraint
Back when Go 1.20 and 1.19 were supported, the go1.20 build constraint
was there to establish 1.20 as the minimum for the package, because it
requires an API that was added only in Go 1.20 and there was no way to
make it work with 1.19's APIs.

By now only Go 1.24 and 1.23 are supported, and the minimum is set via
the go directive in go.mod.

For golang/go#57792.

Change-Id: Ie4d37d34993374cdd380667930ee667af97eeccb
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/649716
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-02-21 09:26:01 -08:00
Roland Shoemaker 911360c8a4 all: bump golang.org/x/crypto dependencies of asm generators
Change-Id: Ieb2f0d45f82647978f0bd1eb47bb347f0bfb7d13
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/649499
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-02-14 15:32:41 -08:00
Gopher Robot 89ff08d67c all: upgrade go directive to at least 1.23.0 [generated]
By now Go 1.24.0 has been released, and Go 1.22 is no longer supported
per the Go Release Policy (https://go.dev/doc/devel/release#policy).

For golang/go#69095.

[git-generate]
(cd . && go get go@1.23.0 && go mod tidy && go fix ./... && go mod edit -toolchain=none)
(cd x509roots/fallback && go get go@1.23.0 && go mod tidy && go fix ./... && go mod edit -toolchain=none)

Change-Id: I879bced994b310927c41f820ec272a518aa0c8a5
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/649715
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2025-02-14 12:15:19 -08:00
Sean Liao e47973b1c1 all: update certs for go1.24
Fixes golang/go#71612

Change-Id: I5cb0596b33cb18016eb1883d1518319588ae1454
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/647975
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
2025-02-10 08:33:42 -08:00
Gopher Robot 9290511cd2 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: Ib9440df43bc2fde0268cbe327c1df839e793f675
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/646220
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: David Chase <drchase@google.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2025-02-04 11:03:03 -08:00
Gopher Robot fa5273e461 x509roots/fallback: update bundle
This is an automated CL which updates the NSS root bundle.

Change-Id: I3a4388574221a77486b184e73f4b776ff0afc09f
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/646215
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2025-02-03 08:51:27 -08:00
Brad Fitzpatrick a8ea4be81f ssh: add ServerConfig.PreAuthConnCallback, ServerPreAuthConn (banner) interface
Fixes golang/go#68688

Change-Id: Id5f72b32c61c9383a26ec182339486a432c7cdf5
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/613856
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Jonathan Amsterdam <jba@google.com>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2025-01-18 11:27:23 -08:00
Evgeny Shatokhin 71d3a4cfdb acme: support challenges that require the ACME client to send a non-empty JSON body in a response to the challenge.
A new extension to the ACME protocol is proposed to support device attestation: https://datatracker.ietf.org/doc/draft-acme-device-attest/
Based on the recent IETF meetings, the proposal is likely to be accepted.
To support the new extension, the ACME client will need to send a non-empty JSON body in the response to a "device-attest-01" challenge.
Fixes golang/go#68674

Change-Id: I29b420ec837f682e3d59071a4a82af56dc319134
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/608975
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Roland Shoemaker <roland@golang.org>
2025-01-16 08:17:40 -08:00
249 changed files with 29774 additions and 21162 deletions
+47 -57
View File
@@ -31,12 +31,11 @@ import (
"crypto/x509/pkix"
"encoding/asn1"
"encoding/base64"
"encoding/hex"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"math/big"
"net"
"net/http"
"strings"
"sync"
@@ -222,7 +221,7 @@ func (c *Client) directoryURL() string {
// CreateCert was part of the old version of ACME. It is incompatible with RFC 8555.
//
// Deprecated: this was for the pre-RFC 8555 version of ACME. Callers should use CreateOrderCert.
// Deprecated: this was for the pre-RFC 8555 version of ACME. Callers should use CreateCertFromOrder.
func (c *Client) CreateCert(ctx context.Context, csr []byte, exp time.Duration, bundle bool) (der [][]byte, certURL string, err error) {
return nil, "", errPreRFC
}
@@ -353,6 +352,10 @@ func (c *Client) authorize(ctx context.Context, typ, val string) (*Authorization
if _, err := c.Discover(ctx); err != nil {
return nil, err
}
if c.dir.AuthzURL == "" {
// Pre-Authorization is unsupported
return nil, errPreAuthorizationNotSupported
}
type authzID struct {
Type string `json:"type"`
@@ -467,7 +470,7 @@ func (c *Client) WaitAuthorization(ctx context.Context, url string) (*Authorizat
// while waiting for a final authorization status.
d := retryAfter(res.Header.Get("Retry-After"))
if d == 0 {
// Given that the fastest challenges TLS-SNI and HTTP-01
// Given that the fastest challenges TLS-ALPN and HTTP-01
// require a CA to make at least 1 network round trip
// and most likely persist a challenge state,
// this default delay seems reasonable.
@@ -514,7 +517,11 @@ func (c *Client) Accept(ctx context.Context, chal *Challenge) (*Challenge, error
return nil, err
}
res, err := c.post(ctx, nil, chal.URI, json.RawMessage("{}"), wantStatus(
payload := json.RawMessage("{}")
if len(chal.Payload) != 0 {
payload = chal.Payload
}
res, err := c.post(ctx, nil, chal.URI, payload, wantStatus(
http.StatusOK, // according to the spec
http.StatusAccepted, // Let's Encrypt: see https://goo.gl/WsJ7VT (acme-divergences.md)
))
@@ -564,50 +571,28 @@ func (c *Client) HTTP01ChallengePath(token string) string {
}
// TLSSNI01ChallengeCert creates a certificate for TLS-SNI-01 challenge response.
// Always returns an error.
//
// Deprecated: This challenge type is unused in both draft-02 and RFC versions of the ACME spec.
func (c *Client) TLSSNI01ChallengeCert(token string, opt ...CertOption) (cert tls.Certificate, name string, err error) {
ka, err := keyAuth(c.Key.Public(), token)
if err != nil {
return tls.Certificate{}, "", err
}
b := sha256.Sum256([]byte(ka))
h := hex.EncodeToString(b[:])
name = fmt.Sprintf("%s.%s.acme.invalid", h[:32], h[32:])
cert, err = tlsChallengeCert([]string{name}, opt)
if err != nil {
return tls.Certificate{}, "", err
}
return cert, name, nil
// Deprecated: This challenge type was only present in pre-standardized ACME
// protocol drafts and is insecure for use in shared hosting environments.
func (c *Client) TLSSNI01ChallengeCert(token string, opt ...CertOption) (tls.Certificate, string, error) {
return tls.Certificate{}, "", errPreRFC
}
// TLSSNI02ChallengeCert creates a certificate for TLS-SNI-02 challenge response.
// Always returns an error.
//
// Deprecated: This challenge type is unused in both draft-02 and RFC versions of the ACME spec.
func (c *Client) TLSSNI02ChallengeCert(token string, opt ...CertOption) (cert tls.Certificate, name string, err error) {
b := sha256.Sum256([]byte(token))
h := hex.EncodeToString(b[:])
sanA := fmt.Sprintf("%s.%s.token.acme.invalid", h[:32], h[32:])
ka, err := keyAuth(c.Key.Public(), token)
if err != nil {
return tls.Certificate{}, "", err
}
b = sha256.Sum256([]byte(ka))
h = hex.EncodeToString(b[:])
sanB := fmt.Sprintf("%s.%s.ka.acme.invalid", h[:32], h[32:])
cert, err = tlsChallengeCert([]string{sanA, sanB}, opt)
if err != nil {
return tls.Certificate{}, "", err
}
return cert, sanA, nil
// Deprecated: This challenge type was only present in pre-standardized ACME
// protocol drafts and is insecure for use in shared hosting environments.
func (c *Client) TLSSNI02ChallengeCert(token string, opt ...CertOption) (tls.Certificate, string, error) {
return tls.Certificate{}, "", errPreRFC
}
// TLSALPN01ChallengeCert creates a certificate for TLS-ALPN-01 challenge response.
// Servers can present the certificate to validate the challenge and prove control
// over a domain name. For more details on TLS-ALPN-01 see
// https://tools.ietf.org/html/draft-shoemaker-acme-tls-alpn-00#section-3
// over an identifier (either a DNS name or the textual form of an IPv4 or IPv6
// address). For more details on TLS-ALPN-01 see
// https://www.rfc-editor.org/rfc/rfc8737 and https://www.rfc-editor.org/rfc/rfc8738
//
// The token argument is a Challenge.Token value.
// If a WithKey option is provided, its private part signs the returned cert,
@@ -615,9 +600,13 @@ func (c *Client) TLSSNI02ChallengeCert(token string, opt ...CertOption) (cert tl
// If no WithKey option is provided, a new ECDSA key is generated using P-256 curve.
//
// The returned certificate is valid for the next 24 hours and must be presented only when
// the server name in the TLS ClientHello matches the domain, and the special acme-tls/1 ALPN protocol
// the server name in the TLS ClientHello matches the identifier, and the special acme-tls/1 ALPN protocol
// has been specified.
func (c *Client) TLSALPN01ChallengeCert(token, domain string, opt ...CertOption) (cert tls.Certificate, err error) {
//
// Validation requests for IP address identifiers will use the reverse DNS form in the server name
// in the TLS ClientHello since the SNI extension is not supported for IP addresses.
// See RFC 8738 Section 6 for more information.
func (c *Client) TLSALPN01ChallengeCert(token, identifier string, opt ...CertOption) (cert tls.Certificate, err error) {
ka, err := keyAuth(c.Key.Public(), token)
if err != nil {
return tls.Certificate{}, err
@@ -647,7 +636,7 @@ func (c *Client) TLSALPN01ChallengeCert(token, domain string, opt ...CertOption)
}
tmpl.ExtraExtensions = append(tmpl.ExtraExtensions, acmeExtension)
newOpt = append(newOpt, WithTemplate(tmpl))
return tlsChallengeCert([]string{domain}, newOpt)
return tlsChallengeCert(identifier, newOpt)
}
// popNonce returns a nonce value previously stored with c.addNonce
@@ -701,7 +690,7 @@ func (c *Client) addNonce(h http.Header) {
}
func (c *Client) fetchNonce(ctx context.Context, url string) (string, error) {
r, err := http.NewRequest("HEAD", url, nil)
r, err := http.NewRequestWithContext(ctx, "HEAD", url, nil)
if err != nil {
return "", err
}
@@ -765,11 +754,15 @@ func defaultTLSChallengeCertTemplate() *x509.Certificate {
}
}
// tlsChallengeCert creates a temporary certificate for TLS-SNI challenges
// with the given SANs and auto-generated public/private key pair.
// The Subject Common Name is set to the first SAN to aid debugging.
// tlsChallengeCert creates a temporary certificate for TLS-ALPN challenges
// for the given identifier, using an auto-generated public/private key pair.
//
// If the provided identifier is a domain name, it will be used as a DNS type SAN and for the
// subject common name. If the provided identifier is an IP address it will be used as an IP type
// SAN.
//
// To create a cert with a custom key pair, specify WithKey option.
func tlsChallengeCert(san []string, opt []CertOption) (tls.Certificate, error) {
func tlsChallengeCert(identifier string, opt []CertOption) (tls.Certificate, error) {
var key crypto.Signer
tmpl := defaultTLSChallengeCertTemplate()
for _, o := range opt {
@@ -793,9 +786,12 @@ func tlsChallengeCert(san []string, opt []CertOption) (tls.Certificate, error) {
return tls.Certificate{}, err
}
}
tmpl.DNSNames = san
if len(san) > 0 {
tmpl.Subject.CommonName = san[0]
if ip := net.ParseIP(identifier); ip != nil {
tmpl.IPAddresses = []net.IP{ip}
} else {
tmpl.DNSNames = []string{identifier}
tmpl.Subject.CommonName = identifier
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
@@ -808,11 +804,5 @@ func tlsChallengeCert(san []string, opt []CertOption) (tls.Certificate, error) {
}, nil
}
// encodePEM returns b encoded as PEM with block of type typ.
func encodePEM(typ string, b []byte) []byte {
pb := &pem.Block{Type: typ, Bytes: b}
return pem.EncodeToMemory(pb)
}
// timeNow is time.Now, except in tests which can mess with it.
var timeNow = time.Now
+88 -112
View File
@@ -9,20 +9,18 @@ import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"net/http"
"net/http/httptest"
"reflect"
"sort"
"strings"
"testing"
"time"
)
@@ -254,6 +252,57 @@ func TestAuthorizeValid(t *testing.T) {
}
}
func TestAuthorizeUnsupported(t *testing.T) {
const (
nonce = "https://example.com/acme/new-nonce"
reg = "https://example.com/acme/new-acct"
order = "https://example.com/acme/new-order"
revoke = "https://example.com/acme/revoke-cert"
keychange = "https://example.com/acme/key-change"
metaTerms = "https://example.com/acme/terms/2017-5-30"
metaWebsite = "https://www.example.com/"
metaCAA = "example.com"
)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Replay-Nonce", "nonce")
if r.Method == http.MethodHead {
return
}
switch r.URL.Path {
case "/": // Directory
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{
"newNonce": %q,
"newAccount": %q,
"newOrder": %q,
"revokeCert": %q,
"keyChange": %q,
"meta": {
"termsOfService": %q,
"website": %q,
"caaIdentities": [%q],
"externalAccountRequired": true
}
}`, nonce, reg, order, revoke, keychange, metaTerms, metaWebsite, metaCAA)
w.WriteHeader(http.StatusOK)
case "/acme/new-authz":
w.WriteHeader(http.StatusBadRequest)
}
}))
defer ts.Close()
client := &Client{Key: testKey, DirectoryURL: ts.URL}
dir, err := client.Discover(context.Background())
if err != nil {
t.Fatal(err)
}
if dir.AuthzURL != "" {
t.Fatalf("expected AuthzURL to be empty, got %q", dir.AuthzURL)
}
if _, err := client.Authorize(context.Background(), "example.com"); !errors.Is(err, errPreAuthorizationNotSupported) {
t.Errorf("expected err to indicate pre-authorization is unsupported, got %+v", err)
}
}
func TestWaitAuthorization(t *testing.T) {
t.Run("wait loop", func(t *testing.T) {
var count int
@@ -640,71 +689,6 @@ func TestLinkHeader(t *testing.T) {
}
}
func TestTLSSNI01ChallengeCert(t *testing.T) {
const (
token = "evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA"
// echo -n <token.testKeyECThumbprint> | shasum -a 256
san = "dbbd5eefe7b4d06eb9d1d9f5acb4c7cd.a27d320e4b30332f0b6cb441734ad7b0.acme.invalid"
)
tlscert, name, err := newTestClient().TLSSNI01ChallengeCert(token)
if err != nil {
t.Fatal(err)
}
if n := len(tlscert.Certificate); n != 1 {
t.Fatalf("len(tlscert.Certificate) = %d; want 1", n)
}
cert, err := x509.ParseCertificate(tlscert.Certificate[0])
if err != nil {
t.Fatal(err)
}
if len(cert.DNSNames) != 1 || cert.DNSNames[0] != san {
t.Fatalf("cert.DNSNames = %v; want %q", cert.DNSNames, san)
}
if cert.DNSNames[0] != name {
t.Errorf("cert.DNSNames[0] != name: %q vs %q", cert.DNSNames[0], name)
}
if cn := cert.Subject.CommonName; cn != san {
t.Errorf("cert.Subject.CommonName = %q; want %q", cn, san)
}
}
func TestTLSSNI02ChallengeCert(t *testing.T) {
const (
token = "evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA"
// echo -n evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA | shasum -a 256
sanA = "7ea0aaa69214e71e02cebb18bb867736.09b730209baabf60e43d4999979ff139.token.acme.invalid"
// echo -n <token.testKeyECThumbprint> | shasum -a 256
sanB = "dbbd5eefe7b4d06eb9d1d9f5acb4c7cd.a27d320e4b30332f0b6cb441734ad7b0.ka.acme.invalid"
)
tlscert, name, err := newTestClient().TLSSNI02ChallengeCert(token)
if err != nil {
t.Fatal(err)
}
if n := len(tlscert.Certificate); n != 1 {
t.Fatalf("len(tlscert.Certificate) = %d; want 1", n)
}
cert, err := x509.ParseCertificate(tlscert.Certificate[0])
if err != nil {
t.Fatal(err)
}
names := []string{sanA, sanB}
if !reflect.DeepEqual(cert.DNSNames, names) {
t.Fatalf("cert.DNSNames = %v;\nwant %v", cert.DNSNames, names)
}
sort.Strings(cert.DNSNames)
i := sort.SearchStrings(cert.DNSNames, name)
if i >= len(cert.DNSNames) || cert.DNSNames[i] != name {
t.Errorf("%v doesn't have %q", cert.DNSNames, name)
}
if cn := cert.Subject.CommonName; cn != sanA {
t.Errorf("CommonName = %q; want %q", cn, sanA)
}
}
func TestTLSALPN01ChallengeCert(t *testing.T) {
const (
token = "evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA"
@@ -750,17 +734,18 @@ func TestTLSALPN01ChallengeCert(t *testing.T) {
if !acmeExts[0].Critical {
t.Errorf("acmeExt.Critical = %v; want true", acmeExts[0].Critical)
}
if bytes.Compare(acmeExts[0].Value, extValue) != 0 {
if !bytes.Equal(acmeExts[0].Value, extValue) {
t.Errorf("acmeExt.Value = %v; want %v", acmeExts[0].Value, extValue)
}
}
func TestTLSChallengeCertOpt(t *testing.T) {
key, err := rsa.GenerateKey(rand.Reader, 512)
key, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
t.Fatal(err)
}
domain := "example.com"
tmpl := &x509.Certificate{
SerialNumber: big.NewInt(2),
Subject: pkix.Name{Organization: []string{"Test"}},
@@ -769,52 +754,43 @@ func TestTLSChallengeCertOpt(t *testing.T) {
opts := []CertOption{WithKey(key), WithTemplate(tmpl)}
client := newTestClient()
cert1, _, err := client.TLSSNI01ChallengeCert("token", opts...)
if err != nil {
t.Fatal(err)
}
cert2, _, err := client.TLSSNI02ChallengeCert("token", opts...)
cert, err := client.TLSALPN01ChallengeCert("token", domain, opts...)
if err != nil {
t.Fatal(err)
}
for i, tlscert := range []tls.Certificate{cert1, cert2} {
// verify generated cert private key
tlskey, ok := tlscert.PrivateKey.(*rsa.PrivateKey)
if !ok {
t.Errorf("%d: tlscert.PrivateKey is %T; want *rsa.PrivateKey", i, tlscert.PrivateKey)
continue
}
if tlskey.D.Cmp(key.D) != 0 {
t.Errorf("%d: tlskey.D = %v; want %v", i, tlskey.D, key.D)
}
// verify generated cert public key
x509Cert, err := x509.ParseCertificate(tlscert.Certificate[0])
if err != nil {
t.Errorf("%d: %v", i, err)
continue
}
tlspub, ok := x509Cert.PublicKey.(*rsa.PublicKey)
if !ok {
t.Errorf("%d: x509Cert.PublicKey is %T; want *rsa.PublicKey", i, x509Cert.PublicKey)
continue
}
if tlspub.N.Cmp(key.N) != 0 {
t.Errorf("%d: tlspub.N = %v; want %v", i, tlspub.N, key.N)
}
// verify template option
sn := big.NewInt(2)
if x509Cert.SerialNumber.Cmp(sn) != 0 {
t.Errorf("%d: SerialNumber = %v; want %v", i, x509Cert.SerialNumber, sn)
}
org := []string{"Test"}
if !reflect.DeepEqual(x509Cert.Subject.Organization, org) {
t.Errorf("%d: Subject.Organization = %+v; want %+v", i, x509Cert.Subject.Organization, org)
}
for _, v := range x509Cert.DNSNames {
if !strings.HasSuffix(v, ".acme.invalid") {
t.Errorf("%d: invalid DNSNames element: %q", i, v)
}
// verify generated cert private key
tlskey, ok := cert.PrivateKey.(*rsa.PrivateKey)
if !ok {
t.Fatalf("tlscert.PrivateKey is %T; want *rsa.PrivateKey", cert.PrivateKey)
}
if tlskey.D.Cmp(key.D) != 0 {
t.Errorf("tlskey.D = %v; want %v", tlskey.D, key.D)
}
// verify generated cert public key
x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
if err != nil {
t.Fatal(err)
}
tlspub, ok := x509Cert.PublicKey.(*rsa.PublicKey)
if !ok {
t.Fatalf("x509Cert.PublicKey is %T; want *rsa.PublicKey", x509Cert.PublicKey)
}
if tlspub.N.Cmp(key.N) != 0 {
t.Errorf("tlspub.N = %v; want %v", tlspub.N, key.N)
}
// verify template option
sn := big.NewInt(2)
if x509Cert.SerialNumber.Cmp(sn) != 0 {
t.Errorf("SerialNumber = %v; want %v", x509Cert.SerialNumber, sn)
}
org := []string{"Test"}
if !reflect.DeepEqual(x509Cert.Subject.Organization, org) {
t.Errorf("Subject.Organization = %+v; want %+v", x509Cert.Subject.Organization, org)
}
for _, v := range x509Cert.DNSNames {
if v != domain {
t.Errorf("invalid DNSNames element: %q", v)
}
}
}
+32 -43
View File
@@ -134,7 +134,8 @@ type Manager struct {
// RenewBefore optionally specifies how early certificates should
// be renewed before they expire.
//
// If zero, they're renewed 30 days before expiration.
// If zero, they're renewed at the lesser of 30 days or
// 1/3 of the certificate lifetime.
RenewBefore time.Duration
// Client is used to perform low-level operations, such as account registration
@@ -247,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")
@@ -292,6 +289,10 @@ func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate,
}
// regular domain
if err := m.hostPolicy()(ctx, name); err != nil {
return nil, err
}
ck := certKey{
domain: strings.TrimSuffix(name, "."), // golang.org/issue/18114
isRSA: !supportsECDSA(hello),
@@ -305,9 +306,6 @@ func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate,
}
// first-time
if err := m.hostPolicy()(ctx, name); err != nil {
return nil, err
}
cert, err = m.createCert(ctx, ck)
if err != nil {
return nil, err
@@ -463,7 +461,7 @@ func (m *Manager) cert(ctx context.Context, ck certKey) (*tls.Certificate, error
leaf: cert.Leaf,
}
m.state[ck] = s
m.startRenew(ck, s.key, s.leaf.NotAfter)
m.startRenew(ck, s.key, s.leaf.NotBefore, s.leaf.NotAfter)
return cert, nil
}
@@ -566,24 +564,21 @@ func encodeECDSAKey(w io.Writer, key *ecdsa.PrivateKey) error {
// If the domain is already being verified, it waits for the existing verification to complete.
// Either way, createCert blocks for the duration of the whole process.
func (m *Manager) createCert(ctx context.Context, ck certKey) (*tls.Certificate, error) {
// TODO: maybe rewrite this whole piece using sync.Once
state, err := m.certState(ck)
state, owner, err := m.certState(ck)
if err != nil {
return nil, err
}
// state may exist if another goroutine is already working on it
// in which case just wait for it to finish
if !state.locked {
// If another goroutine is already working on this state, wait for it
// to finish by taking the read lock
if !owner {
state.RLock()
defer state.RUnlock()
return state.tlscert()
}
// We are the first; state is locked.
// Unblock the readers when domain ownership is verified
// and we got the cert or the process failed.
// We are the first to work on this certKey, so state is write-locked.
// Unblock the readers when our work is complete.
defer state.Unlock()
state.locked = false
der, leaf, err := m.authorizedCert(ctx, state.key, ck)
if err != nil {
@@ -609,14 +604,19 @@ func (m *Manager) createCert(ctx context.Context, ck certKey) (*tls.Certificate,
}
state.cert = der
state.leaf = leaf
m.startRenew(ck, state.key, state.leaf.NotAfter)
m.startRenew(ck, state.key, state.leaf.NotBefore, state.leaf.NotAfter)
return state.tlscert()
}
// certState returns a new or existing certState.
// If a new certState is returned, state.exist is false and the state is locked.
// certState returns a new or existing certState along with a boolean
// indicating whether the caller is the owner of the state.
//
// The owner of the state is responsible for performing the ACME work and
// must unlock the state's write lock when done. Non-owner callers should
// wait on the state's read lock for the owner to finish.
//
// The returned error is non-nil only in the case where a new state could not be created.
func (m *Manager) certState(ck certKey) (*certState, error) {
func (m *Manager) certState(ck certKey) (*certState, bool, error) {
m.stateMu.Lock()
defer m.stateMu.Unlock()
if m.state == nil {
@@ -624,7 +624,7 @@ func (m *Manager) certState(ck certKey) (*certState, error) {
}
// existing state
if state, ok := m.state[ck]; ok {
return state, nil
return state, false, nil
}
// new locked state
@@ -638,16 +638,13 @@ func (m *Manager) certState(ck certKey) (*certState, error) {
key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
}
if err != nil {
return nil, err
return nil, false, err
}
state := &certState{
key: key,
locked: true,
}
state := &certState{key: key}
state.Lock() // will be unlocked by m.certState caller
m.state[ck] = state
return state, nil
return state, true, nil
}
// authorizedCert starts the domain ownership verification process and requests a new cert upon success.
@@ -674,7 +671,7 @@ func (m *Manager) authorizedCert(ctx context.Context, key crypto.Signer, ck cert
if err != nil {
return nil, nil, err
}
chain, _, err := client.CreateOrderCert(ctx, o.FinalizeURL, csr, true)
chain, _, err := client.CreateCertFromOrder(ctx, o, csr, true)
if err != nil {
return nil, nil, err
}
@@ -907,7 +904,7 @@ func httpTokenCacheKey(tokenPath string) string {
//
// The key argument is a certificate private key.
// The exp argument is the cert expiration time (NotAfter).
func (m *Manager) startRenew(ck certKey, key crypto.Signer, exp time.Time) {
func (m *Manager) startRenew(ck certKey, key crypto.Signer, notBefore, notAfter time.Time) {
m.renewalMu.Lock()
defer m.renewalMu.Unlock()
if m.renewal[ck] != nil {
@@ -919,7 +916,7 @@ func (m *Manager) startRenew(ck certKey, key crypto.Signer, exp time.Time) {
}
dr := &domainRenewal{m: m, ck: ck, key: key}
m.renewal[ck] = dr
dr.start(exp)
dr.start(notBefore, notAfter)
}
// stopRenew stops all currently running cert renewal timers.
@@ -1027,13 +1024,6 @@ func (m *Manager) hostPolicy() HostPolicy {
return defaultHostPolicy
}
func (m *Manager) renewBefore() time.Duration {
if m.RenewBefore > renewJitter {
return m.RenewBefore
}
return 720 * time.Hour // 30 days
}
func (m *Manager) now() time.Time {
if m.nowFunc != nil {
return m.nowFunc()
@@ -1044,10 +1034,9 @@ func (m *Manager) now() time.Time {
// certState is ready when its mutex is unlocked for reading.
type certState struct {
sync.RWMutex
locked bool // locked for read/write
key crypto.Signer // private key for cert
cert [][]byte // DER encoding
leaf *x509.Certificate // parsed cert[0]; always non-nil if cert != nil
key crypto.Signer // private key for cert
cert [][]byte // DER encoding
leaf *x509.Certificate // parsed cert[0]; always non-nil if cert != nil
}
// tlscert creates a tls.Certificate from s.key and s.cert.
+33 -6
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",
@@ -513,6 +513,33 @@ func TestGetCertificate_failedAttempt(t *testing.T) {
}
}
// TestGetCertificate_concurrent guards against a data race on certState
// fields between the goroutine performing the ACME work for a domain and
// the other goroutines waiting on the result. See golang/go#80119.
func TestGetCertificate_concurrent(t *testing.T) {
// An unreachable directory URL makes the owner goroutine fail
// quickly inside createCert, so its writes overlap with the
// non-owner goroutines reaching the same code path.
m := &Manager{
Prompt: AcceptTOS,
Client: &acme.Client{DirectoryURL: "http://127.0.0.1:1/"},
}
defer m.stopRenew()
start := make(chan struct{})
var wg sync.WaitGroup
for i := 0; i < 64; i++ {
wg.Add(1)
go func() {
defer wg.Done()
<-start
m.GetCertificate(clientHelloInfo(exampleDomain, algECDSA))
}()
}
close(start)
wg.Wait()
}
func TestRevokeFailedAuthz(t *testing.T) {
ca := acmetest.NewCAServer(t)
// Make the authz unfulfillable on the client side, so it will be left
@@ -561,9 +588,9 @@ func TestHTTPHandlerDefaultFallback(t *testing.T) {
{"GET", "http://example.org/foo?a=b", 302, "https://example.org/foo?a=b"},
{"GET", "http://example.org:80/foo?a=b", 302, "https://example.org:443/foo?a=b"},
{"GET", "http://example.org:80/foo%20bar", 302, "https://example.org:443/foo%20bar"},
{"GET", "http://[2602:d1:xxxx::c60a]:1234", 302, "https://[2602:d1:xxxx::c60a]:443/"},
{"GET", "http://[2602:d1:xxxx::c60a]", 302, "https://[2602:d1:xxxx::c60a]/"},
{"GET", "http://[2602:d1:xxxx::c60a]/foo?a=b", 302, "https://[2602:d1:xxxx::c60a]/foo?a=b"},
{"GET", "http://[2602:d1:abcd::c60a]:1234", 302, "https://[2602:d1:abcd::c60a]:443/"},
{"GET", "http://[2602:d1:abcd::c60a]", 302, "https://[2602:d1:abcd::c60a]/"},
{"GET", "http://[2602:d1:abcd::c60a]/foo?a=b", 302, "https://[2602:d1:abcd::c60a]/foo?a=b"},
{"HEAD", "http://example.org", 302, "https://example.org/"},
{"HEAD", "http://example.org/foo", 302, "https://example.org/foo"},
{"HEAD", "http://example.org/foo/bar/", 302, "https://example.org/foo/bar/"},
@@ -619,7 +646,7 @@ func TestCache(t *testing.T) {
PrivateKey: ecdsaKey,
}
rsaKey, err := rsa.GenerateKey(rand.Reader, 512)
rsaKey, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
t.Fatal(err)
}
@@ -694,7 +721,7 @@ func TestValidCert(t *testing.T) {
if err != nil {
t.Fatal(err)
}
key3, err := rsa.GenerateKey(rand.Reader, 512)
key3, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
t.Fatal(err)
}
+4 -14
View File
@@ -145,7 +145,7 @@ func (ca *CAServer) URL() string {
return ca.url
}
// Roots returns a pool cointaining the CA root.
// Roots returns a pool containing the CA root.
func (ca *CAServer) Roots() *x509.CertPool {
if ca.url == "" {
panic("Roots called before Start")
@@ -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,
},
}
@@ -782,15 +784,3 @@ func decodePayload(v interface{}, r io.Reader) error {
func challengeToken(domain, challType string, authzID int) string {
return fmt.Sprintf("token-%s-%s-%d", domain, challType, authzID)
}
func unique(a []string) []string {
seen := make(map[string]bool)
var res []string
for _, s := range a {
if s != "" && !seen[s] {
seen[s] = true
res = append(res, s)
}
}
return res
}
+6 -26
View File
@@ -10,7 +10,6 @@ import (
"net"
"os"
"path/filepath"
"runtime"
"time"
)
@@ -124,32 +123,13 @@ func (ln *listener) Close() error {
return ln.tcpListener.Close()
}
func homeDir() string {
if runtime.GOOS == "windows" {
return os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
}
if h := os.Getenv("HOME"); h != "" {
return h
}
return "/"
}
func cacheDir() string {
const base = "golang-autocert"
switch runtime.GOOS {
case "darwin":
return filepath.Join(homeDir(), "Library", "Caches", base)
case "windows":
for _, ev := range []string{"APPDATA", "CSIDL_APPDATA", "TEMP", "TMP"} {
if v := os.Getenv(ev); v != "" {
return filepath.Join(v, base)
}
}
// Worst case:
return filepath.Join(homeDir(), base)
cache, err := os.UserCacheDir()
if err != nil {
// Fall back to the root directory.
cache = "/.cache"
}
if xdg := os.Getenv("XDG_CACHE_HOME"); xdg != "" {
return filepath.Join(xdg, base)
}
return filepath.Join(homeDir(), ".cache", base)
return filepath.Join(cache, base)
}
+19 -17
View File
@@ -11,9 +11,6 @@ import (
"time"
)
// renewJitter is the maximum deviation from Manager.RenewBefore.
const renewJitter = time.Hour
// domainRenewal tracks the state used by the periodic timers
// renewing a single domain's cert.
type domainRenewal struct {
@@ -30,13 +27,13 @@ type domainRenewal struct {
// defined by the certificate expiration time exp.
//
// If the timer is already started, calling start is a noop.
func (dr *domainRenewal) start(exp time.Time) {
func (dr *domainRenewal) start(notBefore, notAfter time.Time) {
dr.timerMu.Lock()
defer dr.timerMu.Unlock()
if dr.timer != nil {
return
}
dr.timer = time.AfterFunc(dr.next(exp), dr.renew)
dr.timer = time.AfterFunc(dr.next(notBefore, notAfter), dr.renew)
}
// stop stops the cert renewal timer and waits for any in-flight calls to renew
@@ -79,7 +76,7 @@ func (dr *domainRenewal) renew() {
// TODO: rotate dr.key at some point?
next, err := dr.do(ctx)
if err != nil {
next = renewJitter / 2
next = time.Hour / 2
next += time.Duration(pseudoRand.int63n(int64(next)))
}
testDidRenewLoop(next, err)
@@ -107,8 +104,8 @@ func (dr *domainRenewal) do(ctx context.Context) (time.Duration, error) {
// a race is likely unavoidable in a distributed environment
// but we try nonetheless
if tlscert, err := dr.m.cacheGet(ctx, dr.ck); err == nil {
next := dr.next(tlscert.Leaf.NotAfter)
if next > dr.m.renewBefore()+renewJitter {
next := dr.next(tlscert.Leaf.NotBefore, tlscert.Leaf.NotAfter)
if next > 0 {
signer, ok := tlscert.PrivateKey.(crypto.Signer)
if ok {
state := &certState{
@@ -139,18 +136,23 @@ func (dr *domainRenewal) do(ctx context.Context) (time.Duration, error) {
return 0, err
}
dr.updateState(state)
return dr.next(leaf.NotAfter), nil
return dr.next(leaf.NotBefore, leaf.NotAfter), nil
}
func (dr *domainRenewal) next(expiry time.Time) time.Duration {
d := expiry.Sub(dr.m.now()) - dr.m.renewBefore()
// add a bit of randomness to renew deadline
n := pseudoRand.int63n(int64(renewJitter))
d -= time.Duration(n)
if d < 0 {
return 0
// next returns the wait time before the next renewal should start.
// If manager.RenewBefore is set, it uses that capped at 30 days,
// otherwise it uses a default of 1/3 of the cert lifetime.
// It builds in a jitter of 10% of the renew threshold, capped at 1 hour.
func (dr *domainRenewal) next(notBefore, notAfter time.Time) time.Duration {
threshold := min(notAfter.Sub(notBefore)/3, 30*24*time.Hour)
if dr.m.RenewBefore > 0 {
threshold = min(dr.m.RenewBefore, 30*24*time.Hour)
}
return d
maxJitter := min(threshold/10, time.Hour)
jitter := pseudoRand.int63n(int64(maxJitter))
renewAt := notAfter.Add(-(threshold - time.Duration(jitter)))
renewWait := renewAt.Sub(dr.m.now())
return max(0, renewWait)
}
var testDidRenewLoop = func(next time.Duration, err error) {}
+51 -21
View File
@@ -17,27 +17,60 @@ import (
func TestRenewalNext(t *testing.T) {
now := time.Now()
man := &Manager{
RenewBefore: 7 * 24 * time.Hour,
nowFunc: func() time.Time { return now },
}
defer man.stopRenew()
nowFn := func() time.Time { return now }
tt := []struct {
expiry time.Time
min, max time.Duration
name string
renewBefore time.Duration // arg to Manager
// leaf cert validity
notBefore time.Time
validFor time.Duration
// wait time
waitMin, waitMax time.Duration
}{
{now.Add(90 * 24 * time.Hour), 83*24*time.Hour - renewJitter, 83 * 24 * time.Hour},
{now.Add(time.Hour), 0, 1},
{now, 0, 1},
{now.Add(-time.Hour), 0, 1},
{"default renewal, 1h cert, valid",
0, now, time.Hour, 40 * time.Minute, 50 * time.Minute},
{"default renewal, 1h cert, should renew",
0, now.Add(-50 * time.Minute), time.Hour, 0, 0},
{"default renewal, 1h cert, expired",
0, now.Add(-400 * 24 * time.Hour), time.Hour, 0, 0},
{"default renewal, 6d cert, valid",
0, now, 6 * 24 * time.Hour, 4 * 24 * time.Hour, (4*24 + 1) * time.Hour},
{"default renewal, 6d cert, should renew",
0, now.Add(-5 * 24 * time.Hour), 6 * 24 * time.Hour, 0, 0},
{"default renewal, 6d cert, expired",
0, now.Add(-400 * 24 * time.Hour), 6 * 24 * time.Hour, 0, 0},
{"default renewal, 90d cert, valid",
0, now, 90 * 24 * time.Hour, 60 * 24 * time.Hour, (60*24 + 1) * time.Hour},
{"default renewal, 90d cert, should renew",
0, now.Add(-70 * 24 * time.Hour), 90 * 24 * time.Hour, 0, 0},
{"default renewal, 90d cert, expired",
0, now.Add(-400 * 24 * time.Hour), 90 * 24 * time.Hour, 0, 0},
{"default renewal, 398d cert, valid",
0, now, 398 * 24 * time.Hour, (368 * 24) * time.Hour, (368*24 + 1) * time.Hour},
{"default renewal, 398d cert, should renew",
0, now.Add(-378 * 24 * time.Hour), 398 * 24 * time.Hour, 0, 0},
{"default renewal, 398d cert, expired",
0, now.Add(-400 * 24 * time.Hour), 398 * 24 * time.Hour, 0, 0},
{"7d renewal, 90d cert, valid",
7 * 24 * time.Hour, now, 90 * 24 * time.Hour, 83 * 24 * time.Hour, (83*24 + 1) * time.Hour},
{"7d renewal, 90d cert, should not renew",
7 * 24 * time.Hour, now.Add(-70 * 24 * time.Hour), 90 * 24 * time.Hour, 13 * 24 * time.Hour, (13*24 + 1) * time.Hour},
{"7d renewal, 90d cert, should renew",
7 * 24 * time.Hour, now.Add(-85 * 24 * time.Hour), 90 * 24 * time.Hour, 0, 0},
{"7d renewal, 90d cert, expired",
7 * 24 * time.Hour, now.Add(-400 * 24 * time.Hour), 90 * 24 * time.Hour, 0, 0},
}
dr := &domainRenewal{m: man}
for i, test := range tt {
next := dr.next(test.expiry)
if next < test.min || test.max < next {
t.Errorf("%d: next = %v; want between %v and %v", i, next, test.min, test.max)
}
for _, test := range tt {
t.Run(test.name, func(t *testing.T) {
dr := &domainRenewal{m: &Manager{RenewBefore: test.renewBefore, nowFunc: nowFn}}
defer dr.m.stopRenew()
next := dr.next(test.notBefore, test.notBefore.Add(test.validFor))
if next < test.waitMin || next > test.waitMax {
t.Errorf("expected wait time: %v <= %v <= %v", test.waitMin, next, test.waitMax)
}
})
}
}
@@ -147,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)
@@ -239,7 +269,7 @@ func TestRenewFromCacheAlreadyRenewed(t *testing.T) {
}
// trigger renew
man.startRenew(exampleCertKey, s.key, s.leaf.NotAfter)
man.startRenew(exampleCertKey, s.key, s.leaf.NotBefore, s.leaf.NotAfter)
<-renewed
func() {
man.renewalMu.Lock()
+4 -7
View File
@@ -66,7 +66,7 @@ func (c *Client) retryTimer() *retryTimer {
// The n argument is always bounded between 1 and 30.
// The returned value is always greater than 0.
func defaultBackoff(n int, r *http.Request, res *http.Response) time.Duration {
const max = 10 * time.Second
const maxVal = 10 * time.Second
var jitter time.Duration
if x, err := rand.Int(rand.Reader, big.NewInt(1000)); err == nil {
// Set the minimum to 1ms to avoid a case where
@@ -86,10 +86,7 @@ func defaultBackoff(n int, r *http.Request, res *http.Response) time.Duration {
n = 30
}
d := time.Duration(1<<uint(n-1))*time.Second + jitter
if d > max {
return max
}
return d
return min(d, maxVal)
}
// retryAfter parses a Retry-After HTTP header value,
@@ -131,7 +128,7 @@ func wantStatus(codes ...int) resOkay {
func (c *Client) get(ctx context.Context, url string, ok resOkay) (*http.Response, error) {
retry := c.retryTimer()
for {
req, err := http.NewRequest("GET", url, nil)
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return nil, err
}
@@ -231,7 +228,7 @@ func (c *Client) postNoRetry(ctx context.Context, key crypto.Signer, url string,
if err != nil {
return nil, nil, err
}
req, err := http.NewRequest("POST", url, bytes.NewReader(b))
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(b))
if err != nil {
return nil, nil, err
}
+4 -4
View File
@@ -182,9 +182,9 @@ func (p *prober) runOrder(ctx context.Context, identifiers []acme.AuthzID) {
log.Fatalf("WaitOrder(%q): %v", o.URI, err)
}
csr, certkey := newCSR(identifiers)
der, curl, err := p.client.CreateOrderCert(ctx, o.FinalizeURL, csr, true)
der, curl, err := p.client.CreateCertFromOrder(ctx, o, csr, true)
if err != nil {
log.Fatalf("CreateOrderCert: %v", err)
log.Fatalf("CreateCertFromOrder: %v", err)
}
log.Printf("cert URL: %s", curl)
if err := checkCert(der, identifiers); err != nil {
@@ -247,9 +247,9 @@ func (p *prober) runPreauthz(ctx context.Context, identifiers []acme.AuthzID) {
log.Fatalf("WaitOrder(%q): %v", o.URI, err)
}
csr, certkey := newCSR(identifiers)
der, curl, err := p.client.CreateOrderCert(ctx, o.FinalizeURL, csr, true)
der, curl, err := p.client.CreateCertFromOrder(ctx, o, csr, true)
if err != nil {
log.Fatalf("CreateOrderCert: %v", err)
log.Fatalf("CreateCertFromOrder: %v", err)
}
log.Printf("cert URL: %s", curl)
if err := checkCert(der, identifiers); err != nil {
+6 -9
View File
@@ -92,7 +92,7 @@ func jwsEncodeJSON(claimset interface{}, key crypto.Signer, kid KeyID, nonce, ur
if err != nil {
return nil, err
}
phead := base64.RawURLEncoding.EncodeToString([]byte(phJSON))
phead := base64.RawURLEncoding.EncodeToString(phJSON)
var payload string
if val, ok := claimset.(string); ok {
payload = val
@@ -103,9 +103,7 @@ func jwsEncodeJSON(claimset interface{}, key crypto.Signer, kid KeyID, nonce, ur
}
payload = base64.RawURLEncoding.EncodeToString(cs)
}
hash := sha.New()
hash.Write([]byte(phead + "." + payload))
sig, err := jwsSign(key, sha, hash.Sum(nil))
sig, err := jwsSign(key, sha, []byte(phead+"."+payload))
if err != nil {
return nil, err
}
@@ -195,14 +193,13 @@ func jwkEncode(pub crypto.PublicKey) (string, error) {
return "", ErrUnsupportedKey
}
// jwsSign signs the digest using the given key.
// The hash is unused for ECDSA keys.
func jwsSign(key crypto.Signer, hash crypto.Hash, digest []byte) ([]byte, error) {
// jwsSign signs the payload using the given key.
func jwsSign(key crypto.Signer, hash crypto.Hash, payload []byte) ([]byte, error) {
switch pub := key.Public().(type) {
case *rsa.PublicKey:
return key.Sign(rand.Reader, digest, hash)
return crypto.SignMessage(key, rand.Reader, payload, hash)
case *ecdsa.PublicKey:
sigASN1, err := key.Sign(rand.Reader, digest, hash)
sigASN1, err := crypto.SignMessage(key, rand.Reader, payload, hash)
if err != nil {
return nil, err
}
+39 -5
View File
@@ -14,6 +14,7 @@ import (
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"math/big"
@@ -353,6 +354,22 @@ func (s *customTestSigner) Sign(io.Reader, []byte, crypto.SignerOpts) ([]byte, e
return s.sig, nil
}
type customTestMessageSigner struct {
customTestSigner
msg []byte
opts crypto.SignerOpts
}
func (s *customTestMessageSigner) Sign(io.Reader, []byte, crypto.SignerOpts) ([]byte, error) {
return nil, errors.New("customTestSigner: Sign() called instead of SignMessage()")
}
func (s *customTestMessageSigner) SignMessage(_ io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error) {
s.msg = msg
s.opts = opts
return s.sig, nil
}
func TestJWSEncodeJSONCustom(t *testing.T) {
claims := struct{ Msg string }{"hello"}
const (
@@ -391,24 +408,33 @@ func TestJWSEncodeJSONCustom(t *testing.T) {
)
tt := []struct {
alg, phead string
name, phead string
pub crypto.PublicKey
stdsig, jwsig string
msgSigner bool
}{
{"ES256", es256phead, testKeyEC.Public(), es256stdsig, es256jwsig},
{"RS256", rs256phead, testKey.Public(), testsig, testsig},
{"ES256", es256phead, testKeyEC.Public(), es256stdsig, es256jwsig, false},
{"RS256", rs256phead, testKey.Public(), testsig, testsig, false},
{"ES256-MessageSigner", es256phead, testKeyEC.Public(), es256stdsig, es256jwsig, true},
{"RS256-MessageSigner", rs256phead, testKey.Public(), testsig, testsig, true},
}
for _, tc := range tt {
tc := tc
t.Run(tc.alg, func(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
stdsig, err := base64.RawStdEncoding.DecodeString(tc.stdsig)
if err != nil {
t.Errorf("couldn't decode test vector: %v", err)
}
signer := &customTestSigner{
cs := customTestSigner{
sig: stdsig,
pub: tc.pub,
}
var signer crypto.Signer = &cs
var ms *customTestMessageSigner
if tc.msgSigner {
ms = &customTestMessageSigner{customTestSigner: cs}
signer = ms
}
b, err := jwsEncodeJSON(claims, signer, noKeyID, "nonce", "url")
if err != nil {
@@ -427,6 +453,14 @@ func TestJWSEncodeJSONCustom(t *testing.T) {
if j.Sig != tc.jwsig {
t.Errorf("j.Sig = %q\nwant %q", j.Sig, tc.jwsig)
}
if ms != nil {
if want := tc.phead + "." + payload; string(ms.msg) != want {
t.Errorf("msg = %q; want %q", ms.msg, want)
}
if ms.opts != crypto.SHA256 {
t.Errorf("opts = %v; want %v", ms.opts, crypto.SHA256)
}
}
})
}
}
+809
View File
@@ -0,0 +1,809 @@
// 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 acme_test
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"golang.org/x/crypto/acme"
)
const (
// pebbleModVersion is the module version used for Pebble and Pebble's
// challenge test server. It is ignored if `-pebble-local-dir` is provided.
pebbleModVersion = "v2.10.1"
// startingPort is the first port number used for binding interface
// addresses. Each call to takeNextPort() will increment a port number
// starting at this value.
startingPort = 5555
)
var (
pebbleLocalDir = flag.String(
"pebble-local-dir",
"",
"Local Pebble to use, instead of fetching from source",
)
nextPort atomic.Uint32
)
func init() {
nextPort.Store(startingPort)
}
func TestWithPebble(t *testing.T) {
// We want to use process groups w/ syscall.Kill, and the acme package
// is very platform-agnostic, so skip on non-Linux.
if runtime.GOOS != "linux" {
t.Skip("skipping pebble tests on non-linux OS")
}
if testing.Short() {
t.Skip("skipping pebble tests in short mode")
}
tests := []struct {
name string
challSrv func(*environment) (challengeServer, string)
}{
{
name: "TLSALPN01-Issuance",
challSrv: func(env *environment) (challengeServer, string) {
bindAddr := fmt.Sprintf(":%d", env.config.TLSPort)
return newChallTLSServer(bindAddr), bindAddr
},
},
{
name: "HTTP01-Issuance",
challSrv: func(env *environment) (challengeServer, string) {
bindAddr := fmt.Sprintf(":%d", env.config.HTTPPort)
return newChallHTTPServer(bindAddr), bindAddr
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
env := startPebbleEnvironment(t, nil)
challSrv, challSrvAddr := tt.challSrv(&env)
challSrv.Run()
t.Cleanup(func() {
challSrv.Shutdown()
})
waitForServer(t, challSrvAddr)
testIssuance(t, &env, challSrv)
})
}
}
// challengeServer abstracts over the details of running a challenge response
// server for some supported acme.Challenge type. Responses are provisioned
// during the test issuance process to be presented to the ACME server's
// validation authority.
type challengeServer interface {
Run()
Shutdown() error
Supported(chal *acme.Challenge) bool
Provision(client *acme.Client, ident acme.AuthzID, chal *acme.Challenge) error
}
// challTLSServer is a simple challenge response server that listens for TLS
// connections on a specific port and if they are TLS-ALPN-01 challenge
// requests, completes the handshake using the configured challenge response
// certificate for the SNI value provided.
type challTLSServer struct {
*http.Server
// mu protects challCerts.
mu sync.RWMutex
// challCerts is a map from SNI domain name to challenge response certificate.
challCerts map[string]*tls.Certificate
}
// https://datatracker.ietf.org/doc/html/rfc8737#section-4
const acmeTLSAlpnProtocol = "acme-tls/1"
func newChallTLSServer(address string) *challTLSServer {
challServer := &challTLSServer{Server: &http.Server{
Addr: address,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
}, challCerts: make(map[string]*tls.Certificate)}
// Configure the server to support the TLS-ALPN-01 challenge protocol
// and to use a callback for selecting the handshake certificate.
challServer.Server.TLSConfig = &tls.Config{
NextProtos: []string{acmeTLSAlpnProtocol},
GetCertificate: challServer.getCertificate,
}
return challServer
}
func (c *challTLSServer) Shutdown() error {
log.Printf("challTLSServer: shutting down")
ctx, cancel := context.WithTimeout(context.Background(), 10)
defer cancel()
return c.Server.Shutdown(ctx)
}
func (c *challTLSServer) Run() {
go func() {
// Note: certFile and keyFile are empty because our config uses a
// GetCertificate callback.
if err := c.Server.ListenAndServeTLS("", ""); err != nil {
if !errors.Is(err, http.ErrServerClosed) {
log.Printf("challTLSServer error: %v", err)
}
}
}()
}
func (c *challTLSServer) Supported(chal *acme.Challenge) bool {
return chal.Type == "tls-alpn-01"
}
func (c *challTLSServer) Provision(client *acme.Client, ident acme.AuthzID, chal *acme.Challenge) error {
respCert, err := client.TLSALPN01ChallengeCert(chal.Token, ident.Value)
if err != nil {
return fmt.Errorf("challTLSServer: failed to generate challlenge response cert for %s: %w",
ident.Value, err)
}
log.Printf("challTLSServer: setting challenge response certificate for %s", ident.Value)
c.mu.Lock()
defer c.mu.Unlock()
c.challCerts[ident.Value] = &respCert
return nil
}
func (c *challTLSServer) getCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
// Verify the request looks like a TLS-ALPN-01 challenge request.
if len(clientHello.SupportedProtos) != 1 || clientHello.SupportedProtos[0] != acmeTLSAlpnProtocol {
return nil, fmt.Errorf(
"challTLSServer: non-TLS-ALPN-01 challenge request received with SupportedProtos: %s",
clientHello.SupportedProtos)
}
serverName := clientHello.ServerName
// TLS-ALPN-01 challenge requests for IP addresses are encoded in the SNI
// using the reverse-DNS notation. See RFC 8738 Section 6:
// https://www.rfc-editor.org/rfc/rfc8738.html#section-6
if strings.HasSuffix(serverName, ".in-addr.arpa") {
serverName = strings.TrimSuffix(serverName, ".in-addr.arpa")
parts := strings.Split(serverName, ".")
for i, j := 0, len(parts)-1; i < j; i, j = i+1, j-1 {
parts[i], parts[j] = parts[j], parts[i]
}
serverName = strings.Join(parts, ".")
}
log.Printf("challTLSServer: selecting certificate for request from %s for %s",
clientHello.Conn.RemoteAddr(), serverName)
c.mu.RLock()
defer c.mu.RUnlock()
cert := c.challCerts[serverName]
if cert == nil {
return nil, fmt.Errorf("challTLSServer: no challenge response certificate configured for %s", serverName)
}
return cert, nil
}
// challHTTPServer is a simple challenge response server that listens for HTTP
// connections on a specific port and if they are HTTP-01 challenge requests,
// serves the challenge response key authorization.
type challHTTPServer struct {
*http.Server
// mu protects challMap
mu sync.RWMutex
// challMap is a mapping from request path to response body.
challMap map[string]string
}
func newChallHTTPServer(address string) *challHTTPServer {
challServer := &challHTTPServer{
Server: &http.Server{
Addr: address,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
},
challMap: make(map[string]string),
}
challServer.Server.Handler = challServer
return challServer
}
func (c *challHTTPServer) Supported(chal *acme.Challenge) bool {
return chal.Type == "http-01"
}
func (c *challHTTPServer) Provision(client *acme.Client, ident acme.AuthzID, chall *acme.Challenge) error {
path := client.HTTP01ChallengePath(chall.Token)
body, err := client.HTTP01ChallengeResponse(chall.Token)
if err != nil {
return fmt.Errorf("failed to generate HTTP-01 challenge response for %v challenge %s token %s: %w",
ident, chall.URI, chall.Token, err)
}
c.mu.Lock()
defer c.mu.Unlock()
log.Printf("challHTTPServer: setting challenge response for %s", path)
c.challMap[path] = body
return nil
}
func (c *challHTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log.Printf("challHTTPServer: handling %s to %s from %s", r.Method, r.URL.Path, r.RemoteAddr)
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
c.mu.RLock()
defer c.mu.RUnlock()
response, exists := c.challMap[r.URL.Path]
if !exists {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte(response))
}
func (c *challHTTPServer) Shutdown() error {
log.Printf("challHTTPServer: shutting down")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return c.Server.Shutdown(ctx)
}
func (c *challHTTPServer) Run() {
go func() {
if err := c.Server.ListenAndServe(); err != nil {
if !errors.Is(err, http.ErrServerClosed) {
log.Printf("challHTTPServer error: %v", err)
}
}
}()
}
func testIssuance(t *testing.T, env *environment, challSrv challengeServer) {
t.Helper()
// Bound the total issuance process by a timeout of 60 seconds.
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
// Create a new ACME account.
client := env.client
acct, err := client.Register(ctx, &acme.Account{}, acme.AcceptTOS)
if err != nil {
t.Fatalf("failed to register account: %v", err)
}
if acct.Status != acme.StatusValid {
t.Fatalf("expected new account status to be valid, got %v", acct.Status)
}
log.Printf("registered account: %s", acct.URI)
// Create a new order for some example identifiers
identifiers := []acme.AuthzID{
{
Type: "dns",
Value: "example.com",
},
{
Type: "dns",
Value: "www.example.com",
},
{
Type: "ip",
Value: "127.0.0.1",
},
}
order, err := client.AuthorizeOrder(ctx, identifiers)
if err != nil {
t.Fatalf("failed to create order for %v: %v", identifiers, err)
}
if order.Status != acme.StatusPending {
t.Fatalf("expected new order status to be pending, got %v", order.Status)
}
orderURL := order.URI
log.Printf("created order: %v", orderURL)
// For each pending authz provision a supported challenge type's response
// with the test challenge server, and tell the ACME server to verify it.
for _, authzURL := range order.AuthzURLs {
authz, err := client.GetAuthorization(ctx, authzURL)
if err != nil {
t.Fatalf("failed to get order %s authorization %s: %v",
orderURL, authzURL, err)
}
if authz.Status != acme.StatusPending {
continue
}
for _, challenge := range authz.Challenges {
if challenge.Status != acme.StatusPending || !challSrv.Supported(challenge) {
continue
}
if err := challSrv.Provision(client, authz.Identifier, challenge); err != nil {
t.Fatalf("failed to provision challenge %s: %v", challenge.URI, err)
}
_, err = client.Accept(ctx, challenge)
if err != nil {
t.Fatalf("failed to accept order %s challenge %s: %v",
orderURL, challenge.URI, err)
}
}
}
// Wait for the order to become ready for finalization.
order, err = client.WaitOrder(ctx, order.URI)
if err != nil {
var orderErr *acme.OrderError
if errors.As(err, &orderErr) {
t.Fatalf("failed to wait for order %s: %s: %s", orderURL, err, orderErr.Problem)
} else {
t.Fatalf("failed to wait for order %s: %s", orderURL, err)
}
}
if order.Status != acme.StatusReady {
t.Fatalf("expected order %s status to be ready, got %v",
orderURL, order.Status)
}
// Generate a certificate keypair and a CSR for the order identifiers.
certKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("failed to generate certificate key: %v", err)
}
var dnsNames []string
var ipAddresses []net.IP
for _, ident := range identifiers {
switch ident.Type {
case "dns":
dnsNames = append(dnsNames, ident.Value)
case "ip":
ipAddresses = append(ipAddresses, net.ParseIP(ident.Value))
default:
t.Fatalf("unsupported identifier type: %s", ident.Type)
}
}
csrDer, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{
DNSNames: dnsNames,
IPAddresses: ipAddresses,
}, certKey)
if err != nil {
t.Fatalf("failed to create CSR: %v", err)
}
// Finalize the order by creating a certificate with our CSR.
chain, _, err := client.CreateCertFromOrder(ctx, order, csrDer, true)
if err != nil {
t.Fatalf("failed to finalize order %s with finalize URL %s: %v",
orderURL, order.FinalizeURL, err)
}
// Split the chain into the leaf and any intermediates.
leaf := chain[0]
intermediatesDER := chain[1:]
leafCert, err := x509.ParseCertificate(leaf)
if err != nil {
t.Fatalf("failed to parse order %s leaf certificate: %v", orderURL, err)
}
intermediates := x509.NewCertPool()
for i, intermediateDER := range intermediatesDER {
intermediate, err := x509.ParseCertificate(intermediateDER)
if err != nil {
t.Fatalf("failed to parse intermediate %d: %v", i, err)
}
intermediates.AddCert(intermediate)
}
// Verify there is a valid path from the leaf certificate to Pebble's
// issuing root using the provided intermediate certificates.
roots, err := env.RootCert()
if err != nil {
t.Fatalf("failed to get Pebble issuer root certs: %v", err)
}
paths, err := leafCert.Verify(x509.VerifyOptions{
Intermediates: intermediates,
Roots: roots,
})
if err != nil {
t.Fatalf("failed to verify order %s leaf certificate: %v", orderURL, err)
}
log.Printf("verified %d path(s) from issued leaf certificate to Pebble root CA", len(paths))
// Also verify that the leaf cert is valid for each of the DNS names
// and IP addresses from our order's identifiers.
for _, name := range dnsNames {
if err := leafCert.VerifyHostname(name); err != nil {
t.Fatalf("failed to verify order %s leaf certificate for order DNS name %s: %v",
orderURL, name, err)
}
}
for _, ip := range ipAddresses {
if err := leafCert.VerifyHostname(ip.String()); err != nil {
t.Fatalf("failed to verify order %s leaf certificate for order IP address %s: %v",
orderURL, ip, err)
}
}
}
type environment struct {
config *environmentConfig
client *acme.Client
}
// RootCert returns the Pebble CA's primary issuing hierarchy root certificate.
// This is generated randomly at each startup and can be used to verify
// certificate chains issued by Pebble's ACME interface. Note that this
// is separate from the static root certificate used by the Pebble ACME
// HTTPS interface.
func (e *environment) RootCert() (*x509.CertPool, error) {
// NOTE: in the future we may want to consider the alternative chains
// returned as Link alternative headers.
rootURL := fmt.Sprintf("https://%s/roots/0", e.config.pebbleConfig.ManagementListenAddress)
resp, err := e.client.HTTPClient.Get(rootURL)
if err != nil || resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to GET Pebble root CA from %s: %v", rootURL, err)
}
roots := x509.NewCertPool()
rootPEM, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to parse Pebble root CA PEM: %v", err)
}
rootDERBlock, _ := pem.Decode(rootPEM)
rootCA, err := x509.ParseCertificate(rootDERBlock.Bytes)
if err != nil {
return nil, fmt.Errorf("failed to parse Pebble root CA DER: %v", err)
}
roots.AddCert(rootCA)
return roots, nil
}
// environmentConfig describes the Pebble configuration, and configuration
// shared between pebble and pebble-challtestsrv.
type environmentConfig struct {
pebbleConfig
dnsPort uint32
}
// defaultConfig returns an environmentConfig populated with default values.
// The provided pebbleDir is used to specify certificate/private key paths
// for the HTTPS ACME interface.
func defaultConfig(pebbleDir string) environmentConfig {
return environmentConfig{
pebbleConfig: pebbleConfig{
ListenAddress: fmt.Sprintf("127.0.0.1:%d", takeNextPort()),
ManagementListenAddress: fmt.Sprintf("127.0.0.1:%d", takeNextPort()),
HTTPPort: takeNextPort(),
TLSPort: takeNextPort(),
Certificate: fmt.Sprintf("%s/test/certs/localhost/cert.pem", pebbleDir),
PrivateKey: fmt.Sprintf("%s/test/certs/localhost/key.pem", pebbleDir),
OCSPResponderURL: "",
ExternalAccountBindingRequired: false,
ExternalAccountMACKeys: make(map[string]string),
DomainBlocklist: []string{"blocked-domain.example"},
Profiles: map[string]struct {
Description string
ValidityPeriod uint64
}{
"default": {
Description: "default profile",
ValidityPeriod: 3600,
},
},
RetryAfter: struct {
Authz int
Order int
}{
3,
5,
},
},
dnsPort: takeNextPort(),
}
}
// pebbleConfig matches the JSON structure of the Pebble configuration file.
type pebbleConfig struct {
ListenAddress string
ManagementListenAddress string
HTTPPort uint32
TLSPort uint32
Certificate string
PrivateKey string
OCSPResponderURL string
ExternalAccountBindingRequired bool
ExternalAccountMACKeys map[string]string
DomainBlocklist []string
Profiles map[string]struct {
Description string
ValidityPeriod uint64
}
RetryAfter struct {
Authz int
Order int
}
}
func takeNextPort() uint32 {
return nextPort.Add(1) - 1
}
// startPebbleEnvironment is a test helper that spawns Pebble and Pebble
// challenge test server processes based on the provided environmentConfig. The
// processes will be torn down when the test ends.
func startPebbleEnvironment(t *testing.T, config *environmentConfig) environment {
t.Helper()
var pebbleDir string
if *pebbleLocalDir != "" {
pebbleDir = *pebbleLocalDir
} else {
pebbleDir = fetchModule(t, "github.com/letsencrypt/pebble/v2", pebbleModVersion)
}
binDir := prepareBinaries(t, pebbleDir)
if config == nil {
cfg := defaultConfig(pebbleDir)
config = &cfg
}
marshalConfig := struct {
Pebble pebbleConfig
}{
Pebble: config.pebbleConfig,
}
configData, err := json.Marshal(marshalConfig)
if err != nil {
t.Fatalf("failed to marshal config: %v", err)
}
configFile, err := os.CreateTemp("", "pebble-config-*.json")
if err != nil {
t.Fatalf("failed to create temp config file: %v", err)
}
t.Cleanup(func() { os.Remove(configFile.Name()) })
if _, err := configFile.Write(configData); err != nil {
t.Fatalf("failed to write config file: %v", err)
}
configFile.Close()
log.Printf("pebble dir: %s", pebbleDir)
log.Printf("config file: %s", configFile.Name())
// Spawn the Pebble CA server. It answers ACME requests and performs
// outbound validations. We configure it to use a mock DNS server that
// always answers 127.0.0.1 for all A queries so that validation
// requests for any domain name will resolve to our local challenge
// server instances.
spawnServerProcess(t, binDir, "pebble", "-config", configFile.Name(),
"-dnsserver", fmt.Sprintf("127.0.0.1:%d", config.dnsPort),
"-strict")
// Spawn the Pebble challenge test server. We'll use it to mock DNS
// responses but disable all the other interfaces. We want to stand
// up our own challenge response servers for TLS-ALPN-01,
// etc.
// Note: we specify -defaultIPv6 "" so that no AAAA records are served.
// The LUCI CI runners have issues with IPv6 connectivity on localhost.
spawnServerProcess(t, binDir, "pebble-challtestsrv",
"-dnsserver", fmt.Sprintf(":%d", config.dnsPort),
"-defaultIPv6", "",
"-management", fmt.Sprintf(":%d", takeNextPort()),
"-doh", "",
"-http01", "",
"-tlsalpn01", "",
"-https01", "")
waitForServer(t, config.pebbleConfig.ListenAddress)
waitForServer(t, fmt.Sprintf("127.0.0.1:%d", config.dnsPort))
log.Printf("pebble environment ready")
// Construct a cert pool that contains the CA certificate used by the ACME
// interface's certificate chain. This is separate from the issuing
// hierarchy and is used for the ACME client to interact with the ACME
// interface without cert verification error.
caCertPath := filepath.Join(pebbleDir, "test/certs/pebble.minica.pem")
caCert, err := os.ReadFile(caCertPath)
if err != nil {
t.Fatalf("failed to read CA certificate %s: %v", caCertPath, err)
}
caCertPool := x509.NewCertPool()
if !caCertPool.AppendCertsFromPEM(caCert) {
t.Fatalf("failed to parse CA certificate %s", caCertPath)
}
httpClient := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: caCertPool,
},
},
}
// Create an ACME account keypair/client and verify it can discover
// the Pebble server's ACME directory without error.
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("failed to generate account key: %v", err)
}
client := &acme.Client{
Key: key,
HTTPClient: httpClient,
DirectoryURL: fmt.Sprintf("https://%s/dir", config.ListenAddress),
}
_, err = client.Discover(context.TODO())
if err != nil {
t.Fatalf("failed to discover ACME directory: %v", err)
}
return environment{
config: config,
client: client,
}
}
func waitForServer(t *testing.T, addr string) {
t.Helper()
for i := 0; i < 20; i++ {
if conn, err := net.Dial("tcp", addr); err == nil {
conn.Close()
return
}
time.Sleep(time.Duration(i*100) * time.Millisecond)
}
t.Fatalf("failed to connect to %q after 20 tries", addr)
}
// fetchModule fetches the module at the given version and returns the directory
// containing its source tree. It skips the test if fetching modules is not
// possible in this environment.
//
// Copied from the stdlib cryptotest.FetchModule and adapted to not rely on the
// stdlib internal testenv package.
func fetchModule(t *testing.T, module, version string) string {
// If the default GOMODCACHE doesn't exist, use a temporary directory
// instead. (For example, run.bash sets GOPATH=/nonexist-gopath.)
out, err := exec.Command("go", "env", "GOMODCACHE").Output()
if err != nil {
t.Errorf("go env GOMODCACHE: %v\n%s", err, out)
if ee, ok := err.(*exec.ExitError); ok {
t.Logf("%s", ee.Stderr)
}
t.FailNow()
}
modcacheOk := false
if gomodcache := string(bytes.TrimSpace(out)); gomodcache != "" {
if _, err := os.Stat(gomodcache); err == nil {
modcacheOk = true
}
}
if !modcacheOk {
t.Setenv("GOMODCACHE", t.TempDir())
// Allow t.TempDir() to clean up subdirectories.
t.Setenv("GOFLAGS", os.Getenv("GOFLAGS")+" -modcacherw")
}
t.Logf("fetching %s@%s\n", module, version)
output, err := exec.Command("go", "mod", "download", "-json", module+"@"+version).CombinedOutput()
if err != nil {
t.Fatalf("failed to download %s@%s: %s\n%s\n", module, version, err, output)
}
var j struct {
Dir string
}
if err := json.Unmarshal(output, &j); err != nil {
t.Fatalf("failed to parse 'go mod download': %s\n%s\n", err, output)
}
return j.Dir
}
func prepareBinaries(t *testing.T, pebbleDir string) string {
t.Helper()
// We don't want to build in the module cache dir, which might not be
// writable or to pollute the user's clone with binaries if pebbleLocalDir
// is used.
binDir := t.TempDir()
build := func(cmd string) {
log.Printf("building %s", cmd)
buildCmd := exec.Command(
"go",
"build", "-o", filepath.Join(binDir, cmd), "-mod", "mod", "./cmd/"+cmd)
buildCmd.Dir = pebbleDir
output, err := buildCmd.CombinedOutput()
if err != nil {
t.Fatalf("failed to build %s: %s\n%s\n", cmd, err, output)
}
}
build("pebble")
build("pebble-challtestsrv")
return binDir
}
func spawnServerProcess(t *testing.T, dir string, cmd string, args ...string) {
t.Helper()
var stdout, stderr bytes.Buffer
cmdInstance := exec.Command("./"+cmd, args...)
cmdInstance.Dir = dir
cmdInstance.Stdout = &stdout
cmdInstance.Stderr = &stderr
if err := cmdInstance.Start(); err != nil {
t.Fatalf("failed to start %s: %v", cmd, err)
}
t.Cleanup(func() {
cmdInstance.Process.Kill()
cmdInstance.Wait()
if t.Failed() || testing.Verbose() {
t.Logf("=== %s output ===", cmd)
if stdout.Len() > 0 {
t.Logf("stdout:\n%s", strings.TrimSpace(stdout.String()))
}
if stderr.Len() > 0 {
t.Logf("stderr:\n%s", strings.TrimSpace(stderr.String()))
}
}
})
}
+53 -8
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)
}
@@ -194,7 +197,7 @@ func (c *Client) accountKeyRollover(ctx context.Context, newKey crypto.Signer) e
// identify those with StatusPending status and fulfill a challenge using Accept.
// Once all authorizations are satisfied, the caller will typically want to poll
// order status using WaitOrder until it's in StatusReady state.
// To finalize the order and obtain a certificate, the caller submits a CSR with CreateOrderCert.
// To finalize the order and obtain a certificate, the caller submits a CSR with CreateCertFromOrder.
func (c *Client) AuthorizeOrder(ctx context.Context, id []AuthzID, opt ...OrderOption) (*Order, error) {
dir, err := c.Discover(ctx)
if err != nil {
@@ -232,7 +235,7 @@ func (c *Client) AuthorizeOrder(ctx context.Context, id []AuthzID, opt ...OrderO
return responseOrder(res)
}
// GetOrder retrives an order identified by the given URL.
// GetOrder retrieves an order identified by the given URL.
// For orders created with AuthorizeOrder, the url value is Order.URI.
//
// If a caller needs to poll an order until its status is final,
@@ -247,7 +250,11 @@ func (c *Client) GetOrder(ctx context.Context, url string) (*Order, error) {
return nil, err
}
defer res.Body.Close()
return responseOrder(res)
o, err := responseOrder(res)
if err == nil && o.URI == "" {
o.URI = url
}
return o, err
}
// WaitOrder polls an order from the given URL until it is in one of the final states,
@@ -268,11 +275,14 @@ func (c *Client) WaitOrder(ctx context.Context, url string) (*Order, error) {
}
o, err := responseOrder(res)
res.Body.Close()
if err == nil && o.URI == "" {
o.URI = url
}
switch {
case err != nil:
// Skip and retry.
case o.Status == StatusInvalid:
return nil, &OrderError{OrderURL: o.URI, Status: o.Status}
return nil, &OrderError{OrderURL: o.URI, Status: o.Status, Problem: o.Error}
case o.Status == StatusReady || o.Status == StatusValid:
return o, nil
}
@@ -335,11 +345,43 @@ func responseOrder(res *http.Response) (*Order, error) {
// certificate chain. Otherwise, only a leaf certificate is returned.
// The returned URL can be used to re-fetch the certificate using FetchCert.
//
// This method is only supported by CAs implementing RFC 8555. See CreateCert for pre-RFC CAs.
// This method is only supported by CAs implementing RFC 8555 that return a
// Location header for order finalization responses. Most users should prefer
// CreateCertFromOrder, an alternative that has better interoperation with RFC 8555
// compliant CAs. See CreateCert for pre-RFC CAs.
//
// CreateOrderCert returns an error if the CA's response is unreasonably large.
// Callers are encouraged to parse the returned value to ensure the certificate is valid and has the expected features.
func (c *Client) CreateOrderCert(ctx context.Context, url string, csr []byte, bundle bool) (der [][]byte, certURL string, err error) {
return c.createOrderCert(ctx, url, "", csr, bundle)
}
// CreateCertFromOrder submits the CSR (Certificate Signing Request) to a CA for
// the specified Order created with AuthorizeOrder.
//
// If the bundle argument is true, the returned value also contain the CA (issuer)
// certificate chain. Otherwise, only a leaf certificate is returned.
// The returned URL can be used to re-fetch the certificate using FetchCert.
//
// This method is only supported by CAs implementing RFC 8555.
// See CreateCert for pre-RFC CAs.
//
// CreateCertFromOrder returns an error if the CA's response is unreasonably large.
// Callers are encouraged to parse the returned value to ensure the certificate is valid and has the expected features.
func (c *Client) CreateCertFromOrder(ctx context.Context, order *Order, csr []byte, bundle bool) (der [][]byte, certURL string, err error) {
if order == nil {
return nil, "", errors.New("acme: nil order")
}
if order.URI == "" {
return nil, "", errors.New("acme: order URI is empty")
}
if order.FinalizeURL == "" {
return nil, "", errors.New("acme: order finalize URL is empty")
}
return c.createOrderCert(ctx, order.FinalizeURL, order.URI, csr, bundle)
}
func (c *Client) createOrderCert(ctx context.Context, finalizeURL, orderURL string, csr []byte, bundle bool) (der [][]byte, certURL string, err error) {
if _, err := c.Discover(ctx); err != nil { // required by c.accountKID
return nil, "", err
}
@@ -350,7 +392,7 @@ func (c *Client) CreateOrderCert(ctx context.Context, url string, csr []byte, bu
}{
CSR: base64.RawURLEncoding.EncodeToString(csr),
}
res, err := c.post(ctx, nil, url, req, wantStatus(http.StatusOK))
res, err := c.post(ctx, nil, finalizeURL, req, wantStatus(http.StatusOK))
if err != nil {
return nil, "", err
}
@@ -362,14 +404,17 @@ func (c *Client) CreateOrderCert(ctx context.Context, url string, csr []byte, bu
// Wait for CA to issue the cert if they haven't.
if o.Status != StatusValid {
o, err = c.WaitOrder(ctx, o.URI)
if orderURL == "" {
orderURL = o.URI
}
o, err = c.WaitOrder(ctx, orderURL)
}
if err != nil {
return nil, "", err
}
// The only acceptable status post finalize and WaitOrder is "valid".
if o.Status != StatusValid {
return nil, "", &OrderError{OrderURL: o.URI, Status: o.Status}
return nil, "", &OrderError{OrderURL: o.URI, Status: o.Status, Problem: o.Error}
}
crt, err := c.fetchCertRFC(ctx, o.CertURL, bundle)
return crt, o.CertURL, err
+90 -3
View File
@@ -885,11 +885,17 @@ func TestRFC_WaitOrderError(t *testing.T) {
s.handle("/orders/1", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Location", s.url("/orders/1"))
w.WriteHeader(http.StatusOK)
s := StatusPending
if count > 0 {
s = StatusInvalid
// https://www.rfc-editor.org/rfc/rfc8555#section-7.3.3
errorData := `{
"type": "urn:ietf:params:acme:error:userActionRequired",
"detail": "Terms of service have changed",
"instance": "https://example.com/acme/agreement/?token=W8Ih3PswD-8"
}`
fmt.Fprintf(w, `{"status": %q, "error": %s}`, StatusInvalid, errorData)
} else {
fmt.Fprintf(w, `{"status": %q}`, StatusPending)
}
fmt.Fprintf(w, `{"status": %q}`, s)
count++
})
s.start()
@@ -910,6 +916,13 @@ func TestRFC_WaitOrderError(t *testing.T) {
if e.Status != StatusInvalid {
t.Errorf("e.Status = %q; want %q", e.Status, StatusInvalid)
}
if e.Problem == nil {
t.Errorf("e.Problem = nil")
}
expectedProbType := "urn:ietf:params:acme:error:userActionRequired"
if e.Problem.ProblemType != expectedProbType {
t.Errorf("e.Problem.ProblemType = %q; want %q", e.Problem.ProblemType, expectedProbType)
}
}
func TestRFC_CreateOrderCert(t *testing.T) {
@@ -966,6 +979,80 @@ func TestRFC_CreateOrderCert(t *testing.T) {
}
}
// TestRFC_CreateCertFromOrder tests that finalization responses work even when
// they omit a Location header. Such a header isn't required by RFC 8555 in this
// context and we should be able to complete an order without needing it.
func TestRFC_CreateCertFromOrder(t *testing.T) {
q := &x509.CertificateRequest{
Subject: pkix.Name{CommonName: "example.org"},
}
csr, err := x509.CreateCertificateRequest(rand.Reader, q, testKeyEC)
if err != nil {
t.Fatal(err)
}
tmpl := &x509.Certificate{SerialNumber: big.NewInt(1)}
leaf, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &testKeyEC.PublicKey, testKeyEC)
if err != nil {
t.Fatal(err)
}
s := newACMEServer()
s.handle("/acme/new-account", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Location", s.url("/accounts/1"))
w.Write([]byte(`{"status": "valid"}`))
})
s.handle("/finalize", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"status":"processing"}`)
})
s.handle("/orders/1", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, `{"status":"valid", "certificate":%q}`, s.url("/crt"))
})
s.handle("/crt", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/pem-certificate-chain")
pem.Encode(w, &pem.Block{Type: "CERTIFICATE", Bytes: leaf})
})
s.start()
defer s.close()
cl := &Client{Key: testKeyEC, DirectoryURL: s.url("/")}
order := &Order{URI: s.url("/orders/1"), FinalizeURL: s.url("/finalize")}
cert, curl, err := cl.CreateCertFromOrder(context.Background(), order, csr, true)
if err != nil {
t.Fatalf("CreateCertFromOrder: %v", err)
}
if _, err := x509.ParseCertificate(cert[0]); err != nil {
t.Errorf("ParseCertificate: %v", err)
}
if !reflect.DeepEqual(cert[0], leaf) {
t.Errorf("cert and leaf bytes don't match")
}
if u := s.url("/crt"); curl != u {
t.Errorf("curl = %q; want %q", curl, u)
}
}
// TestRFC_CreateCertFromOrderInvalidOrder tests that invalid CreateCertFromOrder
// calls fail before making a request.
func TestRFC_CreateCertFromOrderInvalidOrder(t *testing.T) {
cl := new(Client)
tests := []struct {
name string
order *Order
}{
{"nil", nil},
{"empty URI", &Order{FinalizeURL: "https://example.com/finalize"}},
{"empty finalize URL", &Order{URI: "https://example.com/order/1"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if _, _, err := cl.CreateCertFromOrder(context.Background(), tt.order, nil, false); err == nil {
t.Fatal("CreateCertFromOrder returned nil error")
}
})
}
}
func TestRFC_AlreadyRevokedCert(t *testing.T) {
s := newACMEServer()
s.handle("/acme/revoke-cert", func(w http.ResponseWriter, r *http.Request) {
+31 -8
View File
@@ -7,6 +7,7 @@ package acme
import (
"crypto"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"net/http"
@@ -55,6 +56,10 @@ var (
// ErrNoAccount indicates that the Client's key has not been registered with the CA.
ErrNoAccount = errors.New("acme: account does not exist")
// errPreAuthorizationNotSupported indicates that the server does not
// support pre-authorization of identifiers.
errPreAuthorizationNotSupported = errors.New("acme: pre-authorization is not supported")
)
// A Subproblem describes an ACME subproblem as reported in an Error.
@@ -109,14 +114,15 @@ type Error struct {
}
func (e *Error) Error() string {
str := fmt.Sprintf("%d %s: %s", e.StatusCode, e.ProblemType, e.Detail)
var sb strings.Builder
fmt.Fprintf(&sb, "%d %s: %s", e.StatusCode, e.ProblemType, e.Detail)
if len(e.Subproblems) > 0 {
str += fmt.Sprintf("; subproblems:")
sb.WriteString("; subproblems:")
for _, sp := range e.Subproblems {
str += fmt.Sprintf("\n\t%s", sp)
fmt.Fprintf(&sb, "\n\t%s", sp)
}
}
return str
return sb.String()
}
// AuthorizationError indicates that an authorization for an identifier
@@ -149,17 +155,24 @@ func (a *AuthorizationError) Error() string {
// OrderError is returned from Client's order related methods.
// It indicates the order is unusable and the clients should start over with
// AuthorizeOrder.
// AuthorizeOrder. A Problem description may be provided with details on
// what caused the order to become unusable.
//
// The clients can still fetch the order object from CA using GetOrder
// to inspect its state.
type OrderError struct {
OrderURL string
Status string
// Problem is the error that occurred while processing the order.
Problem *Error
}
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
@@ -317,7 +330,7 @@ type Order struct {
// Possible values are StatusPending, StatusReady, StatusProcessing, StatusValid and StatusInvalid.
// Pending means the CA does not believe that the client has fulfilled the requirements.
// Ready indicates that the client has fulfilled all the requirements and can submit a CSR
// to obtain a certificate. This is done with Client's CreateOrderCert.
// to obtain a certificate. This is done with Client's CreateCertFromOrder.
// Processing means the certificate is being issued.
// Valid indicates the CA has issued the certificate. It can be downloaded
// from the Order's CertURL. This is done with Client's FetchCert.
@@ -527,6 +540,16 @@ type Challenge struct {
// when this challenge was used.
// The type of a non-nil value is *Error.
Error error
// Payload is the JSON-formatted payload that the client sends
// to the server to indicate it is ready to respond to the challenge.
// When unset, it defaults to an empty JSON object: {}.
// For most challenges, the client must not set Payload,
// see https://tools.ietf.org/html/rfc8555#section-7.5.1.
// Payload is used only for newer challenges (such as "device-attest-01")
// where the client must send additional data for the server to validate
// the challenge.
Payload json.RawMessage
}
// wireChallenge is ACME JSON challenge representation.
@@ -604,7 +627,7 @@ func (*certOptKey) privateCertOpt() {}
//
// In TLS ChallengeCert methods, the template is also used as parent,
// resulting in a self-signed certificate.
// The DNSNames field of t is always overwritten for tls-sni challenge certs.
// The DNSNames or IPAddresses fields of t are always overwritten for tls-alpn challenge certs.
func WithTemplate(t *x509.Certificate) CertOption {
return (*certOptTemplate)(t)
}
+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 -2
View File
@@ -4,12 +4,12 @@ go 1.23
require (
github.com/mmcloughlin/avo v0.6.0
golang.org/x/crypto v0.26.0
golang.org/x/crypto v0.33.0
)
require (
golang.org/x/mod v0.20.0 // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/sys v0.24.0 // indirect
golang.org/x/sys v0.30.0 // indirect
golang.org/x/tools v0.24.0 // indirect
)
+4 -4
View File
@@ -1,12 +1,12 @@
github.com/mmcloughlin/avo v0.6.0 h1:QH6FU8SKoTLaVs80GA8TJuLNkUYl4VokHKlPhVDg4YY=
github.com/mmcloughlin/avo v0.6.0/go.mod h1:8CoAGaCSYXtCPR+8y18Y9aB/kxb8JSS6FRI7mSkvD+8=
golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw=
golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54=
golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus=
golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M=
golang.org/x/mod v0.20.0 h1:utOm6MM3R3dnawAiJgn0y+xvuYRsm1RKM/4giyfDgV0=
golang.org/x/mod v0.20.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/tools v0.24.0 h1:J1shsA93PJUEVaUSaay7UXAyE8aimq3GW0pjlolpa24=
golang.org/x/tools v0.24.0/go.mod h1:YhNqVBIfWHdzvTLs0d8LCuMhkKUgSUKldakyV7W/WDQ=
+22 -17
View File
@@ -6,7 +6,7 @@
// Argon2 was selected as the winner of the Password Hashing Competition and can
// be used to derive cryptographic keys from passwords.
//
// For a detailed specification of Argon2 see [1].
// For a detailed specification of Argon2 see [argon2-specs.pdf].
//
// If you aren't sure which function you need, use Argon2id (IDKey) and
// the parameter recommendations for your scenario.
@@ -17,8 +17,8 @@
// It uses data-independent memory access, which is preferred for password
// hashing and password-based key derivation. Argon2i requires more passes over
// memory than Argon2id to protect from trade-off attacks. The recommended
// parameters (taken from [2]) for non-interactive operations are time=3 and to
// use the maximum available memory.
// parameters (taken from [RFC 9106 Section 7.3]) for non-interactive
// operations are time=3 and to use the maximum available memory.
//
// # Argon2id
//
@@ -26,12 +26,15 @@
// Argon2i and Argon2d. It uses data-independent memory access for the first
// half of the first iteration over the memory and data-dependent memory access
// for the rest. Argon2id is side-channel resistant and provides better brute-
// force cost savings due to time-memory tradeoffs than Argon2i. The recommended
// parameters for non-interactive operations (taken from [2]) are time=1 and to
// use the maximum available memory.
// force cost savings due to time-memory tradeoffs than Argon2i. [RFC 9106
// Section 4] recommends time=1, memory=2*1024*1024 KiB (2 GiB), and threads=4
// as the first recommended option. If much less memory is available, it
// recommends time=3, memory=64*1024 KiB (64 MiB), and threads=4 as the second
// recommended option.
//
// [1] https://github.com/P-H-C/phc-winner-argon2/blob/master/argon2-specs.pdf
// [2] https://tools.ietf.org/html/draft-irtf-cfrg-argon2-03#section-9.3
// [argon2-specs.pdf]: https://github.com/P-H-C/phc-winner-argon2/blob/master/argon2-specs.pdf
// [RFC 9106 Section 4]: https://www.rfc-editor.org/rfc/rfc9106.html#section-4
// [RFC 9106 Section 7.3]: https://www.rfc-editor.org/rfc/rfc9106.html#section-7.3
package argon2
import (
@@ -59,9 +62,9 @@ const (
//
// key := argon2.Key([]byte("some password"), salt, 3, 32*1024, 4, 32)
//
// The draft RFC recommends[2] time=3, and memory=32*1024 is a sensible number.
// If using that amount of memory (32 MB) is not possible in some contexts then
// the time parameter can be increased to compensate.
// The example above uses time=3 and memory=32*1024. Argon2i generally
// requires more passes over memory than Argon2id. If in doubt, prefer IDKey
// and its Argon2id parameter recommendations.
//
// The time parameter specifies the number of passes over the memory and the
// memory parameter specifies the size of the memory in KiB. For example
@@ -81,18 +84,20 @@ func Key(password, salt []byte, time, memory uint32, threads uint8, keyLen uint3
// For example, you can get a derived key for e.g. AES-256 (which needs a
// 32-byte key) by doing:
//
// key := argon2.IDKey([]byte("some password"), salt, 1, 64*1024, 4, 32)
// key := argon2.IDKey([]byte("some password"), salt, 1, 2*1024*1024, 4, 32)
//
// The draft RFC recommends[2] time=1, and memory=64*1024 is a sensible number.
// If using that amount of memory (64 MB) is not possible in some contexts then
// the time parameter can be increased to compensate.
// The example above uses the first [RFC 9106 Section 4] recommended option.
// If much less memory is available, the second recommended option is time=3,
// memory=64*1024 KiB (64 MiB), and threads=4.
//
// The time parameter specifies the number of passes over the memory and the
// memory parameter specifies the size of the memory in KiB. For example
// memory=64*1024 sets the memory cost to ~64 MB. The number of threads can be
// adjusted to the numbers of available CPUs. The cost parameters should be
// memory=2*1024*1024 sets the memory cost to ~2 GiB. The number of threads can
// be adjusted to the numbers of available CPUs. The cost parameters should be
// increased as memory latency and CPU parallelism increases. Remember to get a
// good random salt.
//
// [RFC 9106 Section 4]: https://www.rfc-editor.org/rfc/rfc9106.html#section-4
func IDKey(password, salt []byte, time, memory uint32, threads uint8, keyLen uint32) []byte {
return deriveKey(argon2id, password, salt, nil, nil, time, memory, threads, keyLen)
}
+9
View File
@@ -24,6 +24,7 @@ var (
func TestArgon2(t *testing.T) {
defer func(sse4 bool) { useSSE4 = sse4 }(useSSE4)
defer func(lsx bool) { useLSX = lsx }(useLSX)
if useSSE4 {
t.Log("SSE4.1 version")
@@ -32,6 +33,14 @@ func TestArgon2(t *testing.T) {
testArgon2id(t)
useSSE4 = false
}
if useLSX {
t.Log("LSX version")
testArgon2i(t)
testArgon2d(t)
testArgon2id(t)
useLSX = false
}
t.Log("generic version")
testArgon2i(t)
testArgon2d(t)
+4
View File
@@ -6,6 +6,10 @@ package argon2
var useSSE4 bool
// useLSX reports whether the loong64 LSX vector implementation should be
// used. It is set from cpu.Loong64.HasLSX in blamka_loong64.go's init().
var useLSX bool
func processBlockGeneric(out, in1, in2 *block, xor bool) {
var t block
for i := range t {
+49
View File
@@ -0,0 +1,49 @@
// 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.
//go:build loong64 && gc && !purego
package argon2
import "golang.org/x/sys/cpu"
func init() {
// useLSX (declared in blamka_generic.go) gates the LSX vector path.
// If the running CPU lacks LSX support, processBlockVX falls back
// to processBlockGeneric.
useLSX = cpu.Loong64.HasLSX
}
//go:noescape
func blamkaLOONG64(b *block)
//go:noescape
func mixBlocksVX(out, a, b, c *block)
//go:noescape
func xorBlocksVX(out, a, b, c *block)
func processBlock(out, in1, in2 *block) {
processBlockVX(out, in1, in2, false)
}
func processBlockXOR(out, in1, in2 *block) {
processBlockVX(out, in1, in2, true)
}
func processBlockVX(out, in1, in2 *block, xor bool) {
if !useLSX {
processBlockGeneric(out, in1, in2, xor)
return
}
var t block
mixBlocksVX(&t, in1, in2, &t)
blamkaLOONG64(&t)
if xor {
xorBlocksVX(out, in1, in2, &t)
} else {
mixBlocksVX(out, in1, in2, &t)
}
}
+240
View File
@@ -0,0 +1,240 @@
// 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.
//go:build loong64 && gc && !purego
#include "textflag.h"
// HALF_ROUND applies one BlaMka half-round (mul-add-xor-rotate) to two
// groups of 4 columns, each packed 2-wide into V registers (v0/v2/v4/v6
// hold one pair of columns in lane0/lane1, v1/v3/v5/v7 hold the other).
// t0, t1 are scratch registers, one per independent column group.
#define HALF_ROUND(v0, v1, v2, v3, v4, v5, v6, v7, t0, t1) \
VMULWEVVWU v0, v2, t0; \
VADDV t0, t0, t0; \
VADDV v0, v2, v0; \
VADDV v0, t0, v0; \
VXORV v6, v0, v6; \
VROTRV $32, v6, v6; \
VMULWEVVWU v1, v3, t1; \
VADDV t1, t1, t1; \
VADDV v1, v3, v1; \
VADDV v1, t1, v1; \
VXORV v7, v1, v7; \
VROTRV $32, v7, v7; \
VMULWEVVWU v4, v6, t0; \
VADDV t0, t0, t0; \
VADDV v4, v6, v4; \
VADDV v4, t0, v4; \
VXORV v2, v4, v2; \
VROTRV $24, v2, v2; \
VMULWEVVWU v5, v7, t1; \
VADDV t1, t1, t1; \
VADDV v5, v7, v5; \
VADDV v5, t1, v5; \
VXORV v3, v5, v3; \
VROTRV $24, v3, v3; \
VMULWEVVWU v0, v2, t0; \
VADDV t0, t0, t0; \
VADDV v0, v2, v0; \
VADDV v0, t0, v0; \
VXORV v6, v0, v6; \
VROTRV $16, v6, v6; \
VMULWEVVWU v1, v3, t1; \
VADDV t1, t1, t1; \
VADDV v1, v3, v1; \
VADDV v1, t1, v1; \
VXORV v7, v1, v7; \
VROTRV $16, v7, v7; \
VMULWEVVWU v4, v6, t0; \
VADDV t0, t0, t0; \
VADDV v4, v6, v4; \
VADDV v4, t0, v4; \
VXORV v2, v4, v2; \
VROTRV $63, v2, v2; \
VMULWEVVWU v5, v7, t1; \
VADDV t1, t1, t1; \
VADDV v5, v7, v5; \
VADDV v5, t1, v5; \
VXORV v3, v5, v3; \
VROTRV $63, v3, v3
// SHUFFLE / SHUFFLE_INV: reused verbatim from blake2b_loong64.s -- amd64
// avo source confirms argon2's SHUFFLE/SHUFFLE_INV and blake2b's SHUFFLE
// are byte-for-byte identical macros (diagonalize / undiagonalize),
// operating only on V2..V7 (V0/V1 untouched), with V13 held at zero.
#define SHUFFLE \
VADDV V2, V13, V12; \
VADDV V6, V13, V16; \
VADDV V4, V13, V14; \
VADDV V5, V13, V4; \
VADDV V14, V13, V5; \
VSHUF4IV $9, V3, V2; \
VSHUF4IV $9, V12, V3; \
VSHUF4IV $3, V7, V6; \
VSHUF4IV $3, V16, V7
#define SHUFFLE_INV \
VADDV V2, V13, V12; \
VADDV V6, V13, V16; \
VADDV V4, V13, V14; \
VADDV V5, V13, V4; \
VADDV V14, V13, V5; \
VSHUF4IV $3, V3, V2; \
VSHUF4IV $3, V12, V3; \
VSHUF4IV $9, V7, V6; \
VSHUF4IV $9, V16, V7
// LOAD_MSG_0 / STORE_MSG_0: row pass. `off` is the byte offset of the
// 128-byte (16-uint64) row group; within the macro the 8 loads step by
// 16B (2 uint64 per V register). Called from blamkaLOONG64 with off
// stepping by 128B across the 8 row groups -- do not confuse the two
// strides.
#define LOAD_MSG_0(off) \
VMOVQ (off+0)(R4), V0; \
VMOVQ (off+16)(R4), V1; \
VMOVQ (off+32)(R4), V2; \
VMOVQ (off+48)(R4), V3; \
VMOVQ (off+64)(R4), V4; \
VMOVQ (off+80)(R4), V5; \
VMOVQ (off+96)(R4), V6; \
VMOVQ (off+112)(R4), V7
#define STORE_MSG_0(off) \
VMOVQ V0, (off+0)(R4); \
VMOVQ V1, (off+16)(R4); \
VMOVQ V2, (off+32)(R4); \
VMOVQ V3, (off+48)(R4); \
VMOVQ V4, (off+64)(R4); \
VMOVQ V5, (off+80)(R4); \
VMOVQ V6, (off+96)(R4); \
VMOVQ V7, (off+112)(R4)
// LOAD_MSG_1 / STORE_MSG_1: diagonal pass. `off` is the byte offset within
// a 128-byte row group; within the macro the 8 loads step by 128B (one
// element from each of the 8 row groups, mirroring blamka_generic.go's
// t[off], t[128+off], t[256+off], ...). Called from blamkaLOONG64 with
// off stepping by 16B (2 uint64) across the 8 diagonal groups -- the
// inner/outer strides are swapped relative to LOAD_MSG_0/STORE_MSG_0.
#define LOAD_MSG_1(off) \
VMOVQ (off+0)(R4), V0; \
VMOVQ (off+128)(R4), V1; \
VMOVQ (off+256)(R4), V2; \
VMOVQ (off+384)(R4), V3; \
VMOVQ (off+512)(R4), V4; \
VMOVQ (off+640)(R4), V5; \
VMOVQ (off+768)(R4), V6; \
VMOVQ (off+896)(R4), V7
#define STORE_MSG_1(off) \
VMOVQ V0, (off+0)(R4); \
VMOVQ V1, (off+128)(R4); \
VMOVQ V2, (off+256)(R4); \
VMOVQ V3, (off+384)(R4); \
VMOVQ V4, (off+512)(R4); \
VMOVQ V5, (off+640)(R4); \
VMOVQ V6, (off+768)(R4); \
VMOVQ V7, (off+896)(R4)
// BLAMKA_ROUND_0(off): one full row pass over the 16-uint64 group at
// byte offset off -- corresponds to a single call to blamkaGeneric
// with the "row" argument order (t[off]..t[off+15]).
#define BLAMKA_ROUND_0(off) \
LOAD_MSG_0(off); \
HALF_ROUND(V0, V1, V2, V3, V4, V5, V6, V7, V8, V9); \
SHUFFLE; \
HALF_ROUND(V0, V1, V2, V3, V4, V5, V6, V7, V8, V9); \
SHUFFLE_INV; \
STORE_MSG_0(off)
// BLAMKA_ROUND_1(off): one full diagonal pass over the 16 uint64s at
// diagonal offset off -- corresponds to a single call to blamkaGeneric
// with the "diagonal" argument order (t[off], t[off+1], t[16+off], ...).
#define BLAMKA_ROUND_1(off) \
LOAD_MSG_1(off); \
HALF_ROUND(V0, V1, V2, V3, V4, V5, V6, V7, V8, V9); \
SHUFFLE; \
HALF_ROUND(V0, V1, V2, V3, V4, V5, V6, V7, V8, V9); \
SHUFFLE_INV; \
STORE_MSG_1(off)
// func blamkaLOONG64(b *block)
TEXT ·blamkaLOONG64(SB), NOSPLIT, $0-8
MOVV b+0(FP), R4
VXORV V13, V13, V13 // V13 = 0, used by SHUFFLE/SHUFFLE_INV
// Round 0: 8 row passes, stride 128 bytes (16 uint64s).
BLAMKA_ROUND_0(0)
BLAMKA_ROUND_0(128)
BLAMKA_ROUND_0(256)
BLAMKA_ROUND_0(384)
BLAMKA_ROUND_0(512)
BLAMKA_ROUND_0(640)
BLAMKA_ROUND_0(768)
BLAMKA_ROUND_0(896)
// Round 1: 8 diagonal passes, stride 16 bytes (2 uint64s).
BLAMKA_ROUND_1(0)
BLAMKA_ROUND_1(16)
BLAMKA_ROUND_1(32)
BLAMKA_ROUND_1(48)
BLAMKA_ROUND_1(64)
BLAMKA_ROUND_1(80)
BLAMKA_ROUND_1(96)
BLAMKA_ROUND_1(112)
RET
// func mixBlocksVX(out, a, b, c *block)
TEXT ·mixBlocksVX(SB), NOSPLIT, $0-32
MOVV out+0(FP), R4
MOVV a+8(FP), R5
MOVV b+16(FP), R6
MOVV c+24(FP), R7
MOVV $1024, R8
PCALIGN $16
mixloop:
VMOVQ (R5), V0
VMOVQ (R6), V1
VMOVQ (R7), V2
VXORV V0, V1, V0
VXORV V0, V2, V0
VMOVQ V0, (R4)
ADDV $16, R4
ADDV $16, R5
ADDV $16, R6
ADDV $16, R7
SUBV $16, R8
BNE R8, R0, mixloop
RET
// func xorBlocksVX(out, a, b, c *block)
TEXT ·xorBlocksVX(SB), NOSPLIT, $0-32
MOVV out+0(FP), R4
MOVV a+8(FP), R5
MOVV b+16(FP), R6
MOVV c+24(FP), R7
MOVV $1024, R8
PCALIGN $16
xorloop:
VMOVQ (R5), V0
VMOVQ (R6), V1
VMOVQ (R7), V2
VMOVQ (R4), V3
VXORV V0, V1, V0
VXORV V0, V2, V0
VXORV V0, V3, V0
VMOVQ V0, (R4)
ADDV $16, R4
ADDV $16, R5
ADDV $16, R6
ADDV $16, R7
SUBV $16, R8
BNE R8, R0, xorloop
RET
+1 -1
View File
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !amd64 || purego || !gc
//go:build (!amd64 && !loong64) || purego || !gc
package argon2
+1 -1
View File
@@ -50,7 +50,7 @@ func (ih InvalidHashPrefixError) Error() string {
type InvalidCostError int
func (ic InvalidCostError) Error() string {
return fmt.Sprintf("crypto/bcrypt: cost %d is outside allowed range (%d,%d)", int(ic), MinCost, MaxCost)
return fmt.Sprintf("crypto/bcrypt: cost %d is outside allowed inclusive range %d..%d", int(ic), MinCost, MaxCost)
}
const (
+2 -2
View File
@@ -4,13 +4,13 @@ go 1.23
require (
github.com/mmcloughlin/avo v0.6.0
golang.org/x/crypto v0.26.0
golang.org/x/crypto v0.33.0
)
require (
golang.org/x/mod v0.20.0 // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/sys v0.24.0 // indirect
golang.org/x/sys v0.30.0 // indirect
golang.org/x/tools v0.24.0 // indirect
)
+4 -4
View File
@@ -1,12 +1,12 @@
github.com/mmcloughlin/avo v0.6.0 h1:QH6FU8SKoTLaVs80GA8TJuLNkUYl4VokHKlPhVDg4YY=
github.com/mmcloughlin/avo v0.6.0/go.mod h1:8CoAGaCSYXtCPR+8y18Y9aB/kxb8JSS6FRI7mSkvD+8=
golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw=
golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54=
golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus=
golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M=
golang.org/x/mod v0.20.0 h1:utOm6MM3R3dnawAiJgn0y+xvuYRsm1RKM/4giyfDgV0=
golang.org/x/mod v0.20.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/tools v0.24.0 h1:J1shsA93PJUEVaUSaay7UXAyE8aimq3GW0pjlolpa24=
golang.org/x/tools v0.24.0/go.mod h1:YhNqVBIfWHdzvTLs0d8LCuMhkKUgSUKldakyV7W/WDQ=
+2 -2
View File
@@ -4,12 +4,12 @@ go 1.23
require (
github.com/mmcloughlin/avo v0.6.0
golang.org/x/crypto v0.26.0
golang.org/x/crypto v0.33.0
)
require (
golang.org/x/mod v0.20.0 // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/sys v0.24.0 // indirect
golang.org/x/sys v0.30.0 // indirect
golang.org/x/tools v0.24.0 // indirect
)
+4 -4
View File
@@ -1,12 +1,12 @@
github.com/mmcloughlin/avo v0.6.0 h1:QH6FU8SKoTLaVs80GA8TJuLNkUYl4VokHKlPhVDg4YY=
github.com/mmcloughlin/avo v0.6.0/go.mod h1:8CoAGaCSYXtCPR+8y18Y9aB/kxb8JSS6FRI7mSkvD+8=
golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw=
golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54=
golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus=
golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M=
golang.org/x/mod v0.20.0 h1:utOm6MM3R3dnawAiJgn0y+xvuYRsm1RKM/4giyfDgV0=
golang.org/x/mod v0.20.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/tools v0.24.0 h1:J1shsA93PJUEVaUSaay7UXAyE8aimq3GW0pjlolpa24=
golang.org/x/tools v0.24.0/go.mod h1:YhNqVBIfWHdzvTLs0d8LCuMhkKUgSUKldakyV7W/WDQ=
+20
View File
@@ -0,0 +1,20 @@
// 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.
//go:build loong64 && gc && !purego
package blake2b
import "golang.org/x/sys/cpu"
//go:noescape
func hashBlocksVX(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte)
func hashBlocks(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) {
if cpu.Loong64.HasLSX {
hashBlocksVX(h, c, flag, blocks)
} else {
hashBlocksGeneric(h, c, flag, blocks)
}
}
+252
View File
@@ -0,0 +1,252 @@
// 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.
//go:build loong64 && gc && !purego
#include "textflag.h"
DATA ·iv0<>+0(SB)/8, $0x6a09e667f3bcc908
DATA ·iv0<>+8(SB)/8, $0xbb67ae8584caa73b
GLOBL ·iv0<>(SB), RODATA|NOPTR, $16
DATA ·iv1<>+0(SB)/8, $0x3c6ef372fe94f82b
DATA ·iv1<>+8(SB)/8, $0xa54ff53a5f1d36f1
GLOBL ·iv1<>(SB), RODATA|NOPTR, $16
DATA ·iv2<>+0(SB)/8, $0x510e527fade682d1
DATA ·iv2<>+8(SB)/8, $0x9b05688c2b3e6c1f
GLOBL ·iv2<>(SB), RODATA|NOPTR, $16
DATA ·iv3<>+0(SB)/8, $0x1f83d9abfb41bd6b
DATA ·iv3<>+8(SB)/8, $0x5be0cd19137e2179
GLOBL ·iv3<>(SB), RODATA|NOPTR, $16
#define SHUFFLE_1 \
VADDV V2, V13, V12; \ // V12 = V2
VADDV V6, V13, V16; \ // V16 = V6
VADDV V4, V13, V14; \ // V14 = V4
VADDV V5, V13, V4; \ // V4 = V5
VADDV V14, V13, V5; \ // V5 = V4
VSHUF4IV $9, V3, V2; \
VSHUF4IV $9, V12, V3; \
VSHUF4IV $3, V7, V6; \
VSHUF4IV $3, V16, V7; \
#define SHUFFLE_2 \
VADDV V2, V13, V12; \ // V12 = V2
VADDV V6, V13, V16; \ // V16 = V6
VADDV V4, V13, V14; \ // V14 = V4
VADDV V5, V13, V4; \ // V4 = V5
VADDV V14, V13, V5; \ // V5 = V4
VSHUF4IV $3, V3, V2; \
VSHUF4IV $3, V12, V3; \
VSHUF4IV $9, V7, V6; \
VSHUF4IV $9, V16, V7; \
#define LOAD_M(a, b, c, d, e, f, g, h) \
VMOVQ a, V8.V[0]; \
VMOVQ b, V8.V[1]; \
VMOVQ c, V9.V[0]; \
VMOVQ d, V9.V[1]; \
VMOVQ e, V10.V[0]; \
VMOVQ f, V10.V[1]; \
VMOVQ g, V11.V[0]; \
VMOVQ h, V11.V[1]; \
#define ROUND_0 \
VADDV V0, V8, V0; \
VADDV V1, V9, V1; \
VADDV V0, V2, V0; \
VADDV V1, V3, V1; \
VXORV V6, V0, V6; \
VXORV V7, V1, V7; \
VROTRV $32, V6, V6; \
VROTRV $32, V7, V7; \
VADDV V4, V6, V4; \
VADDV V5, V7, V5; \
VXORV V2, V4, V2; \
VXORV V3, V5, V3; \
VROTRV $24, V2, V2; \
VROTRV $24, V3, V3; \
VADDV V0, V10, V0; \
VADDV V1, V11, V1; \
VADDV V0, V2, V0; \
VADDV V1, V3, V1; \
VXORV V6, V0, V6; \
VXORV V7, V1, V7; \
VROTRV $16, V6, V6; \
VROTRV $16, V7, V7; \
VADDV V4, V6, V4; \
VADDV V5, V7, V5; \
VXORV V2, V4, V2; \
VXORV V3, V5, V3; \
VROTRV $63, V2, V2; \
VROTRV $63, V3, V3; \
#define ROUND_8 ROUND_0
// func hashBlocksVX(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte)
TEXT ·hashBlocksVX(SB), NOSPLIT, $0-48
MOVV h+0(FP), R4
MOVV c+8(FP), R5
MOVV flag+16(FP), R6
MOVV blocks_base+24(FP), R7
MOVV blocks_len+32(FP), R8
MOVV (R5), R9 // c0
MOVV 8(R5), R10 // c1
loop:
ADDV $0x80, R9
SGTU $0x80, R9, R11
ADDV R10, R11, R10
VMOVQ R9, V8.V[0]
VMOVQ R10, V8.V[1]
MOVV $·iv0<>(SB), R11
MOVV $·iv1<>(SB), R12
MOVV $·iv2<>(SB), R13
MOVV $·iv3<>(SB), R14
VMOVQ (R13), V6
VMOVQ (R11), V4
VMOVQ (R12), V5
MOVV (R14), R15 // v14
MOVV 8(R14), R16
VXORV V6, V8, V6
XOR R15, R6, R15
VMOVQ R16, V7.V[1]
VMOVQ R15, V7.V[0]
VMOVQ (R4), V0
VMOVQ 16(R4), V1
VMOVQ 32(R4), V2
VMOVQ 48(R4), V3
MOVV 0(R7), R11
MOVV 8(R7), R12
MOVV 16(R7), R13
MOVV 24(R7), R14
MOVV 32(R7), R15
MOVV 40(R7), R16
MOVV 48(R7), R17
MOVV 56(R7), R18
MOVV 64(R7), R19
MOVV 72(R7), R24
MOVV 80(R7), R25
MOVV 88(R7), R26
MOVV 96(R7), R27
MOVV 104(R7), R28
MOVV 112(R7), R29
MOVV 120(R7), R30
VXORV V13, V13, V13 // V13=0
LOAD_M(R11, R13, R15, R17, R12, R14, R16, R18)
ROUND_0
SHUFFLE_1
LOAD_M(R19, R25, R27, R29, R24, R26, R28, R30)
ROUND_8
SHUFFLE_2
LOAD_M(R29, R15, R24, R28, R25, R19, R30, R17)
ROUND_0
SHUFFLE_1
LOAD_M(R12, R11, R26, R16, R27, R13, R18, R14)
ROUND_8
SHUFFLE_2
LOAD_M(R26, R27, R16, R30, R19, R11, R13, R28)
ROUND_0
SHUFFLE_1
LOAD_M(R25, R14, R18, R24, R29, R17, R12, R15)
ROUND_8
SHUFFLE_2
LOAD_M(R18, R14, R28, R26, R24, R12, R27, R29)
ROUND_0
SHUFFLE_1
LOAD_M(R13, R16, R15, R30, R17, R25, R11, R19)
ROUND_8
SHUFFLE_2
LOAD_M(R24, R16, R13, R25, R11, R18, R15, R30)
ROUND_0
SHUFFLE_1
LOAD_M(R29, R26, R17, R14, R12, R27, R19, R28)
ROUND_8
SHUFFLE_2
LOAD_M(R13, R17, R11, R19, R27, R25, R26, R14)
ROUND_0
SHUFFLE_1
LOAD_M(R15, R18, R30, R12, R28, R16, R29, R24)
ROUND_8
SHUFFLE_2
LOAD_M(R27, R12, R29, R15, R16, R30, R28, R25)
ROUND_0
SHUFFLE_1
LOAD_M(R11, R17, R24, R19, R18, R14, R13, R26)
ROUND_8
SHUFFLE_2
LOAD_M(R28, R18, R27, R14, R26, R29, R12, R24)
ROUND_0
SHUFFLE_1
LOAD_M(R16, R30, R19, R13, R11, R15, R17, R25)
ROUND_8
SHUFFLE_2
LOAD_M(R17, R29, R26, R11, R30, R24, R14, R19)
ROUND_0
SHUFFLE_1
LOAD_M(R27, R28, R12, R25, R13, R18, R15, R16)
ROUND_8
SHUFFLE_2
LOAD_M(R25, R19, R18, R12, R13, R15, R17, R16)
ROUND_0
SHUFFLE_1
LOAD_M(R30, R24, R14, R28, R26, R29, R27, R11)
ROUND_8
SHUFFLE_2
LOAD_M(R11, R13, R15, R17, R12, R14, R16, R18)
ROUND_0
SHUFFLE_1
LOAD_M(R19, R25, R27, R29, R24, R26, R28, R30)
ROUND_8
SHUFFLE_2
LOAD_M(R29, R15, R24, R28, R25, R19, R30, R17)
ROUND_0
SHUFFLE_1
LOAD_M(R12, R11, R26, R16, R27, R13, R18, R14)
ROUND_8
SHUFFLE_2
VMOVQ (R4), V8
VMOVQ 16(R4), V9
VMOVQ 32(R4), V10
VMOVQ 48(R4), V11
VXORV V0, V4, V0
VXORV V1, V5, V1
VXORV V2, V6, V2
VXORV V3, V7, V3
VXORV V0, V8, V0
VXORV V1, V9, V1
VXORV V2, V10, V2
VXORV V3, V11, V3
VMOVQ V0, (R4)
VMOVQ V1, 16(R4)
VMOVQ V2, 32(R4)
VMOVQ V3, 48(R4)
SUBV $128, R8
ADDV $128, R7
BNE R8, R0, loop
MOVV R9, (R5)
MOVV R10, 8(R5)
RET
+1 -1
View File
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !amd64 || purego || !gc
//go:build (!amd64 && !loong64) || purego || !gc
package blake2b
+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 {
+8
View File
@@ -12,6 +12,8 @@ import (
// XOF defines the interface to hash functions that
// support arbitrary-length output.
//
// New callers should prefer the standard library [hash.XOF].
type XOF interface {
// Write absorbs more data into the hash's state. It panics if called
// after Read.
@@ -47,6 +49,8 @@ const maxOutputLength = (1 << 32) * 64
//
// A non-nil key turns the hash into a MAC. The key must between
// zero and 32 bytes long.
//
// The result can be safely interface-upgraded to [hash.XOF].
func NewXOF(size uint32, key []byte) (XOF, error) {
if len(key) > Size {
return nil, errKeySize
@@ -93,6 +97,10 @@ func (x *xof) Clone() XOF {
return &clone
}
func (x *xof) BlockSize() int {
return x.d.BlockSize()
}
func (x *xof) Reset() {
x.cfg[0] = byte(Size)
binary.LittleEndian.PutUint32(x.cfg[4:], uint32(Size)) // leaf length
+2 -2
View File
@@ -4,12 +4,12 @@ go 1.23
require (
github.com/mmcloughlin/avo v0.6.0
golang.org/x/crypto v0.26.0
golang.org/x/crypto v0.33.0
)
require (
golang.org/x/mod v0.20.0 // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/sys v0.24.0 // indirect
golang.org/x/sys v0.30.0 // indirect
golang.org/x/tools v0.24.0 // indirect
)
+4 -4
View File
@@ -1,12 +1,12 @@
github.com/mmcloughlin/avo v0.6.0 h1:QH6FU8SKoTLaVs80GA8TJuLNkUYl4VokHKlPhVDg4YY=
github.com/mmcloughlin/avo v0.6.0/go.mod h1:8CoAGaCSYXtCPR+8y18Y9aB/kxb8JSS6FRI7mSkvD+8=
golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw=
golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54=
golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus=
golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M=
golang.org/x/mod v0.20.0 h1:utOm6MM3R3dnawAiJgn0y+xvuYRsm1RKM/4giyfDgV0=
golang.org/x/mod v0.20.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/tools v0.24.0 h1:J1shsA93PJUEVaUSaay7UXAyE8aimq3GW0pjlolpa24=
golang.org/x/tools v0.24.0/go.mod h1:YhNqVBIfWHdzvTLs0d8LCuMhkKUgSUKldakyV7W/WDQ=
+1 -1
View File
@@ -29,7 +29,7 @@ loop:
MOVD $NUM_ROUNDS, R21
VLD1 (R11), [V30.S4, V31.S4]
// load contants
// load constants
// VLD4R (R10), [V0.S4, V1.S4, V2.S4, V3.S4]
WORD $0x4D60E940
+22
View File
@@ -0,0 +1,22 @@
// 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.
//go:build gc && !purego
package chacha20
import "golang.org/x/sys/cpu"
const bufSize = 256
//go:noescape
func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32)
func (c *Cipher) xorKeyStreamBlocks(dst, src []byte) {
if cpu.Loong64.HasLSX {
xorKeyStreamVX(dst, src, &c.key, &c.nonce, &c.counter)
} else {
c.xorKeyStreamBlocksGeneric(dst, src)
}
}
+342
View File
@@ -0,0 +1,342 @@
// 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.
// derived from chacha_arm64.s
//go:build gc && !purego
#include "textflag.h"
DATA ·constants+0x00(SB)/4, $0x61707865
DATA ·constants+0x04(SB)/4, $0x3320646e
DATA ·constants+0x08(SB)/4, $0x79622d32
DATA ·constants+0x0c(SB)/4, $0x6b206574
GLOBL ·constants(SB), NOPTR|RODATA, $32
DATA ·incRotMatrix+0x00(SB)/4, $0x00000000
DATA ·incRotMatrix+0x04(SB)/4, $0x00000001
DATA ·incRotMatrix+0x08(SB)/4, $0x00000002
DATA ·incRotMatrix+0x0c(SB)/4, $0x00000003
GLOBL ·incRotMatrix(SB), NOPTR|RODATA, $32
#define NUM_ROUNDS 10
// func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32)
TEXT ·xorKeyStreamVX(SB), NOSPLIT, $0
MOVV dst+0(FP), R4
MOVV src+24(FP), R5
MOVV src_len+32(FP), R6
MOVV key+48(FP), R7
MOVV nonce+56(FP), R8
MOVV counter+64(FP), R9
MOVV $·constants(SB), R10
MOVV $·incRotMatrix(SB), R11
MOVW (R9), R12
loop:
MOVV $NUM_ROUNDS, R15
// load 4-32bit data from incRotMatrix added to counter
VMOVQ (R11), V30
// load contants
VMOVQ (R10), V0.W4
VMOVQ 4(R10), V1.W4
VMOVQ 8(R10), V2.W4
VMOVQ 12(R10), V3.W4
// load keys
VMOVQ (R7), V4.W4
VMOVQ 4(R7), V5.W4
VMOVQ 8(R7), V6.W4
VMOVQ 12(R7), V7.W4
VMOVQ 16(R7), V8.W4
VMOVQ 20(R7), V9.W4
VMOVQ 24(R7), V10.W4
VMOVQ 28(R7), V11.W4
// load counter + nonce
VMOVQ (R9), V12.W4
VMOVQ (R8), V13.W4
VMOVQ 4(R8), V14.W4
VMOVQ 8(R8), V15.W4
// update counter
VADDW V30, V12, V12
chacha:
// V0..V3 += V4..V7
// V12..V15 <<<= ((V12..V15 XOR V0..V3), 16)
VADDW V0, V4, V0
VADDW V1, V5, V1
VADDW V2, V6, V2
VADDW V3, V7, V3
VXORV V12, V0, V12
VXORV V13, V1, V13
VXORV V14, V2, V14
VXORV V15, V3, V15
VROTRW $16, V12, V12
VROTRW $16, V13, V13
VROTRW $16, V14, V14
VROTRW $16, V15, V15
// V8..V11 += V12..V15
// V4..V7 <<<= ((V4..V7 XOR V8..V11), 12)
VADDW V8, V12, V8
VADDW V9, V13, V9
VADDW V10, V14, V10
VADDW V11, V15, V11
VXORV V4, V8, V4
VXORV V5, V9, V5
VXORV V6, V10, V6
VXORV V7, V11, V7
VROTRW $20, V4, V4
VROTRW $20, V5, V5
VROTRW $20, V6, V6
VROTRW $20, V7, V7
// V0..V3 += V4..V7
// V12..V15 <<<= ((V12..V15 XOR V0..V3), 8)
VADDW V0, V4, V0
VADDW V1, V5, V1
VADDW V2, V6, V2
VADDW V3, V7, V3
VXORV V12, V0, V12
VXORV V13, V1, V13
VXORV V14, V2, V14
VXORV V15, V3, V15
VROTRW $24, V12, V12
VROTRW $24, V13, V13
VROTRW $24, V14, V14
VROTRW $24, V15, V15
// V8..V11 += V12..V15
// V4..V7 <<<= ((V4..V7 XOR V8..V11), 7)
VADDW V12, V8, V8
VADDW V13, V9, V9
VADDW V14, V10, V10
VADDW V15, V11, V11
VXORV V4, V8, V4
VXORV V5, V9, V5
VXORV V6, V10, V6
VXORV V7, V11, V7
VROTRW $25, V4, V4
VROTRW $25, V5, V5
VROTRW $25, V6, V6
VROTRW $25, V7, V7
// V0..V3 += V5..V7, V4
// V15,V12-V14 <<<= ((V15,V12-V14 XOR V0..V3), 16)
VADDW V0, V5, V0
VADDW V1, V6, V1
VADDW V2, V7, V2
VADDW V3, V4, V3
VXORV V15, V0, V15
VXORV V12, V1, V12
VXORV V13, V2, V13
VXORV V14, V3, V14
VROTRW $16, V15, V15
VROTRW $16, V12, V12
VROTRW $16, V13, V13
VROTRW $16, V14, V14
// V10,V11,V8,V9 += V15,V12,V13,V14
// V5,V6,V7,V4 <<<= ((V5,V6,V7,V4 XOR V10,V11,V8,V9), 12)
VADDW V10, V15, V10
VADDW V11, V12, V11
VADDW V8, V13, V8
VADDW V9, V14, V9
VXORV V5, V10, V5
VXORV V6, V11, V6
VXORV V7, V8, V7
VXORV V4, V9, V4
VROTRW $20, V5, V5
VROTRW $20, V6, V6
VROTRW $20, V7, V7
VROTRW $20, V4, V4
// V0..V3 += V5..V7, V4
// V15,V12-V14 <<<= ((V15,V12-V14 XOR V0..V3), 8)
VADDW V5, V0, V0
VADDW V6, V1, V1
VADDW V7, V2, V2
VADDW V4, V3, V3
VXORV V15, V0, V15
VXORV V12, V1, V12
VXORV V13, V2, V13
VXORV V14, V3, V14
VROTRW $24, V15, V15
VROTRW $24, V12, V12
VROTRW $24, V13, V13
VROTRW $24, V14, V14
// V10,V11,V8,V9 += V15,V12,V13,V14
// V5,V6,V7,V4 <<<= ((V5,V6,V7,V4 XOR V10,V11,V8,V9), 7)
VADDW V15, V10, V10
VADDW V12, V11, V11
VADDW V13, V8, V8
VADDW V14, V9, V9
VXORV V5, V10, V5
VXORV V6, V11, V6
VXORV V7, V8, V7
VXORV V4, V9, V4
VROTRW $25, V5, V5
VROTRW $25, V6, V6
VROTRW $25, V7, V7
VROTRW $25, V4, V4
SUBV $1, R15
BNE R15, R0, chacha
// load origin contants
VMOVQ (R10), V16.W4
VMOVQ 4(R10), V17.W4
VMOVQ 8(R10), V18.W4
VMOVQ 12(R10), V19.W4
// load origin keys
VMOVQ (R7), V20.W4
VMOVQ 4(R7), V21.W4
VMOVQ 8(R7), V22.W4
VMOVQ 12(R7), V23.W4
VMOVQ 16(R7), V24.W4
VMOVQ 20(R7), V25.W4
VMOVQ 24(R7), V26.W4
VMOVQ 28(R7), V27.W4
// add back the initial state to generate the key stream
VADDW V30, V12, V12 // update counter in advance to prevent V30 from being overwritten
VADDW V16, V0, V0
VADDW V17, V1, V1
VADDW V18, V2, V2
VADDW V19, V3, V3
// load origin counter + nonce
VMOVQ (R9), V28.W4
VMOVQ (R8), V29.W4
VMOVQ 4(R8), V30.W4
VMOVQ 8(R8), V31.W4
VADDW V20, V4, V4
VADDW V21, V5, V5
VADDW V22, V6, V6
VADDW V23, V7, V7
VADDW V24, V8, V8
VADDW V25, V9, V9
VADDW V26, V10, V10
VADDW V27, V11, V11
VADDW V28, V12, V12
VADDW V29, V13, V13
VADDW V30, V14, V14
VADDW V31, V15, V15
// shuffle
VILVLW V0, V1, V16
VILVHW V0, V1, V17
VILVLW V2, V3, V18
VILVHW V2, V3, V19
VILVLW V4, V5 ,V20
VILVHW V4, V5, V21
VILVLW V6, V7, V22
VILVHW V6, V7, V23
VILVLW V8, V9, V24
VILVHW V8, V9, V25
VILVLW V10, V11, V26
VILVHW V10, V11, V27
VILVLW V12, V13, V28
VILVHW V12, V13, V29
VILVLW V14, V15, V30
VILVHW V14, V15, V31
VILVLV V16, V18, V0
VILVHV V16, V18, V4
VILVLV V17, V19, V8
VILVHV V17, V19, V12
// load src data from R5
VMOVQ 0(R5), V16
VMOVQ 16(R5), V17
VMOVQ 32(R5), V18
VMOVQ 48(R5), V19
VILVLV V20, V22, V1
VILVHV V20, V22, V5
VILVLV V21, V23, V9
VILVHV V21, V23, V13
VMOVQ 64(R5), V20
VMOVQ 80(R5), V21
VMOVQ 96(R5), V22
VMOVQ 112(R5), V23
VILVLV V24, V26, V2
VILVHV V24, V26, V6
VILVLV V25, V27, V10
VILVHV V25, V27, V14
VMOVQ 128(R5), V24
VMOVQ 144(R5), V25
VMOVQ 160(R5), V26
VMOVQ 176(R5), V27
VILVLV V28, V30, V3
VILVHV V28, V30, V7
VILVLV V29, V31, V11
VILVHV V29, V31, V15
VMOVQ 192(R5), V28
VMOVQ 208(R5), V29
VMOVQ 224(R5), V30
VMOVQ 240(R5), V31
VXORV V0, V16, V16
VXORV V1, V17, V17
VXORV V2, V18, V18
VXORV V3, V19, V19
VMOVQ V16, 0(R4)
VMOVQ V17, 16(R4)
VMOVQ V18, 32(R4)
VMOVQ V19, 48(R4)
VXORV V4, V20, V20
VXORV V5, V21, V21
VXORV V6, V22, V22
VXORV V7, V23, V23
VMOVQ V20, 64(R4)
VMOVQ V21, 80(R4)
VMOVQ V22, 96(R4)
VMOVQ V23, 112(R4)
VXORV V8, V24, V24
VXORV V9, V25, V25
VXORV V10, V26, V26
VXORV V11, V27, V27
VMOVQ V24, 128(R4)
VMOVQ V25, 144(R4)
VMOVQ V26, 160(R4)
VMOVQ V27, 176(R4)
VXORV V12, V28, V28
VXORV V13, V29, V29
VXORV V14, V30, V30
VXORV V15, V31, V31
VMOVQ V28, 192(R4)
VMOVQ V29, 208(R4)
VMOVQ V30, 224(R4)
VMOVQ V31, 240(R4)
ADD $4, R12, R12
MOVW R12, (R9) // update counter
ADDV $256, R4, R4
ADDV $256, R5, R5
SUBV $256, R6, R6
BNE R6, R0, loop
RET
+1 -1
View File
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build (!arm64 && !s390x && !ppc64 && !ppc64le) || !gc || purego
//go:build (!arm64 && !loong64 && !s390x && !ppc64 && !ppc64le) || !gc || purego
package chacha20
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -4,12 +4,12 @@ go 1.23
require (
github.com/mmcloughlin/avo v0.6.0
golang.org/x/crypto v0.26.0
golang.org/x/crypto v0.33.0
)
require (
golang.org/x/mod v0.20.0 // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/sys v0.24.0 // indirect
golang.org/x/sys v0.30.0 // indirect
golang.org/x/tools v0.24.0 // indirect
)
+4 -4
View File
@@ -1,12 +1,12 @@
github.com/mmcloughlin/avo v0.6.0 h1:QH6FU8SKoTLaVs80GA8TJuLNkUYl4VokHKlPhVDg4YY=
github.com/mmcloughlin/avo v0.6.0/go.mod h1:8CoAGaCSYXtCPR+8y18Y9aB/kxb8JSS6FRI7mSkvD+8=
golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw=
golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54=
golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus=
golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M=
golang.org/x/mod v0.20.0 h1:utOm6MM3R3dnawAiJgn0y+xvuYRsm1RKM/4giyfDgV0=
golang.org/x/mod v0.20.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/tools v0.24.0 h1:J1shsA93PJUEVaUSaay7UXAyE8aimq3GW0pjlolpa24=
golang.org/x/tools v0.24.0/go.mod h1:YhNqVBIfWHdzvTLs0d8LCuMhkKUgSUKldakyV7W/WDQ=
+3
View File
@@ -38,6 +38,9 @@ type chacha20poly1305 struct {
// New returns a ChaCha20-Poly1305 AEAD that uses the given 256-bit key.
func New(key []byte) (cipher.AEAD, error) {
if fips140Enforced() {
return nil, errors.New("chacha20poly1305: use of ChaCha20Poly1305 is not allowed in FIPS 140-only mode")
}
if len(key) != KeySize {
return nil, errors.New("chacha20poly1305: bad key length")
}
+11 -5
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)
}
@@ -56,14 +56,17 @@ func (c *chacha20poly1305) seal(dst, nonce, plaintext, additionalData []byte) []
ret, out := sliceForAppend(dst, len(plaintext)+16)
if alias.InexactOverlap(out, plaintext) {
panic("chacha20poly1305: invalid buffer overlap")
panic("chacha20poly1305: invalid buffer overlap of output and input")
}
if alias.AnyOverlap(out, additionalData) {
panic("chacha20poly1305: invalid buffer overlap of output and additional data")
}
chacha20Poly1305Seal(out[:], state[:], plaintext, additionalData)
return ret
}
func (c *chacha20poly1305) open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
if !cpu.X86.HasSSSE3 {
if !useAVX2 {
return c.openGeneric(dst, nonce, ciphertext, additionalData)
}
@@ -73,7 +76,10 @@ func (c *chacha20poly1305) open(dst, nonce, ciphertext, additionalData []byte) (
ciphertext = ciphertext[:len(ciphertext)-16]
ret, out := sliceForAppend(dst, len(ciphertext))
if alias.InexactOverlap(out, ciphertext) {
panic("chacha20poly1305: invalid buffer overlap")
panic("chacha20poly1305: invalid buffer overlap of output and input")
}
if alias.AnyOverlap(out, additionalData) {
panic("chacha20poly1305: invalid buffer overlap of output and additional data")
}
if !chacha20Poly1305Open(out, state[:], ciphertext, additionalData) {
for i := range out {
File diff suppressed because it is too large Load Diff
+8 -2
View File
@@ -31,7 +31,10 @@ func (c *chacha20poly1305) sealGeneric(dst, nonce, plaintext, additionalData []b
ret, out := sliceForAppend(dst, len(plaintext)+poly1305.TagSize)
ciphertext, tag := out[:len(plaintext)], out[len(plaintext):]
if alias.InexactOverlap(out, plaintext) {
panic("chacha20poly1305: invalid buffer overlap")
panic("chacha20poly1305: invalid buffer overlap of output and input")
}
if alias.AnyOverlap(out, additionalData) {
panic("chacha20poly1305: invalid buffer overlap of output and additional data")
}
var polyKey [32]byte
@@ -67,7 +70,10 @@ func (c *chacha20poly1305) openGeneric(dst, nonce, ciphertext, additionalData []
ret, out := sliceForAppend(dst, len(ciphertext))
if alias.InexactOverlap(out, ciphertext) {
panic("chacha20poly1305: invalid buffer overlap")
panic("chacha20poly1305: invalid buffer overlap of output and input")
}
if alias.AnyOverlap(out, additionalData) {
panic("chacha20poly1305: invalid buffer overlap of output and additional data")
}
if !p.Verify(tag) {
for i := range out {
+6 -6
View File
@@ -153,7 +153,7 @@ func TestRandom(t *testing.T) {
t.Run("X", func(t *testing.T) { f(t, NonceSizeX) })
}
func benchamarkChaCha20Poly1305Seal(b *testing.B, buf []byte, nonceSize int) {
func benchmarkChaCha20Poly1305Seal(b *testing.B, buf []byte, nonceSize int) {
b.ReportAllocs()
b.SetBytes(int64(len(buf)))
@@ -176,7 +176,7 @@ func benchamarkChaCha20Poly1305Seal(b *testing.B, buf []byte, nonceSize int) {
}
}
func benchamarkChaCha20Poly1305Open(b *testing.B, buf []byte, nonceSize int) {
func benchmarkChaCha20Poly1305Open(b *testing.B, buf []byte, nonceSize int) {
b.ReportAllocs()
b.SetBytes(int64(len(buf)))
@@ -204,17 +204,17 @@ func benchamarkChaCha20Poly1305Open(b *testing.B, buf []byte, nonceSize int) {
func BenchmarkChacha20Poly1305(b *testing.B) {
for _, length := range []int{64, 1350, 8 * 1024} {
b.Run("Open-"+strconv.Itoa(length), func(b *testing.B) {
benchamarkChaCha20Poly1305Open(b, make([]byte, length), NonceSize)
benchmarkChaCha20Poly1305Open(b, make([]byte, length), NonceSize)
})
b.Run("Seal-"+strconv.Itoa(length), func(b *testing.B) {
benchamarkChaCha20Poly1305Seal(b, make([]byte, length), NonceSize)
benchmarkChaCha20Poly1305Seal(b, make([]byte, length), NonceSize)
})
b.Run("Open-"+strconv.Itoa(length)+"-X", func(b *testing.B) {
benchamarkChaCha20Poly1305Open(b, make([]byte, length), NonceSizeX)
benchmarkChaCha20Poly1305Open(b, make([]byte, length), NonceSizeX)
})
b.Run("Seal-"+strconv.Itoa(length)+"-X", func(b *testing.B) {
benchamarkChaCha20Poly1305Seal(b, make([]byte, length), NonceSizeX)
benchmarkChaCha20Poly1305Seal(b, make([]byte, length), NonceSizeX)
})
}
}
+9
View File
@@ -0,0 +1,9 @@
// 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.26
package chacha20poly1305
func fips140Enforced() bool { return false }
+11
View File
@@ -0,0 +1,11 @@
// 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.26
package chacha20poly1305
import "crypto/fips140"
func fips140Enforced() bool { return fips140.Enforced() }
+3
View File
@@ -22,6 +22,9 @@ type xchacha20poly1305 struct {
// preferred when nonce uniqueness cannot be trivially ensured, or whenever
// nonces are randomly generated.
func NewX(key []byte) (cipher.AEAD, error) {
if fips140Enforced() {
return nil, errors.New("chacha20poly1305: use of ChaCha20Poly1305 is not allowed in FIPS 140-only mode")
}
if len(key) != KeySize {
return nil, errors.New("chacha20poly1305: bad key length")
}
+1 -1
View File
@@ -234,7 +234,7 @@ func (b *Builder) AddASN1(tag asn1.Tag, f BuilderContinuation) {
// Identifiers with the low five bits set indicate high-tag-number format
// (two or more octets), which we don't support.
if tag&0x1f == 0x1f {
b.err = fmt.Errorf("cryptobyte: high-tag number identifier octects not supported: 0x%x", tag)
b.err = fmt.Errorf("cryptobyte: high-tag number identifier octets not supported: 0x%x", tag)
return
}
b.AddUint8(uint8(tag))
+8 -5
View File
@@ -3,11 +3,14 @@
// license that can be found in the LICENSE file.
// Package curve25519 provides an implementation of the X25519 function, which
// performs scalar multiplication on the elliptic curve known as Curve25519.
// See RFC 7748.
// performs scalar multiplication on the elliptic curve known as Curve25519
// according to [RFC 7748].
//
// This package is a wrapper for the X25519 implementation
// in the crypto/ecdh package.
// The curve25519 package is a wrapper for the X25519 implementation in the
// crypto/ecdh package. It is [frozen] and is not accepting new features.
//
// [RFC 7748]: https://datatracker.ietf.org/doc/html/rfc7748
// [frozen]: https://go.dev/wiki/Frozen
package curve25519
import "crypto/ecdh"
@@ -36,7 +39,7 @@ func ScalarBaseMult(dst, scalar *[32]byte) {
curve := ecdh.X25519()
priv, err := curve.NewPrivateKey(scalar[:])
if err != nil {
panic("curve25519: internal error: scalarBaseMult was not 32 bytes")
panic("curve25519: " + err.Error())
}
copy(dst[:], priv.PublicKey().Bytes())
}
+7 -4
View File
@@ -2,16 +2,19 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package ed25519 implements the Ed25519 signature algorithm. See
// https://ed25519.cr.yp.to/.
// Package ed25519 implements the Ed25519 signature algorithm.
//
// These functions are also compatible with the “Ed25519” function defined in
// RFC 8032. However, unlike RFC 8032's formulation, this package's private key
// [RFC 8032]. However, unlike RFC 8032's formulation, this package's private key
// representation includes a public key suffix to make multiple signing
// operations with the same key more efficient. This package refers to the RFC
// 8032 private key as the “seed”.
//
// This package is a wrapper around the standard library crypto/ed25519 package.
// The ed25519 package is a wrapper for the Ed25519 implementation in the
// crypto/ed25519 package. It is [frozen] and is not accepting new features.
//
// [RFC 8032]: https://datatracker.ietf.org/doc/html/rfc8032
// [frozen]: https://go.dev/wiki/Frozen
package ed25519
import (
+5 -5
View File
@@ -1,11 +1,11 @@
module golang.org/x/crypto
go 1.20
go 1.26.0
require (
golang.org/x/net v0.21.0 // tagx:ignore
golang.org/x/sys v0.29.0
golang.org/x/term v0.28.0
golang.org/x/net v0.58.0 // tagx:ignore
golang.org/x/sys v0.48.0
golang.org/x/term v0.46.0
)
require golang.org/x/text v0.21.0 // indirect
require golang.org/x/text v0.42.0 // indirect
+8 -8
View File
@@ -1,8 +1,8 @@
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.28.0 h1:/Ts8HFuMR2E6IP/jlo7QVLZHggjKQbhu/7H0LJFr3Gg=
golang.org/x/term v0.28.0/go.mod h1:Sw/lC2IAUZ92udQNf3WodGtn4k/XoLyZoh8v/8uiwek=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
+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,
+2 -2
View File
@@ -4,12 +4,12 @@ go 1.23
require (
github.com/mmcloughlin/avo v0.6.0
golang.org/x/crypto v0.26.0
golang.org/x/crypto v0.33.0
)
require (
golang.org/x/mod v0.20.0 // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/sys v0.24.0 // indirect
golang.org/x/sys v0.30.0 // indirect
golang.org/x/tools v0.24.0 // indirect
)
+4 -4
View File
@@ -1,12 +1,12 @@
github.com/mmcloughlin/avo v0.6.0 h1:QH6FU8SKoTLaVs80GA8TJuLNkUYl4VokHKlPhVDg4YY=
github.com/mmcloughlin/avo v0.6.0/go.mod h1:8CoAGaCSYXtCPR+8y18Y9aB/kxb8JSS6FRI7mSkvD+8=
golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw=
golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54=
golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus=
golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M=
golang.org/x/mod v0.20.0 h1:utOm6MM3R3dnawAiJgn0y+xvuYRsm1RKM/4giyfDgV0=
golang.org/x/mod v0.20.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/tools v0.24.0 h1:J1shsA93PJUEVaUSaay7UXAyE8aimq3GW0pjlolpa24=
golang.org/x/tools v0.24.0/go.mod h1:YhNqVBIfWHdzvTLs0d8LCuMhkKUgSUKldakyV7W/WDQ=
+1 -1
View File
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build (!amd64 && !ppc64le && !ppc64 && !s390x) || !gc || purego
//go:build (!amd64 && !loong64 && !ppc64le && !ppc64 && !riscv64 && !s390x) || !gc || purego
package poly1305
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build gc && !purego
//go:build gc && !purego && (amd64 || loong64 || ppc64 || ppc64le || riscv64)
package poly1305
+123
View File
@@ -0,0 +1,123 @@
// 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 gc && !purego
// func update(state *macState, msg []byte)
TEXT ·update(SB), $0-32
MOVV state+0(FP), R4
MOVV msg_base+8(FP), R5
MOVV msg_len+16(FP), R6
MOVV $0x10, R7
MOVV (R4), R8 // h0
MOVV 8(R4), R9 // h1
MOVV 16(R4), R10 // h2
MOVV 24(R4), R11 // r0
MOVV 32(R4), R12 // r1
BLT R6, R7, bytes_between_0_and_15
loop:
MOVV (R5), R14 // msg[0:8]
MOVV 8(R5), R16 // msg[8:16]
ADDV R14, R8, R8 // h0 (x1 + y1 = z1', if z1' < x1 then z1' overflow)
ADDV R16, R9, R27
SGTU R14, R8, R24 // h0.carry
SGTU R9, R27, R28
ADDV R27, R24, R9 // h1
SGTU R27, R9, R24
OR R24, R28, R24 // h1.carry
ADDV $0x01, R24, R24
ADDV R10, R24, R10 // h2
ADDV $16, R5, R5 // msg = msg[16:]
multiply:
MULV R8, R11, R14 // h0r0.lo
MULHVU R8, R11, R15 // h0r0.hi
MULV R9, R11, R13 // h1r0.lo
MULHVU R9, R11, R16 // h1r0.hi
ADDV R13, R15, R15
SGTU R13, R15, R24
ADDV R24, R16, R16
MULV R10, R11, R25
ADDV R16, R25, R25
MULV R8, R12, R13 // h0r1.lo
MULHVU R8, R12, R16 // h0r1.hi
ADDV R13, R15, R15
SGTU R13, R15, R24
ADDV R24, R16, R16
MOVV R16, R8
MULV R10, R12, R26 // h2r1
MULV R9, R12, R13 // h1r1.lo
MULHVU R9, R12, R16 // h1r1.hi
ADDV R13, R25, R25
ADDV R16, R26, R27
SGTU R13, R25, R24
ADDV R27, R24, R26
ADDV R8, R25, R25
SGTU R8, R25, R24
ADDV R24, R26, R26
AND $3, R25, R10
AND $-4, R25, R17
ADDV R17, R14, R8
ADDV R26, R15, R27
SGTU R17, R8, R24
SGTU R26, R27, R28
ADDV R27, R24, R9
SGTU R27, R9, R24
OR R24, R28, R24
ADDV R24, R10, R10
SLLV $62, R26, R27
SRLV $2, R25, R28
SRLV $2, R26, R26
OR R27, R28, R25
ADDV R25, R8, R8
ADDV R26, R9, R27
SGTU R25, R8, R24
SGTU R26, R27, R28
ADDV R27, R24, R9
SGTU R27, R9, R24
OR R24, R28, R24
ADDV R24, R10, R10
SUBV $16, R6, R6
BGE R6, R7, loop
bytes_between_0_and_15:
BEQ R6, R0, done
MOVV $1, R14
XOR R15, R15
ADDV R6, R5, R5
flush_buffer:
MOVBU -1(R5), R25
SRLV $56, R14, R24
SLLV $8, R15, R28
SLLV $8, R14, R14
OR R24, R28, R15
XOR R25, R14, R14
SUBV $1, R6, R6
SUBV $1, R5, R5
BNE R6, R0, flush_buffer
ADDV R14, R8, R8
SGTU R14, R8, R24
ADDV R15, R9, R27
SGTU R15, R27, R28
ADDV R27, R24, R9
SGTU R27, R9, R24
OR R24, R28, R24
ADDV R10, R24, R10
MOVV $16, R6
JMP multiply
done:
MOVV R8, (R4)
MOVV R9, 8(R4)
MOVV R10, 16(R4)
RET
-47
View File
@@ -1,47 +0,0 @@
// Copyright 2019 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 gc && !purego && (ppc64 || ppc64le)
package poly1305
//go:noescape
func update(state *macState, msg []byte)
// mac is a wrapper for macGeneric that redirects calls that would have gone to
// updateGeneric to update.
//
// Its Write and Sum methods are otherwise identical to the macGeneric ones, but
// using function pointers would carry a major performance cost.
type mac struct{ macGeneric }
func (h *mac) Write(p []byte) (int, error) {
nn := len(p)
if h.offset > 0 {
n := copy(h.buffer[h.offset:], p)
if h.offset+n < TagSize {
h.offset += n
return nn, nil
}
p = p[n:]
h.offset = 0
update(&h.macState, h.buffer[:])
}
if n := len(p) - (len(p) % TagSize); n > 0 {
update(&h.macState, p[:n])
p = p[n:]
}
if len(p) > 0 {
h.offset += copy(h.buffer[h.offset:], p)
}
return nn, nil
}
func (h *mac) Sum(out *[16]byte) {
state := h.macState
if h.offset > 0 {
update(&state, h.buffer[:h.offset])
}
finalize(out, &state.h, &state.s)
}
+158
View File
@@ -0,0 +1,158 @@
// 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.
//go:build gc && !purego
#define LOAD64U(base, offset, t0, t1, t2, t3, dst) \
MOVBU (offset+0*1)(base), t0; \
MOVBU (offset+1*1)(base), t1; \
MOVBU (offset+2*1)(base), t2; \
MOVBU (offset+3*1)(base), t3; \
SLL $8, t1; \
SLL $16, t2; \
SLL $24, t3; \
OR t1, t0; \
OR t3, t2; \
OR t2, t0, dst; \
MOVBU (offset+4*1)(base), t0; \
MOVBU (offset+5*1)(base), t1; \
MOVBU (offset+6*1)(base), t2; \
MOVBU (offset+7*1)(base), t3; \
SLL $32, t0; \
SLL $40, t1; \
SLL $48, t2; \
SLL $56, t3; \
OR t1, t0; \
OR t3, t2; \
OR t2, t0; \
OR t0, dst
// func update(state *macState, msg []byte)
TEXT ·update(SB), $0-32
MOV state+0(FP), X5
MOV msg_base+8(FP), X6
MOV msg_len+16(FP), X7
MOV $16, X8
AND $7, X6, X28
MOV (0*8)(X5), X9 // h0
MOV (1*8)(X5), X10 // h1
MOV (2*8)(X5), X11 // h2
MOV (3*8)(X5), X12 // r0
MOV (4*8)(X5), X13 // r1
BLT X7, X8, tail
loop:
BEQZ X28, aligned_load
LOAD64U(X6, 0*8, X16, X18, X19, X20, X15) // msg[0:8]
LOAD64U(X6, 1*8, X16, X18, X19, X20, X17) // msg[8:16]
JMP block
aligned_load:
MOV (0*8)(X6), X15 // msg[0:8]
MOV (1*8)(X6), X17 // msg[8:16]
block:
ADD X15, X9 // h0 (x1 + y1 = z1', if z1' < x1 then z1' overflow)
SLTU X15, X9, X19 // h0.carry
ADD X17, X10, X22
SLTU X17, X22, X23
ADD X22, X19, X10 // h1
SLTU X22, X10, X19
OR X23, X19 // h1.carry
ADD $1, X19
ADD X19, X11 // h2
ADD $16, X6 // msg = msg[16:]
multiply:
MULHU X9, X12, X16 // h0r0.hi
MUL X9, X12, X15 // h0r0.lo
MULHU X10, X12, X17 // h1r0.hi
MUL X10, X12, X14 // h1r0.lo
ADD X14, X16
SLTU X14, X16, X19
ADD X19, X17
MUL X11, X12, X20
ADD X17, X20
MULHU X9, X13, X17 // h0r1.hi
MUL X9, X13, X14 // h0r1.lo
ADD X14, X16
SLTU X14, X16, X19
ADD X19, X17
MOV X17, X9
MUL X11, X13, X21 // h2r1
MULHU X10, X13, X17 // h1r1.hi
MUL X10, X13, X14 // h1r1.lo
ADD X14, X20
ADD X17, X21, X22
SLTU X14, X20, X19
ADD X22, X19, X21
ADD X9, X20
SLTU X9, X20, X19
ADD X19, X21
AND $3, X20, X11
AND $-4, X20, X18
ADD X18, X15, X9
ADD X21, X16, X22
SLTU X18, X9, X19
SLTU X21, X22, X23
ADD X22, X19, X10
SLTU X22, X10, X19
OR X19, X23, X19
ADD X19, X11
SLL $62, X21, X22
SRL $2, X20, X23
SRL $2, X21, X21
OR X22, X23, X20
ADD X20, X9, X9
ADD X21, X10, X22
SLTU X20, X9, X19
SLTU X21, X22, X23
ADD X22, X19, X10
SLTU X22, X10, X19
OR X19, X23, X19
ADD X19, X11, X11
SUB $16, X7, X7
BGE X7, X8, loop
tail:
BEQ X7, X0, done
MOV $1, X15
MOV $0, X16
ADD X7, X6, X6
flush_buffer:
MOVBU -1(X6), X20
SRL $56, X15, X19
SLL $8, X16, X23
SLL $8, X15, X15
OR X19, X23, X16
XOR X20, X15
SUB $1, X7, X7
SUB $1, X6, X6
BNE X7, X0, flush_buffer
ADD X15, X9
SLTU X15, X9, X19
ADD X16, X10, X22
SLTU X16, X22, X23
ADD X22, X19, X10
SLTU X22, X10, X19
OR X23, X19
ADD X19, X11
MOV $16, X7
JMP multiply
done:
MOV X9, (0*8)(X5) // h0
MOV X10, (1*8)(X5)
MOV X11, (2*8)(X5)
RET
-12
View File
@@ -1,12 +0,0 @@
This package runs a set of the Wycheproof tests provided by
https://github.com/google/wycheproof.
The JSON test files live in
https://github.com/google/wycheproof/tree/master/testvectors
and are being fetched and cached at a pinned version every time
these tests are run. To change the version of the wycheproof
repository that is being used for testing, update wycheproofModVer.
The structs for these tests are generated from the
schemas provided in https://github.com/google/wycheproof/tree/master/schemas
using https://github.com/a-h/generate.
-176
View File
@@ -1,176 +0,0 @@
// Copyright 2020 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 wycheproof
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"fmt"
"testing"
"golang.org/x/crypto/chacha20poly1305"
)
func TestAEAD(t *testing.T) {
// AeadTestVector
type AeadTestVector struct {
// additional authenticated data
Aad string `json:"aad,omitempty"`
// A brief description of the test case
Comment string `json:"comment,omitempty"`
// the ciphertext (without iv and tag)
Ct string `json:"ct,omitempty"`
// A list of flags
Flags []string `json:"flags,omitempty"`
// the nonce
Iv string `json:"iv,omitempty"`
// the key
Key string `json:"key,omitempty"`
// the plaintext
Msg string `json:"msg,omitempty"`
// Test result
Result string `json:"result,omitempty"`
// the authentication tag
Tag string `json:"tag,omitempty"`
// Identifier of the test case
TcId int `json:"tcId,omitempty"`
}
// Notes a description of the labels used in the test vectors
type Notes struct {
}
// AeadTestGroup
type AeadTestGroup struct {
// the IV size in bits
IvSize int `json:"ivSize,omitempty"`
// the keySize in bits
KeySize int `json:"keySize,omitempty"`
// the expected size of the tag in bits
TagSize int `json:"tagSize,omitempty"`
Tests []*AeadTestVector `json:"tests,omitempty"`
Type interface{} `json:"type,omitempty"`
}
// Root
type Root struct {
// the primitive tested in the test file
Algorithm string `json:"algorithm,omitempty"`
// the version of the test vectors.
GeneratorVersion string `json:"generatorVersion,omitempty"`
// additional documentation
Header []string `json:"header,omitempty"`
// a description of the labels used in the test vectors
Notes *Notes `json:"notes,omitempty"`
// the number of test vectors in this test
NumberOfTests int `json:"numberOfTests,omitempty"`
Schema interface{} `json:"schema,omitempty"`
TestGroups []*AeadTestGroup `json:"testGroups,omitempty"`
}
testSealOpen := func(t *testing.T, aead cipher.AEAD, tv *AeadTestVector, recoverBadNonce func()) {
defer recoverBadNonce()
iv, tag, ct, msg, aad := decodeHex(tv.Iv), decodeHex(tv.Tag), decodeHex(tv.Ct), decodeHex(tv.Msg), decodeHex(tv.Aad)
genCT := aead.Seal(nil, iv, msg, aad)
genMsg, err := aead.Open(nil, iv, genCT, aad)
if err != nil {
t.Errorf("failed to decrypt generated ciphertext: %s", err)
}
if !bytes.Equal(genMsg, msg) {
t.Errorf("unexpected roundtripped plaintext: got %x, want %x", genMsg, msg)
}
ctWithTag := append(ct, tag...)
msg2, err := aead.Open(nil, iv, ctWithTag, aad)
wantPass := shouldPass(tv.Result, tv.Flags, nil)
if !wantPass && err == nil {
t.Error("decryption succeeded when it should've failed")
} else if wantPass {
if err != nil {
t.Fatalf("decryption failed: %s", err)
}
if !bytes.Equal(genCT, ctWithTag) {
t.Errorf("generated ciphertext doesn't match expected: got %x, want %x", genCT, ctWithTag)
}
if !bytes.Equal(msg, msg2) {
t.Errorf("decrypted ciphertext doesn't match expected: got %x, want %x", msg2, msg)
}
}
}
vectors := map[string]func(*testing.T, []byte) cipher.AEAD{
"aes_gcm_test.json": func(t *testing.T, key []byte) cipher.AEAD {
aesCipher, err := aes.NewCipher(key)
if err != nil {
t.Fatalf("failed to construct cipher: %s", err)
}
aead, err := cipher.NewGCM(aesCipher)
if err != nil {
t.Fatalf("failed to construct cipher: %s", err)
}
return aead
},
"chacha20_poly1305_test.json": func(t *testing.T, key []byte) cipher.AEAD {
aead, err := chacha20poly1305.New(key)
if err != nil {
t.Fatalf("failed to construct cipher: %s", err)
}
return aead
},
"xchacha20_poly1305_test.json": func(t *testing.T, key []byte) cipher.AEAD {
aead, err := chacha20poly1305.NewX(key)
if err != nil {
t.Fatalf("failed to construct cipher: %s", err)
}
return aead
},
}
for file, cipherInit := range vectors {
var root Root
readTestVector(t, file, &root)
for _, tg := range root.TestGroups {
for _, tv := range tg.Tests {
testName := fmt.Sprintf("%s #%d", file, tv.TcId)
if tv.Comment != "" {
testName += fmt.Sprintf(" %s", tv.Comment)
}
t.Run(testName, func(t *testing.T) {
aead := cipherInit(t, decodeHex(tv.Key))
testSealOpen(t, aead, tv, func() {
// A bad nonce causes a panic in AEAD.Seal and AEAD.Open,
// so should be recovered. Fail the test if it broke for
// some other reason.
if r := recover(); r != nil {
if tg.IvSize/8 == aead.NonceSize() {
t.Error("unexpected panic")
}
}
})
})
}
}
}
}
-127
View File
@@ -1,127 +0,0 @@
// Copyright 2019 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 wycheproof
import (
"crypto/aes"
"crypto/cipher"
"encoding/hex"
"fmt"
"testing"
)
func TestAesCbc(t *testing.T) {
// IndCpaTestVector
type IndCpaTestVector struct {
// A brief description of the test case
Comment string `json:"comment,omitempty"`
// the raw ciphertext (without IV)
Ct string `json:"ct,omitempty"`
// A list of flags
Flags []string `json:"flags,omitempty"`
// the initialization vector
Iv string `json:"iv,omitempty"`
// the key
Key string `json:"key,omitempty"`
// the plaintext
Msg string `json:"msg,omitempty"`
// Test result
Result string `json:"result,omitempty"`
// Identifier of the test case
TcId int `json:"tcId,omitempty"`
}
// Notes a description of the labels used in the test vectors
type Notes struct {
}
// IndCpaTestGroup
type IndCpaTestGroup struct {
// the IV size in bits
IvSize int `json:"ivSize,omitempty"`
// the keySize in bits
KeySize int `json:"keySize,omitempty"`
// the expected size of the tag in bits
TagSize int `json:"tagSize,omitempty"`
Tests []*IndCpaTestVector `json:"tests,omitempty"`
Type interface{} `json:"type,omitempty"`
}
// Root
type Root struct {
// the primitive tested in the test file
Algorithm string `json:"algorithm,omitempty"`
// the version of the test vectors.
GeneratorVersion string `json:"generatorVersion,omitempty"`
// additional documentation
Header []string `json:"header,omitempty"`
// a description of the labels used in the test vectors
Notes *Notes `json:"notes,omitempty"`
// the number of test vectors in this test
NumberOfTests int `json:"numberOfTests,omitempty"`
Schema interface{} `json:"schema,omitempty"`
TestGroups []*IndCpaTestGroup `json:"testGroups,omitempty"`
}
var root Root
readTestVector(t, "aes_cbc_pkcs5_test.json", &root)
for _, tg := range root.TestGroups {
tests:
for _, tv := range tg.Tests {
block, err := aes.NewCipher(decodeHex(tv.Key))
if err != nil {
t.Fatalf("#%d: %v", tv.TcId, err)
}
mode := cipher.NewCBCDecrypter(block, decodeHex(tv.Iv))
ct := decodeHex(tv.Ct)
if len(ct)%aes.BlockSize != 0 {
panic(fmt.Sprintf("#%d: ciphertext is not a multiple of the block size", tv.TcId))
}
mode.CryptBlocks(ct, ct) // decrypt the block in place
// Skip the tests that are broken due to bad padding. Panic if there are any
// tests left that are invalid for some other reason in the future, to
// evaluate what to do with those tests.
for _, flag := range tv.Flags {
if flag == "BadPadding" {
continue tests
}
}
if !shouldPass(tv.Result, tv.Flags, nil) {
panic(fmt.Sprintf("#%d: found an invalid test that is broken for some reason other than bad padding", tv.TcId))
}
// Remove the PKCS#5 padding from the given ciphertext to validate it
padding := ct[len(ct)-1]
paddingNum := int(padding)
for i := paddingNum; i > 0; i-- {
if ct[len(ct)-i] != padding { // panic if the padding is unexpectedly bad
panic(fmt.Sprintf("#%d: bad padding at index=%d of %v", tv.TcId, i, ct))
}
}
ct = ct[:len(ct)-paddingNum]
if got, want := hex.EncodeToString(ct), tv.Msg; got != want {
t.Errorf("#%d, type: %s, comment: %q, decoded ciphertext not equal: %s, want %s", tv.TcId, tv.Result, tv.Comment, got, want)
}
}
}
}
-9
View File
@@ -1,9 +0,0 @@
// Copyright 2022 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 boringcrypto
package wycheproof
const boringcryptoEnabled = true
-123
View File
@@ -1,123 +0,0 @@
// Copyright 2019 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 wycheproof
import (
"crypto/dsa"
"testing"
wdsa "golang.org/x/crypto/internal/wycheproof/internal/dsa"
)
func TestDsa(t *testing.T) {
// AsnSignatureTestVector
type AsnSignatureTestVector struct {
// A brief description of the test case
Comment string `json:"comment,omitempty"`
// A list of flags
Flags []string `json:"flags,omitempty"`
// The message to sign
Msg string `json:"msg,omitempty"`
// Test result
Result string `json:"result,omitempty"`
// An ASN encoded signature for msg
Sig string `json:"sig,omitempty"`
// Identifier of the test case
TcId int `json:"tcId,omitempty"`
}
// DsaPublicKey
type DsaPublicKey struct {
// the generator of the multiplicative subgroup
G string `json:"g,omitempty"`
// the key size in bits
KeySize int `json:"keySize,omitempty"`
// the modulus p
P string `json:"p,omitempty"`
// the order of the generator g
Q string `json:"q,omitempty"`
// the key type
Type string `json:"type,omitempty"`
// the public key value
Y string `json:"y,omitempty"`
}
// DsaTestGroup
type DsaTestGroup struct {
// unenocded DSA public key
Key *DsaPublicKey `json:"key,omitempty"`
// DER encoded public key
KeyDer string `json:"keyDer,omitempty"`
// Pem encoded public key
KeyPem string `json:"keyPem,omitempty"`
// the hash function used for DSA
Sha string `json:"sha,omitempty"`
Tests []*AsnSignatureTestVector `json:"tests,omitempty"`
Type interface{} `json:"type,omitempty"`
}
// Notes a description of the labels used in the test vectors
type Notes struct {
}
// Root
type Root struct {
// the primitive tested in the test file
Algorithm string `json:"algorithm,omitempty"`
// the version of the test vectors.
GeneratorVersion string `json:"generatorVersion,omitempty"`
// additional documentation
Header []string `json:"header,omitempty"`
// a description of the labels used in the test vectors
Notes *Notes `json:"notes,omitempty"`
// the number of test vectors in this test
NumberOfTests int `json:"numberOfTests,omitempty"`
Schema interface{} `json:"schema,omitempty"`
TestGroups []*DsaTestGroup `json:"testGroups,omitempty"`
}
flagsShouldPass := map[string]bool{
// An encoded ASN.1 integer missing a leading zero is invalid, but accepted by some implementations.
"NoLeadingZero": false,
}
var root Root
readTestVector(t, "dsa_test.json", &root)
for _, tg := range root.TestGroups {
pub := decodePublicKey(tg.KeyDer).(*dsa.PublicKey)
h := parseHash(tg.Sha).New()
for _, sig := range tg.Tests {
h.Reset()
h.Write(decodeHex(sig.Msg))
hashed := h.Sum(nil)
hashed = hashed[:pub.Q.BitLen()/8] // Truncate to the byte-length of the subgroup (Q)
got := wdsa.VerifyASN1(pub, hashed, decodeHex(sig.Sig))
if want := shouldPass(sig.Result, sig.Flags, flagsShouldPass); got != want {
t.Errorf("tcid: %d, type: %s, comment: %q, wanted success: %t", sig.TcId, sig.Result, sig.Comment, want)
}
}
}
}
-140
View File
@@ -1,140 +0,0 @@
// Copyright 2022 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 wycheproof
import (
"bytes"
"crypto/ecdh"
"fmt"
"testing"
)
func TestECDHStdLib(t *testing.T) {
type ECDHTestVector struct {
// A brief description of the test case
Comment string `json:"comment,omitempty"`
// A list of flags
Flags []string `json:"flags,omitempty"`
// the private key
Private string `json:"private,omitempty"`
// Encoded public key
Public string `json:"public,omitempty"`
// Test result
Result string `json:"result,omitempty"`
// The shared secret key
Shared string `json:"shared,omitempty"`
// Identifier of the test case
TcID int `json:"tcId,omitempty"`
}
type ECDHTestGroup struct {
Curve string `json:"curve,omitempty"`
Tests []*ECDHTestVector `json:"tests,omitempty"`
}
type Root struct {
TestGroups []*ECDHTestGroup `json:"testGroups,omitempty"`
}
flagsShouldPass := map[string]bool{
// We don't support compressed points.
"CompressedPoint": false,
// We don't support decoding custom curves.
"UnnamedCurve": false,
// WrongOrder and UnusedParam are only found with UnnamedCurve.
"WrongOrder": false,
"UnusedParam": false,
// X25519 specific flags
"Twist": true,
"SmallPublicKey": false,
"LowOrderPublic": false,
"ZeroSharedSecret": false,
"NonCanonicalPublic": true,
}
// curveToCurve is a map of all elliptic curves supported
// by crypto/elliptic, which can subsequently be parsed and tested.
curveToCurve := map[string]ecdh.Curve{
"secp256r1": ecdh.P256(),
"secp384r1": ecdh.P384(),
"secp521r1": ecdh.P521(),
"curve25519": ecdh.X25519(),
}
curveToKeySize := map[string]int{
"secp256r1": 32,
"secp384r1": 48,
"secp521r1": 66,
"curve25519": 32,
}
for _, f := range []string{
"ecdh_secp256r1_ecpoint_test.json",
"ecdh_secp384r1_ecpoint_test.json",
"ecdh_secp521r1_ecpoint_test.json",
"x25519_test.json",
} {
var root Root
readTestVector(t, f, &root)
for _, tg := range root.TestGroups {
if _, ok := curveToCurve[tg.Curve]; !ok {
continue
}
for _, tt := range tg.Tests {
tg, tt := tg, tt
t.Run(fmt.Sprintf("%s/%d", tg.Curve, tt.TcID), func(t *testing.T) {
t.Logf("Type: %v", tt.Result)
t.Logf("Flags: %q", tt.Flags)
t.Log(tt.Comment)
shouldPass := shouldPass(tt.Result, tt.Flags, flagsShouldPass)
curve := curveToCurve[tg.Curve]
p := decodeHex(tt.Public)
pub, err := curve.NewPublicKey(p)
if err != nil {
if shouldPass {
t.Errorf("NewPublicKey: %v", err)
}
return
}
privBytes := decodeHex(tt.Private)
if len(privBytes) != curveToKeySize[tg.Curve] {
t.Skipf("non-standard key size %d", len(privBytes))
}
priv, err := curve.NewPrivateKey(privBytes)
if err != nil {
if shouldPass {
t.Errorf("NewPrivateKey: %v", err)
}
return
}
shared := decodeHex(tt.Shared)
x, err := priv.ECDH(pub)
if err != nil {
if tg.Curve == "curve25519" && !shouldPass {
// ECDH is expected to only return an error when using X25519,
// in all other cases an error is unexpected.
return
}
t.Fatalf("ECDH: %v", err)
}
if bytes.Equal(shared, x) != shouldPass {
if shouldPass {
t.Errorf("ECDH = %x, want %x", shared, x)
} else {
t.Errorf("ECDH = %x, want anything else", shared)
}
}
})
}
}
}
}
-163
View File
@@ -1,163 +0,0 @@
// Copyright 2019 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 wycheproof
import (
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/x509"
"encoding/asn1"
"errors"
"fmt"
"testing"
"golang.org/x/crypto/cryptobyte"
casn1 "golang.org/x/crypto/cryptobyte/asn1"
)
func TestECDH(t *testing.T) {
type ECDHTestVector struct {
// A brief description of the test case
Comment string `json:"comment,omitempty"`
// A list of flags
Flags []string `json:"flags,omitempty"`
// the private key
Private string `json:"private,omitempty"`
// Encoded public key
Public string `json:"public,omitempty"`
// Test result
Result string `json:"result,omitempty"`
// The shared secret key
Shared string `json:"shared,omitempty"`
// Identifier of the test case
TcID int `json:"tcId,omitempty"`
}
type ECDHTestGroup struct {
Curve string `json:"curve,omitempty"`
Tests []*ECDHTestVector `json:"tests,omitempty"`
}
type Root struct {
TestGroups []*ECDHTestGroup `json:"testGroups,omitempty"`
}
flagsShouldPass := map[string]bool{
// ParsePKIXPublicKey doesn't support compressed points, but we test
// them against UnmarshalCompressed anyway.
"CompressedPoint": true,
// We don't support decoding custom curves.
"UnnamedCurve": false,
// WrongOrder and UnusedParam are only found with UnnamedCurve.
"WrongOrder": false,
"UnusedParam": false,
}
// supportedCurves is a map of all elliptic curves supported
// by crypto/elliptic, which can subsequently be parsed and tested.
supportedCurves := map[string]bool{
"secp224r1": true,
"secp256r1": true,
"secp384r1": true,
"secp521r1": true,
}
var root Root
readTestVector(t, "ecdh_test.json", &root)
for _, tg := range root.TestGroups {
if !supportedCurves[tg.Curve] {
continue
}
for _, tt := range tg.Tests {
tg, tt := tg, tt
t.Run(fmt.Sprintf("%s/%d", tg.Curve, tt.TcID), func(t *testing.T) {
t.Logf("Type: %v", tt.Result)
t.Logf("Flags: %q", tt.Flags)
t.Log(tt.Comment)
shouldPass := shouldPass(tt.Result, tt.Flags, flagsShouldPass)
p := decodeHex(tt.Public)
pp, err := x509.ParsePKIXPublicKey(p)
if err != nil {
pp, err = decodeCompressedPKIX(p)
}
if err != nil {
if shouldPass {
t.Errorf("unexpected parsing error: %s", err)
}
return
}
pub := pp.(*ecdsa.PublicKey)
priv := decodeHex(tt.Private)
shared := decodeHex(tt.Shared)
x, _ := pub.Curve.ScalarMult(pub.X, pub.Y, priv)
xBytes := make([]byte, (pub.Curve.Params().BitSize+7)/8)
got := bytes.Equal(shared, x.FillBytes(xBytes))
if want := shouldPass; got != want {
t.Errorf("wanted success %v, got %v", want, got)
}
})
}
}
}
func decodeCompressedPKIX(der []byte) (interface{}, error) {
s := cryptobyte.String(der)
var s1, s2 cryptobyte.String
var algoOID, namedCurveOID asn1.ObjectIdentifier
var pointDER []byte
if !s.ReadASN1(&s1, casn1.SEQUENCE) || !s.Empty() ||
!s1.ReadASN1(&s2, casn1.SEQUENCE) ||
!s2.ReadASN1ObjectIdentifier(&algoOID) ||
!s2.ReadASN1ObjectIdentifier(&namedCurveOID) || !s2.Empty() ||
!s1.ReadASN1BitStringAsBytes(&pointDER) || !s1.Empty() {
return nil, errors.New("failed to parse PKIX structure")
}
if !algoOID.Equal(oidPublicKeyECDSA) {
return nil, errors.New("wrong algorithm OID")
}
namedCurve := namedCurveFromOID(namedCurveOID)
if namedCurve == nil {
return nil, errors.New("unsupported elliptic curve")
}
x, y := elliptic.UnmarshalCompressed(namedCurve, pointDER)
if x == nil {
return nil, errors.New("failed to unmarshal elliptic curve point")
}
pub := &ecdsa.PublicKey{
Curve: namedCurve,
X: x,
Y: y,
}
return pub, nil
}
var (
oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
)
func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
switch {
case oid.Equal(oidNamedCurveP224):
return elliptic.P224()
case oid.Equal(oidNamedCurveP256):
return elliptic.P256()
case oid.Equal(oidNamedCurveP384):
return elliptic.P384()
case oid.Equal(oidNamedCurveP521):
return elliptic.P521()
}
return nil
}
-105
View File
@@ -1,105 +0,0 @@
// Copyright 2019 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 wycheproof
import (
"crypto/ecdsa"
"math/big"
"testing"
"golang.org/x/crypto/cryptobyte"
"golang.org/x/crypto/cryptobyte/asn1"
)
func TestECDSA(t *testing.T) {
type ASNSignatureTestVector struct {
// A brief description of the test case
Comment string `json:"comment"`
// A list of flags
Flags []string `json:"flags"`
// The message to sign
Msg string `json:"msg"`
// Test result
Result string `json:"result"`
// An ASN.1 encoded signature for msg
Sig string `json:"sig"`
// Identifier of the test case
TcID int `json:"tcId"`
}
type ECPublicKey struct {
// The EC group used by this public key
Curve interface{} `json:"curve"`
}
type ECDSATestGroup struct {
// Unencoded EC public key
Key *ECPublicKey `json:"key"`
// DER encoded public key
KeyDER string `json:"keyDer"`
// the hash function used for ECDSA
SHA string `json:"sha"`
Tests []*ASNSignatureTestVector `json:"tests"`
}
type Root struct {
TestGroups []*ECDSATestGroup `json:"testGroups"`
}
flagsShouldPass := map[string]bool{
// An encoded ASN.1 integer missing a leading zero is invalid, but
// accepted by some implementations.
"MissingZero": false,
// A signature using a weaker hash than the EC params is not a security
// risk, as long as the hash is secure.
// https://www.imperialviolet.org/2014/05/25/strengthmatching.html
"WeakHash": true,
}
// supportedCurves is a map of all elliptic curves supported
// by crypto/elliptic, which can subsequently be parsed and tested.
supportedCurves := map[string]bool{
"secp224r1": true,
"secp256r1": true,
"secp384r1": true,
"secp521r1": true,
}
var root Root
readTestVector(t, "ecdsa_test.json", &root)
for _, tg := range root.TestGroups {
curve := tg.Key.Curve.(string)
if !supportedCurves[curve] {
continue
}
pub := decodePublicKey(tg.KeyDER).(*ecdsa.PublicKey)
h := parseHash(tg.SHA).New()
for _, sig := range tg.Tests {
h.Reset()
h.Write(decodeHex(sig.Msg))
hashed := h.Sum(nil)
sigBytes := decodeHex(sig.Sig)
got := ecdsa.VerifyASN1(pub, hashed, sigBytes)
if want := shouldPass(sig.Result, sig.Flags, flagsShouldPass); got != want {
t.Errorf("tcid: %d, type: %s, comment: %q, VerifyASN1 wanted success: %t", sig.TcID, sig.Result, sig.Comment, want)
}
var r, s big.Int
var inner cryptobyte.String
input := cryptobyte.String(sigBytes)
if !input.ReadASN1(&inner, asn1.SEQUENCE) ||
!input.Empty() ||
!inner.ReadASN1Integer(&r) ||
!inner.ReadASN1Integer(&s) ||
!inner.Empty() {
continue
}
got = ecdsa.Verify(pub, hashed, &r, &s)
if want := shouldPass(sig.Result, sig.Flags, flagsShouldPass); got != want {
t.Errorf("tcid: %d, type: %s, comment: %q, Verify wanted success: %t", sig.TcID, sig.Result, sig.Comment, want)
}
}
}
}
-97
View File
@@ -1,97 +0,0 @@
// Copyright 2019 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 wycheproof
import (
"crypto/ed25519"
"testing"
)
func TestEddsa(t *testing.T) {
// Jwk the private key in webcrypto format
type Jwk struct {
}
// Key unencoded key pair
type Key struct {
}
// Notes a description of the labels used in the test vectors
type Notes struct {
}
// SignatureTestVector
type SignatureTestVector struct {
// A brief description of the test case
Comment string `json:"comment,omitempty"`
// A list of flags
Flags []string `json:"flags,omitempty"`
// The message to sign
Msg string `json:"msg,omitempty"`
// Test result
Result string `json:"result,omitempty"`
// A signature for msg
Sig string `json:"sig,omitempty"`
// Identifier of the test case
TcId int `json:"tcId,omitempty"`
}
// EddsaTestGroup
type EddsaTestGroup struct {
// the private key in webcrypto format
Jwk *Jwk `json:"jwk,omitempty"`
// unencoded key pair
Key *Key `json:"key,omitempty"`
// Asn encoded public key
KeyDer string `json:"keyDer,omitempty"`
// Pem encoded public key
KeyPem string `json:"keyPem,omitempty"`
Tests []*SignatureTestVector `json:"tests,omitempty"`
Type interface{} `json:"type,omitempty"`
}
// Root
type Root struct {
// the primitive tested in the test file
Algorithm string `json:"algorithm,omitempty"`
// the version of the test vectors.
GeneratorVersion string `json:"generatorVersion,omitempty"`
// additional documentation
Header []string `json:"header,omitempty"`
// a description of the labels used in the test vectors
Notes *Notes `json:"notes,omitempty"`
// the number of test vectors in this test
NumberOfTests int `json:"numberOfTests,omitempty"`
Schema interface{} `json:"schema,omitempty"`
TestGroups []*EddsaTestGroup `json:"testGroups,omitempty"`
}
var root Root
readTestVector(t, "eddsa_test.json", &root)
for _, tg := range root.TestGroups {
pub := decodePublicKey(tg.KeyDer).(ed25519.PublicKey)
for _, sig := range tg.Tests {
got := ed25519.Verify(pub, decodeHex(sig.Msg), decodeHex(sig.Sig))
if want := shouldPass(sig.Result, sig.Flags, nil); got != want {
t.Errorf("tcid: %d, type: %s, comment: %q, wanted success: %t", sig.TcId, sig.Result, sig.Comment, want)
}
}
}
}
-111
View File
@@ -1,111 +0,0 @@
// Copyright 2019 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 wycheproof
import (
"bytes"
"io"
"testing"
"golang.org/x/crypto/hkdf"
)
func TestHkdf(t *testing.T) {
// HkdfTestVector
type HkdfTestVector struct {
// A brief description of the test case
Comment string `json:"comment,omitempty"`
// A list of flags
Flags []string `json:"flags,omitempty"`
// the key (input key material)
Ikm string `json:"ikm,omitempty"`
// additional information used in the key derivation
Info string `json:"info,omitempty"`
// the generated bytes (output key material)
Okm string `json:"okm,omitempty"`
// Test result
Result string `json:"result,omitempty"`
// the salt for the key derivation
Salt string `json:"salt,omitempty"`
// the size of the output in bytes
Size int `json:"size,omitempty"`
// Identifier of the test case
TcId int `json:"tcId,omitempty"`
}
// Notes a description of the labels used in the test vectors
type Notes struct {
}
// HkdfTestGroup
type HkdfTestGroup struct {
// the size of the ikm in bits
KeySize int `json:"keySize,omitempty"`
Tests []*HkdfTestVector `json:"tests,omitempty"`
Type interface{} `json:"type,omitempty"`
}
// Root
type Root struct {
// the primitive tested in the test file
Algorithm string `json:"algorithm,omitempty"`
// the version of the test vectors.
GeneratorVersion string `json:"generatorVersion,omitempty"`
// additional documentation
Header []string `json:"header,omitempty"`
// a description of the labels used in the test vectors
Notes *Notes `json:"notes,omitempty"`
// the number of test vectors in this test
NumberOfTests int `json:"numberOfTests,omitempty"`
Schema interface{} `json:"schema,omitempty"`
TestGroups []*HkdfTestGroup `json:"testGroups,omitempty"`
}
fileHashAlgorithms := map[string]string{
"hkdf_sha1_test.json": "SHA-1",
"hkdf_sha256_test.json": "SHA-256",
"hkdf_sha384_test.json": "SHA-384",
"hkdf_sha512_test.json": "SHA-512",
}
for f := range fileHashAlgorithms {
var root Root
readTestVector(t, f, &root)
for _, tg := range root.TestGroups {
for _, tv := range tg.Tests {
h := parseHash(fileHashAlgorithms[f]).New
hkdf := hkdf.New(h, decodeHex(tv.Ikm), decodeHex(tv.Salt), decodeHex(tv.Info))
key := make([]byte, tv.Size)
wantPass := shouldPass(tv.Result, tv.Flags, nil)
_, err := io.ReadFull(hkdf, key)
if (err == nil) != wantPass {
t.Errorf("tcid: %d, type: %s, comment: %q, wanted success: %t, got: %v", tv.TcId, tv.Result, tv.Comment, wantPass, err)
}
if err != nil {
continue // don't validate output text if reading failed
}
if got, want := key, decodeHex(tv.Okm); !bytes.Equal(got, want) {
t.Errorf("tcid: %d, type: %s, comment: %q, output bytes don't match", tv.TcId, tv.Result, tv.Comment)
}
}
}
}
}
-105
View File
@@ -1,105 +0,0 @@
// Copyright 2020 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 wycheproof
import (
"crypto/hmac"
"testing"
)
func TestHMAC(t *testing.T) {
// MacTestVector
type MacTestVector struct {
// A brief description of the test case
Comment string `json:"comment,omitempty"`
// A list of flags
Flags []string `json:"flags,omitempty"`
// the key
Key string `json:"key,omitempty"`
// the plaintext
Msg string `json:"msg,omitempty"`
// Test result
Result string `json:"result,omitempty"`
// the authentication tag
Tag string `json:"tag,omitempty"`
// Identifier of the test case
TcId int `json:"tcId,omitempty"`
}
// MacTestGroup
type MacTestGroup struct {
// the keySize in bits
KeySize int `json:"keySize,omitempty"`
// the expected size of the tag in bits
TagSize int `json:"tagSize,omitempty"`
Tests []*MacTestVector `json:"tests,omitempty"`
Type interface{} `json:"type,omitempty"`
}
// Notes a description of the labels used in the test vectors
type Notes struct {
}
// Root
type Root struct {
// the primitive tested in the test file
Algorithm string `json:"algorithm,omitempty"`
// the version of the test vectors.
GeneratorVersion string `json:"generatorVersion,omitempty"`
// additional documentation
Header []string `json:"header,omitempty"`
// a description of the labels used in the test vectors
Notes *Notes `json:"notes,omitempty"`
// the number of test vectors in this test
NumberOfTests int `json:"numberOfTests,omitempty"`
Schema interface{} `json:"schema,omitempty"`
TestGroups []*MacTestGroup `json:"testGroups,omitempty"`
}
fileHashAlgs := map[string]string{
"hmac_sha1_test.json": "SHA-1",
"hmac_sha224_test.json": "SHA-224",
"hmac_sha256_test.json": "SHA-256",
"hmac_sha384_test.json": "SHA-384",
"hmac_sha512_test.json": "SHA-512",
}
for f := range fileHashAlgs {
var root Root
readTestVector(t, f, &root)
for _, tg := range root.TestGroups {
h := parseHash(fileHashAlgs[f])
// Skip test vectors where the tag length does not equal the
// hash length, since crypto/hmac does not support generating
// these truncated tags.
if tg.TagSize/8 != h.Size() {
continue
}
for _, tv := range tg.Tests {
hm := hmac.New(h.New, decodeHex(tv.Key))
hm.Write(decodeHex(tv.Msg))
tag := hm.Sum(nil)
got := hmac.Equal(decodeHex(tv.Tag), tag)
if want := shouldPass(tv.Result, tv.Flags, nil); want != got {
t.Errorf("%s, tcid: %d, type: %s, comment: %q, unexpected result", f, tv.TcId, tv.Result, tv.Comment)
}
}
}
}
}
-33
View File
@@ -1,33 +0,0 @@
// Copyright 2019 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 dsa provides an internal version of dsa.Verify
// that is used for the Wycheproof tests.
package dsa
import (
"crypto/dsa"
"math/big"
"golang.org/x/crypto/cryptobyte"
"golang.org/x/crypto/cryptobyte/asn1"
)
// VerifyASN1 verifies the ASN1 encoded signature, sig, of hash using the
// public key, pub. Its return value records whether the signature is valid.
func VerifyASN1(pub *dsa.PublicKey, hash, sig []byte) bool {
var (
r, s = &big.Int{}, &big.Int{}
inner cryptobyte.String
)
input := cryptobyte.String(sig)
if !input.ReadASN1(&inner, asn1.SEQUENCE) ||
!input.Empty() ||
!inner.ReadASN1Integer(r) ||
!inner.ReadASN1Integer(s) ||
!inner.Empty() {
return false
}
return dsa.Verify(pub, hash, r, s)
}
-9
View File
@@ -1,9 +0,0 @@
// Copyright 2022 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 !boringcrypto
package wycheproof
const boringcryptoEnabled = false
@@ -1,149 +0,0 @@
// Copyright 2020 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 wycheproof
import (
"bytes"
"crypto/rsa"
"crypto/x509"
"fmt"
"testing"
)
func TestRSAOAEPDecrypt(t *testing.T) {
// Notes a description of the labels used in the test vectors
type Notes struct {
}
// RsaesOaepTestVector
type RsaesOaepTestVector struct {
// A brief description of the test case
Comment string `json:"comment,omitempty"`
// An encryption of msg
Ct string `json:"ct,omitempty"`
// A list of flags
Flags []string `json:"flags,omitempty"`
// The label used for the encryption
Label string `json:"label,omitempty"`
// The encrypted message
Msg string `json:"msg,omitempty"`
// Test result
Result string `json:"result,omitempty"`
// Identifier of the test case
TcId int `json:"tcId,omitempty"`
}
// RsaesOaepTestGroup
type RsaesOaepTestGroup struct {
// The private exponent
D string `json:"d,omitempty"`
// The public exponent
E string `json:"e,omitempty"`
// the message generating function (e.g. MGF1)
Mgf string `json:"mgf,omitempty"`
// The hash function used for the message generating function.
MgfSha string `json:"mgfSha,omitempty"`
// The modulus of the key
N string `json:"n,omitempty"`
// Pem encoded private key
PrivateKeyPem string `json:"privateKeyPem,omitempty"`
// Pkcs 8 encoded private key.
PrivateKeyPkcs8 string `json:"privateKeyPkcs8,omitempty"`
// The hash function for hashing the label.
Sha string `json:"sha,omitempty"`
Tests []*RsaesOaepTestVector `json:"tests,omitempty"`
Type interface{} `json:"type,omitempty"`
}
// Root
type Root struct {
// the primitive tested in the test file
Algorithm string `json:"algorithm,omitempty"`
// the version of the test vectors.
GeneratorVersion string `json:"generatorVersion,omitempty"`
// additional documentation
Header []string `json:"header,omitempty"`
// a description of the labels used in the test vectors
Notes *Notes `json:"notes,omitempty"`
// the number of test vectors in this test
NumberOfTests int `json:"numberOfTests,omitempty"`
Schema interface{} `json:"schema,omitempty"`
TestGroups []*RsaesOaepTestGroup `json:"testGroups,omitempty"`
}
// rsa.DecryptOAEP doesn't support using a different hash for the
// MGF and the label, so skip all of the test vectors that use
// these unbalanced constructions. rsa_oaep_misc_test.json contains
// both balanced and unbalanced constructions so in that case
// we just filter out any test groups where MgfSha != Sha
files := []string{
"rsa_oaep_2048_sha1_mgf1sha1_test.json",
"rsa_oaep_2048_sha224_mgf1sha224_test.json",
"rsa_oaep_2048_sha256_mgf1sha256_test.json",
"rsa_oaep_2048_sha384_mgf1sha384_test.json",
"rsa_oaep_2048_sha512_mgf1sha512_test.json",
"rsa_oaep_3072_sha256_mgf1sha256_test.json",
"rsa_oaep_3072_sha512_mgf1sha512_test.json",
"rsa_oaep_4096_sha256_mgf1sha256_test.json",
"rsa_oaep_4096_sha512_mgf1sha512_test.json",
"rsa_oaep_misc_test.json",
}
flagsShouldPass := map[string]bool{
// rsa.DecryptOAEP happily supports small key sizes
"SmallModulus": true,
}
for _, f := range files {
var root Root
readTestVector(t, f, &root)
for _, tg := range root.TestGroups {
if tg.MgfSha != tg.Sha {
continue
}
priv, err := x509.ParsePKCS8PrivateKey(decodeHex(tg.PrivateKeyPkcs8))
if err != nil {
t.Fatalf("%s failed to parse PKCS #8 private key: %s", f, err)
}
hash := parseHash(tg.Sha)
for _, tv := range tg.Tests {
t.Run(fmt.Sprintf("%s #%d", f, tv.TcId), func(t *testing.T) {
wantPass := shouldPass(tv.Result, tv.Flags, flagsShouldPass)
plaintext, err := rsa.DecryptOAEP(hash.New(), nil, priv.(*rsa.PrivateKey), decodeHex(tv.Ct), decodeHex(tv.Label))
if wantPass {
if err != nil {
t.Fatalf("comment: %s, expected success: %s", tv.Comment, err)
}
if !bytes.Equal(plaintext, decodeHex(tv.Msg)) {
t.Errorf("comment: %s, unexpected plaintext: got %x, want %s", tv.Comment, plaintext, tv.Msg)
}
} else if err == nil {
t.Errorf("comment: %s, expected failure", tv.Comment)
}
})
}
}
}
}
-169
View File
@@ -1,169 +0,0 @@
// Copyright 2019 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 wycheproof
import (
"crypto/rsa"
"testing"
)
func TestRsaPss(t *testing.T) {
// KeyJwk Public key in JWK format
type KeyJwk struct {
}
// Notes a description of the labels used in the test vectors
type Notes struct {
}
// SignatureTestVector
type SignatureTestVector struct {
// A brief description of the test case
Comment string `json:"comment,omitempty"`
// A list of flags
Flags []string `json:"flags,omitempty"`
// The message to sign
Msg string `json:"msg,omitempty"`
// Test result
Result string `json:"result,omitempty"`
// A signature for msg
Sig string `json:"sig,omitempty"`
// Identifier of the test case
TcId int `json:"tcId,omitempty"`
}
// RsassaPkcs1TestGroup
type RsassaPkcs1TestGroup struct {
// The private exponent
D string `json:"d,omitempty"`
// The public exponent
E string `json:"e,omitempty"`
// ASN encoding of the sequence [n, e]
KeyAsn string `json:"keyAsn,omitempty"`
// ASN encoding of the public key
KeyDer string `json:"keyDer,omitempty"`
// Public key in JWK format
KeyJwk *KeyJwk `json:"keyJwk,omitempty"`
// Pem encoded public key
KeyPem string `json:"keyPem,omitempty"`
// the size of the modulus in bits
KeySize int `json:"keySize,omitempty"`
// The modulus of the key
N string `json:"n,omitempty"`
// The salt length
SLen int `json:"sLen,omitempty"`
// the hash function used for the message
Sha string `json:"sha,omitempty"`
Tests []*SignatureTestVector `json:"tests,omitempty"`
Type interface{} `json:"type,omitempty"`
}
// Root
type Root struct {
// the primitive tested in the test file
Algorithm string `json:"algorithm,omitempty"`
// the version of the test vectors.
GeneratorVersion string `json:"generatorVersion,omitempty"`
// additional documentation
Header []string `json:"header,omitempty"`
// a description of the labels used in the test vectors
Notes *Notes `json:"notes,omitempty"`
// the number of test vectors in this test
NumberOfTests int `json:"numberOfTests,omitempty"`
Schema interface{} `json:"schema,omitempty"`
TestGroups []*RsassaPkcs1TestGroup `json:"testGroups,omitempty"`
}
flagsShouldPass := map[string]bool{
// A signature using a weaker hash than the EC params is not a security risk, as long as the hash is secure.
// https://www.imperialviolet.org/2014/05/25/strengthmatching.html
"WeakHash": true,
}
// filesOverrideToPassZeroSLen is a map of all test files
// and which TcIds that should be overridden to pass if the
// rsa.PSSOptions.SaltLength is zero.
// These tests expect a failure with a PSSOptions.SaltLength: 0
// and a signature that uses a different salt length. However,
// a salt length of 0 is defined as rsa.PSSSaltLengthAuto which
// works deterministically to auto-detect the length when
// verifying, so these tests actually pass as they should.
filesOverrideToPassZeroSLen := map[string][]int{
"rsa_pss_2048_sha1_mgf1_20_test.json": []int{46, 47},
"rsa_pss_2048_sha256_mgf1_0_test.json": []int{67, 68},
"rsa_pss_2048_sha256_mgf1_32_test.json": []int{67, 68},
"rsa_pss_3072_sha256_mgf1_32_test.json": []int{67, 68},
"rsa_pss_4096_sha256_mgf1_32_test.json": []int{67, 68},
"rsa_pss_4096_sha512_mgf1_32_test.json": []int{136, 137},
// "rsa_pss_misc_test.json": nil, // TODO: This ones seems to be broken right now, but can enable later on.
}
if !boringcryptoEnabled {
// boringcrypto doesn't support the truncated SHA-512 hashes, so only
// test them if boringcrypto isn't enabled.
filesOverrideToPassZeroSLen["rsa_pss_2048_sha512_256_mgf1_28_test.json"] = []int{13, 14, 15}
filesOverrideToPassZeroSLen["rsa_pss_2048_sha512_256_mgf1_32_test.json"] = []int{13, 14}
}
for f := range filesOverrideToPassZeroSLen {
var root Root
readTestVector(t, f, &root)
for _, tg := range root.TestGroups {
pub := decodePublicKey(tg.KeyDer).(*rsa.PublicKey)
ch := parseHash(tg.Sha)
h := ch.New()
opts := &rsa.PSSOptions{
Hash: ch,
SaltLength: rsa.PSSSaltLengthAuto,
}
// Run all the tests twice: the first time with the salt length
// as PSSSaltLengthAuto, and the second time with the salt length
// explictily set to tg.SLen.
for i := 0; i < 2; i++ {
for _, sig := range tg.Tests {
h.Reset()
h.Write(decodeHex(sig.Msg))
hashed := h.Sum(nil)
err := rsa.VerifyPSS(pub, ch, hashed, decodeHex(sig.Sig), opts)
want := shouldPass(sig.Result, sig.Flags, flagsShouldPass)
if opts.SaltLength == 0 {
for _, id := range filesOverrideToPassZeroSLen[f] {
if sig.TcId == id {
want = true
break
}
}
}
if (err == nil) != want {
t.Errorf("file: %v, tcid: %d, type: %s, opts.SaltLength: %v, comment: %q, wanted success: %t", f, sig.TcId, sig.Result, opts.SaltLength, sig.Comment, want)
}
}
// Update opts.SaltLength for the second run of the tests.
opts.SaltLength = tg.SLen
}
}
}
}
-123
View File
@@ -1,123 +0,0 @@
// Copyright 2019 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 wycheproof
import (
"crypto/rsa"
"testing"
)
func TestRsa(t *testing.T) {
// KeyJwk Public key in JWK format
type KeyJwk struct {
}
// Notes a description of the labels used in the test vectors
type Notes struct {
}
// SignatureTestVector
type SignatureTestVector struct {
// A brief description of the test case
Comment string `json:"comment,omitempty"`
// A list of flags
Flags []string `json:"flags,omitempty"`
// The message to sign
Msg string `json:"msg,omitempty"`
// Test result
Result string `json:"result,omitempty"`
// A signature for msg
Sig string `json:"sig,omitempty"`
// Identifier of the test case
TcId int `json:"tcId,omitempty"`
}
// RsassaPkcs1TestGroup
type RsassaPkcs1TestGroup struct {
// The private exponent
D string `json:"d,omitempty"`
// The public exponent
E string `json:"e,omitempty"`
// ASN encoding of the sequence [n, e]
KeyAsn string `json:"keyAsn,omitempty"`
// ASN encoding of the public key
KeyDer string `json:"keyDer,omitempty"`
// Public key in JWK format
KeyJwk *KeyJwk `json:"keyJwk,omitempty"`
// Pem encoded public key
KeyPem string `json:"keyPem,omitempty"`
// the size of the modulus in bits
KeySize int `json:"keySize,omitempty"`
// The modulus of the key
N string `json:"n,omitempty"`
// the hash function used for the message
Sha string `json:"sha,omitempty"`
Tests []*SignatureTestVector `json:"tests,omitempty"`
Type interface{} `json:"type,omitempty"`
}
// Root
type Root struct {
// the primitive tested in the test file
Algorithm string `json:"algorithm,omitempty"`
// the version of the test vectors.
GeneratorVersion string `json:"generatorVersion,omitempty"`
// additional documentation
Header []string `json:"header,omitempty"`
// a description of the labels used in the test vectors
Notes *Notes `json:"notes,omitempty"`
// the number of test vectors in this test
NumberOfTests int `json:"numberOfTests,omitempty"`
Schema interface{} `json:"schema,omitempty"`
TestGroups []*RsassaPkcs1TestGroup `json:"testGroups,omitempty"`
}
flagsShouldPass := map[string]bool{
// Omitting the parameter field in an ASN encoded integer is a legacy behavior.
"MissingNull": false,
// Keys with a modulus less than 2048 bits are supported by crypto/rsa.
"SmallModulus": true,
// Small public keys are supported by crypto/rsa.
"SmallPublicKey": true,
}
var root Root
readTestVector(t, "rsa_signature_test.json", &root)
for _, tg := range root.TestGroups {
pub := decodePublicKey(tg.KeyDer).(*rsa.PublicKey)
ch := parseHash(tg.Sha)
h := ch.New()
for _, sig := range tg.Tests {
h.Reset()
h.Write(decodeHex(sig.Msg))
hashed := h.Sum(nil)
err := rsa.VerifyPKCS1v15(pub, ch, hashed, decodeHex(sig.Sig))
want := shouldPass(sig.Result, sig.Flags, flagsShouldPass)
if (err == nil) != want {
t.Errorf("tcid: %d, type: %s, comment: %q, wanted success: %t", sig.TcId, sig.Result, sig.Comment, want)
}
}
}
}
-141
View File
@@ -1,141 +0,0 @@
// Copyright 2019 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 wycheproof runs a set of the Wycheproof tests
// provided by https://github.com/google/wycheproof.
package wycheproof
import (
"crypto"
"crypto/x509"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"testing"
_ "crypto/sha1"
_ "crypto/sha256"
_ "crypto/sha512"
)
const wycheproofModVer = "v0.0.0-20191219022705-2196000605e4"
var wycheproofTestVectorsDir string
func TestMain(m *testing.M) {
flag.Parse()
if flag.Lookup("test.short").Value.(flag.Getter).Get().(bool) {
log.Println("skipping test that downloads testdata via 'go mod download' in short mode")
os.Exit(0)
}
if _, err := exec.LookPath("go"); err != nil {
log.Printf("skipping test because 'go' command is unavailable: %v", err)
os.Exit(0)
}
if os.Getenv("GO_BUILDER_FLAKY_NET") != "" {
log.Printf("skipping test because GO_BUILDER_FLAKY_NET is set")
os.Exit(0)
}
// Download the JSON test files from github.com/google/wycheproof
// using `go mod download -json` so the cached source of the testdata
// can be used in the following tests.
path := "github.com/google/wycheproof@" + wycheproofModVer
cmd := exec.Command("go", "mod", "download", "-json", path)
output, err := cmd.Output()
if err != nil {
log.Fatalf("failed to run `go mod download -json %s`, output: %s", path, output)
}
var dm struct {
Dir string // absolute path to cached source root directory
}
if err := json.Unmarshal(output, &dm); err != nil {
log.Fatal(err)
}
// Now that the module has been downloaded, use the absolute path of the
// cached source as the root directory for all tests going forward.
wycheproofTestVectorsDir = filepath.Join(dm.Dir, "testvectors")
os.Exit(m.Run())
}
func readTestVector(t *testing.T, f string, dest interface{}) {
b, err := os.ReadFile(filepath.Join(wycheproofTestVectorsDir, f))
if err != nil {
t.Fatalf("failed to read json file: %v", err)
}
if err := json.Unmarshal(b, &dest); err != nil {
t.Fatalf("failed to unmarshal json file: %v", err)
}
}
func decodeHex(s string) []byte {
b, err := hex.DecodeString(s)
if err != nil {
panic(err)
}
return b
}
func decodePublicKey(der string) interface{} {
d := decodeHex(der)
pub, err := x509.ParsePKIXPublicKey(d)
if err != nil {
panic(fmt.Sprintf("failed to parse DER encoded public key: %v", err))
}
return pub
}
func parseHash(h string) crypto.Hash {
switch h {
case "SHA-1":
return crypto.SHA1
case "SHA-256":
return crypto.SHA256
case "SHA-224":
return crypto.SHA224
case "SHA-384":
return crypto.SHA384
case "SHA-512":
return crypto.SHA512
case "SHA-512/224":
return crypto.SHA512_224
case "SHA-512/256":
return crypto.SHA512_256
default:
panic(fmt.Sprintf("could not identify SHA hash algorithm: %q", h))
}
}
// shouldPass returns whether or not the test should pass.
// flagsShouldPass is a map associated with whether or not
// a flag for an "acceptable" result should pass.
// Every possible flag value that's associated with an
// "acceptable" result should be explicitly specified,
// otherwise the test will panic.
func shouldPass(result string, flags []string, flagsShouldPass map[string]bool) bool {
switch result {
case "valid":
return true
case "invalid":
return false
case "acceptable":
for _, flag := range flags {
pass, ok := flagsShouldPass[flag]
if !ok {
panic(fmt.Sprintf("unspecified flag: %q", flag))
}
if !pass {
return false
}
}
return true // There are no flags, or all are meant to pass.
default:
panic(fmt.Sprintf("unexpected result: %v", result))
}
}
+10 -19
View File
@@ -2,25 +2,16 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
Package auth authenticates a message using a secret key.
The Sum function, viewed as a function of the message for a uniform random
key, is designed to meet the standard notion of unforgeability. This means
that an attacker cannot find authenticators for any messages not authenticated
by the sender, even if the attacker has adaptively influenced the messages
authenticated by the sender. For a formal definition see, e.g., Section 2.4
of Bellare, Kilian, and Rogaway, "The security of the cipher block chaining
message authentication code," Journal of Computer and System Sciences 61 (2000),
362–399; http://www-cse.ucsd.edu/~mihir/papers/cbc.html.
auth does not make any promises regarding "strong" unforgeability; perhaps
one valid authenticator can be converted into another valid authenticator for
the same message. NaCl also does not make any promises regarding "truncated
unforgeability."
This package is interoperable with NaCl: https://nacl.cr.yp.to/auth.html.
*/
// Package auth authenticates a message using a secret key.
//
// This package is interoperable with [NaCl].
//
// The auth package is essentially a wrapper for HMAC-SHA-512 (implemented by
// crypto/hmac and crypto/sha512), truncated to 32 bytes. It is [frozen] and is
// not accepting new features.
//
// [NaCl]: https://nacl.cr.yp.to/auth.html
// [frozen]: https://go.dev/wiki/Frozen
package auth
import (
+1 -1
View File
@@ -114,7 +114,7 @@ func TestSealOpenAnonymous(t *testing.T) {
t.Fatal("expected out to be unchanged")
}
if !bytes.HasPrefix(box, orig) {
t.Fatal("expected out to be coppied to returned slice")
t.Fatal("expected out to be copied to returned slice")
}
_, ok = OpenAnonymous(nil, box[len(out):], publicKey, privateKey)
if !ok {
+8 -13
View File
@@ -4,20 +4,15 @@
// Package sign signs small messages using public-key cryptography.
//
// Sign uses Ed25519 to sign messages. The length of messages is not hidden.
// Messages should be small because:
// 1. The whole message needs to be held in memory to be processed.
// 2. Using large messages pressures implementations on small machines to process
// plaintext without verifying the signature. This is very dangerous, and this API
// discourages it, but a protocol that uses excessive message sizes might present
// some implementations with no other choice.
// 3. Performance may be improved by working with messages that fit into data caches.
// Thus large amounts of data should be chunked so that each message is small.
// This package is interoperable with [libsodium], as well as [TweetNaCl].
//
// This package is not interoperable with the current release of NaCl
// (https://nacl.cr.yp.to/sign.html), which does not support Ed25519 yet. However,
// it is compatible with the NaCl fork libsodium (https://www.libsodium.org), as well
// as TweetNaCl (https://tweetnacl.cr.yp.to/).
// The sign package is essentially a wrapper for the Ed25519 signature
// algorithm (implemented by crypto/ed25519). It is [frozen] and is not accepting
// new features.
//
// [libsodium]: https://libsodium.gitbook.io/doc/public-key_cryptography/public-key_signatures
// [TweetNaCl]: https://tweetnacl.cr.yp.to/
// [frozen]: https://go.dev/wiki/Frozen
package sign
import (
+1 -1
View File
@@ -69,6 +69,6 @@ func TestGenerateSignOpen(t *testing.T) {
}
if !bytes.Equal(message, testMessage) {
t.Fatalf("verified message does not match signed messge, got\n%x\n, expected\n%x", message, testMessage)
t.Fatalf("verified message does not match signed message, got\n%x\n, expected\n%x", message, testMessage)
}
}
+12 -5
View File
@@ -85,7 +85,8 @@ type certID struct {
// https://tools.ietf.org/html/rfc2560#section-4.1.1
type ocspRequest struct {
TBSRequest tbsRequest
TBSRequest tbsRequest
OptionalSignature asn1.RawValue `asn1:"explicit,tag:0,optional"`
}
type tbsRequest struct {
@@ -321,10 +322,10 @@ type Request struct {
func (req *Request) Marshal() ([]byte, error) {
hashAlg := getOIDFromHashAlgorithm(req.HashAlgorithm)
if hashAlg == nil {
return nil, errors.New("Unknown hash algorithm")
return nil, errors.New("unknown hash algorithm")
}
return asn1.Marshal(ocspRequest{
tbsRequest{
TBSRequest: tbsRequest{
Version: 0,
RequestList: []request{
{
@@ -418,8 +419,10 @@ func (p ParseError) Error() string {
}
// ParseRequest parses an OCSP request in DER form. It only supports
// requests for a single certificate. Signed requests are not supported.
// If a request includes a signature, it will result in a ParseError.
// requests for a single certificate identifier. If a request includes
// multiple certificate identifiers, only the first will be included in
// the parsed Request. Signed requests are not supported. If a request
// includes a signature, it will result in a ParseError.
func ParseRequest(bytes []byte) (*Request, error) {
var req ocspRequest
rest, err := asn1.Unmarshal(bytes, &req)
@@ -430,6 +433,10 @@ func ParseRequest(bytes []byte) (*Request, error) {
return nil, ParseError("trailing data in OCSP request")
}
if len(req.OptionalSignature.FullBytes) > 0 {
return nil, ParseError("signed OCSP requests are not supported")
}
if len(req.TBSRequest.RequestList) == 0 {
return nil, ParseError("OCSP request contains no request body")
}
+127 -1
View File
@@ -15,10 +15,15 @@ import (
"encoding/asn1"
"encoding/hex"
"encoding/pem"
"errors"
"math/big"
"reflect"
"strings"
"testing"
"time"
"golang.org/x/crypto/cryptobyte"
cbasn1 "golang.org/x/crypto/cryptobyte/asn1"
)
func TestOCSPDecode(t *testing.T) {
@@ -190,7 +195,7 @@ func TestOCSPRequest(t *testing.T) {
t.Fatal(err)
}
if bytes.Compare(expectedBytes, marshaledRequest) != 0 {
if !bytes.Equal(expectedBytes, marshaledRequest) {
t.Errorf(
"Marshaled request doesn't match expected: wanted %x, got %x",
expectedBytes,
@@ -199,6 +204,127 @@ func TestOCSPRequest(t *testing.T) {
}
}
func TestOCSPRequestErrors(t *testing.T) {
tests := []struct {
name string
input []byte
wantErr string
}{
{
name: "signed request",
input: testOCSPRequest(1, true),
wantErr: "signed",
},
{
name: "trailing data",
input: append(testOCSPRequest(1, false), 0x00),
wantErr: "trailing",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
_, err := ParseRequest(tc.input)
if err == nil {
t.Fatalf(
"ParseRequest succeeded, want ParseError containing %q",
tc.wantErr,
)
}
var parseError ParseError
if !errors.As(err, &parseError) {
t.Fatalf("ParseRequest returned %T, want ParseError", err)
}
if !strings.Contains(parseError.Error(), tc.wantErr) {
t.Fatalf(
"ParseRequest error = %q, want it to contain %q",
parseError.Error(), tc.wantErr,
)
}
})
}
}
func TestOCSPMultipleCertRequest(t *testing.T) {
req, err := ParseRequest(testOCSPRequest(2, false))
if err != nil {
t.Fatalf("ParseRequest errored for multiple request input: %q", err)
}
// testOCSPRequest uses the request cert counter as the issuerNameHash,
// issuerKeyHash and serial. We expect the first request cert to be used
// (counter=1), not the second (counter=2).
wantHash := []byte{0x01}
if actual := req.IssuerNameHash; !bytes.Equal(actual, wantHash) {
t.Errorf(
"ParseRequest.IssuerNameHash returned = %q, wanted %q",
actual, wantHash,
)
}
if actual := req.IssuerKeyHash; !bytes.Equal(actual, wantHash) {
t.Errorf("ParseRequest.IssuerKeyHash returned = %q, wanted %q",
actual, wantHash)
}
wantSerial := big.NewInt(0x01)
if actual := req.SerialNumber; actual.Cmp(wantSerial) != 0 {
t.Errorf("ParseRequest.SerialNumber returned = %q, wanted %q",
actual, wantHash)
}
}
// testOCSPRequest constructs an unsupported OCSP request in DER form for testing.
//
// We build these by hand using cryptobyte to specifically target shapes that are
// not supported by ParseRequest, and can't be created with CreateRequest.
//
// The resulting requestList will contain numCerts RequestList entries. If
// includeSignature is true, the request will carry a signature field (with an
// arbitrary signatureAlgorithm and signature).
//
// See RFC 6960, §4.1.1.
func testOCSPRequest(numCerts int, includeSignature bool) []byte {
sha1AlgID, err := asn1.Marshal(pkix.AlgorithmIdentifier{
Algorithm: asn1.ObjectIdentifier{1, 3, 14, 3, 2, 26},
Parameters: asn1.RawValue{Tag: 5 /* ASN.1 NULL */},
})
if err != nil {
panic(err)
}
var b cryptobyte.Builder
b.AddASN1(cbasn1.SEQUENCE, func(b *cryptobyte.Builder) { // OCSPRequest
b.AddASN1(cbasn1.SEQUENCE, func(b *cryptobyte.Builder) { // tbsRequest
b.AddASN1(cbasn1.SEQUENCE, func(b *cryptobyte.Builder) { // requestList
for i := 0; i < numCerts; i++ {
b.AddASN1(cbasn1.SEQUENCE, func(b *cryptobyte.Builder) { // Request
b.AddASN1(cbasn1.SEQUENCE, func(b *cryptobyte.Builder) { // CertID
b.AddBytes(sha1AlgID) // hashAlgorithm
b.AddASN1OctetString([]byte{byte(i + 1)}) // issuerNameHash
b.AddASN1OctetString([]byte{byte(i + 1)}) // issuerKeyHash
b.AddASN1Int64(int64(i + 1)) // serialNumber
})
})
}
})
})
if includeSignature {
// optionalSignature [0] EXPLICIT Signature
b.AddASN1(cbasn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
b.AddASN1(cbasn1.SEQUENCE, func(b *cryptobyte.Builder) { // Signature
b.AddBytes(sha1AlgID) // signatureAlgorithm
b.AddASN1BitString([]byte{0x09, 0x0A, 0x0B, 0x0C}) // signature
})
})
}
})
der, err := b.Bytes()
if err != nil {
panic(err)
}
return der
}
func TestOCSPResponse(t *testing.T) {
leafCert, _ := hex.DecodeString(leafCertHex)
leaf, err := x509.ParseCertificate(leafCert)
+6 -5
View File
@@ -5,11 +5,12 @@
// Package armor implements OpenPGP ASCII Armor, see RFC 4880. OpenPGP Armor is
// very similar to PEM except that it has an additional CRC checksum.
//
// Deprecated: this package is unmaintained except for security fixes. New
// applications should consider a more focused, modern alternative to OpenPGP
// for their specific task. If you are required to interoperate with OpenPGP
// systems and need a maintained package, consider a community fork.
// See https://golang.org/issue/44226.
// Deprecated: this package is unsafe by design, and has numerous known security
// issues. It is not maintained, and should not be used. New applications should
// consider a more focused, modern alternative to OpenPGP for their specific
// task. If you are required to interoperate with OpenPGP systems and need a
// maintained package, consider github.com/ProtonMail/go-crypto/openpgp, which
// is a maintained fork that aims to be a drop-in replacement for this package.
package armor
import (
+6 -5
View File
@@ -8,11 +8,12 @@
// Clearsigned messages are cryptographically signed, but the contents of the
// message are kept in plaintext so that it can be read without special tools.
//
// Deprecated: this package is unmaintained except for security fixes. New
// applications should consider a more focused, modern alternative to OpenPGP
// for their specific task. If you are required to interoperate with OpenPGP
// systems and need a maintained package, consider a community fork.
// See https://golang.org/issue/44226.
// Deprecated: this package is unsafe by design, and has numerous known security
// issues. It is not maintained, and should not be used. New applications should
// consider a more focused, modern alternative to OpenPGP for their specific
// task. If you are required to interoperate with OpenPGP systems and need a
// maintained package, consider github.com/ProtonMail/go-crypto/openpgp, which
// is a maintained fork that aims to be a drop-in replacement for this package.
package clearsign
import (
+6 -5
View File
@@ -4,11 +4,12 @@
// Package errors contains common error types for the OpenPGP packages.
//
// Deprecated: this package is unmaintained except for security fixes. New
// applications should consider a more focused, modern alternative to OpenPGP
// for their specific task. If you are required to interoperate with OpenPGP
// systems and need a maintained package, consider a community fork.
// See https://golang.org/issue/44226.
// Deprecated: this package is unsafe by design, and has numerous known security
// issues. It is not maintained, and should not be used. New applications should
// consider a more focused, modern alternative to OpenPGP for their specific
// task. If you are required to interoperate with OpenPGP systems and need a
// maintained package, consider github.com/ProtonMail/go-crypto/openpgp, which
// is a maintained fork that aims to be a drop-in replacement for this package.
package errors
import (
+1 -1
View File
@@ -51,7 +51,7 @@ func TestOpaqueParseReason(t *testing.T) {
const expectedBad = 3
// Test post-conditions, make sure we actually parsed packets as expected.
if badPackets != expectedBad {
t.Errorf("unexpected # unparseable packets: %d (want %d)", badPackets, expectedBad)
t.Errorf("unexpected # unparsable packets: %d (want %d)", badPackets, expectedBad)
}
if uid == nil {
t.Errorf("failed to find expected UID in unsupported keyring")
+6 -5
View File
@@ -5,11 +5,12 @@
// Package packet implements parsing and serialization of OpenPGP packets, as
// specified in RFC 4880.
//
// Deprecated: this package is unmaintained except for security fixes. New
// applications should consider a more focused, modern alternative to OpenPGP
// for their specific task. If you are required to interoperate with OpenPGP
// systems and need a maintained package, consider a community fork.
// See https://golang.org/issue/44226.
// Deprecated: this package is unsafe by design, and has numerous known security
// issues. It is not maintained, and should not be used. New applications should
// consider a more focused, modern alternative to OpenPGP for their specific
// task. If you are required to interoperate with OpenPGP systems and need a
// maintained package, consider github.com/ProtonMail/go-crypto/openpgp, which
// is a maintained fork that aims to be a drop-in replacement for this package.
package packet
import (
+6 -5
View File
@@ -4,11 +4,12 @@
// Package openpgp implements high level operations on OpenPGP messages.
//
// Deprecated: this package is unmaintained except for security fixes. New
// applications should consider a more focused, modern alternative to OpenPGP
// for their specific task. If you are required to interoperate with OpenPGP
// systems and need a maintained package, consider a community fork.
// See https://golang.org/issue/44226.
// Deprecated: this package is unsafe by design, and has numerous known security
// issues. It is not maintained, and should not be used. New applications should
// consider a more focused, modern alternative to OpenPGP for their specific
// task. If you are required to interoperate with OpenPGP systems and need a
// maintained package, consider github.com/ProtonMail/go-crypto/openpgp, which
// is a maintained fork that aims to be a drop-in replacement for this package.
package openpgp
import (
+7 -6
View File
@@ -5,11 +5,12 @@
// Package s2k implements the various OpenPGP string-to-key transforms as
// specified in RFC 4800 section 3.7.1.
//
// Deprecated: this package is unmaintained except for security fixes. New
// applications should consider a more focused, modern alternative to OpenPGP
// for their specific task. If you are required to interoperate with OpenPGP
// systems and need a maintained package, consider a community fork.
// See https://golang.org/issue/44226.
// Deprecated: this package is unsafe by design, and has numerous known security
// issues. It is not maintained, and should not be used. New applications should
// consider a more focused, modern alternative to OpenPGP for their specific
// task. If you are required to interoperate with OpenPGP systems and need a
// maintained package, consider github.com/ProtonMail/go-crypto/openpgp, which
// is a maintained fork that aims to be a drop-in replacement for this package.
package s2k
import (
@@ -53,7 +54,7 @@ func (c *Config) hash() crypto.Hash {
func (c *Config) encodedCount() uint8 {
if c == nil || c.S2KCount == 0 {
return 96 // The common case. Correspoding to 65536
return 96 // The common case. Corresponding to 65536
}
i := c.S2KCount
+4
View File
@@ -8,6 +8,10 @@
// The version of OTR implemented by this package has been deprecated
// (https://bugs.otr.im/lib/libotr/issues/140). An implementation of OTRv3 is
// available at https://github.com/coyim/otr3.
//
// The otr package is [frozen] and is not accepting new features.
//
// [frozen]: https://go.dev/wiki/Frozen
package otr
import (
+3 -3
View File
@@ -75,8 +75,8 @@ const libOTRPrivateKey = `(privkeys
(account
(name "foo@example.com")
(protocol prpl-jabber)
(private-key
(dsa
(private-key
(dsa
(p #00FC07ABCF0DC916AFF6E9AE47BEF60C7AB9B4D6B2469E436630E36F8A489BE812486A09F30B71224508654940A835301ACC525A4FF133FC152CC53DCC59D65C30A54F1993FE13FE63E5823D4C746DB21B90F9B9C00B49EC7404AB1D929BA7FBA12F2E45C6E0A651689750E8528AB8C031D3561FECEE72EBB4A090D450A9B7A857#)
(q #00997BD266EF7B1F60A5C23F3A741F2AEFD07A2081#)
(g #535E360E8A95EBA46A4F7DE50AD6E9B2A6DB785A66B64EB9F20338D2A3E8FB0E94725848F1AA6CC567CB83A1CC517EC806F2E92EAE71457E80B2210A189B91250779434B41FC8A8873F6DB94BEA7D177F5D59E7E114EE10A49CFD9CEF88AE43387023B672927BA74B04EB6BBB5E57597766A2F9CE3857D7ACE3E1E3BC1FC6F26#)
@@ -402,7 +402,7 @@ func TestAgainstLibOTR(t *testing.T) {
// This test requires otr.c.test to be built as /tmp/a.out.
// If enabled, this tests runs forever performing OTR handshakes in a
// loop.
return
t.Skip("This test requires otr.c.test to be built as /tmp/a.out")
alicePrivateKey, _ := hex.DecodeString(alicePrivateKeyHex)
var alice Conversation
+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},

Some files were not shown because too many files have changed in this diff Show More