Compare commits

...
234 Commits
Author SHA1 Message Date
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
Gopher Robot 8929309228 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I86bc4657bf10e469231536cff39cbdb86c1135c7
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/640455
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: David Chase <drchase@google.com>
2025-01-06 06:44:30 -08:00
cuishuang 4a75ba54c2 all: make function and struct comments match the names
Change-Id: Iba9c1fc2895adca0d3455f8068b040d0ca006408
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/639575
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>
Auto-Submit: Ian Lance Taylor <iant@google.com>
2025-01-02 08:15:46 -08:00
Roland Shoemaker b4f1988a35 ssh: make the public key cache a 1-entry FIFO cache
Users of the the ssh package seem to extremely commonly misuse the
PublicKeyCallback API, assuming that the key passed in the last call
before a connection is established is the key used for authentication.
Some users then make authorization decisions based on this key. This
property is not documented, and may not be correct, due to the caching
behavior of the package, resulting in users making incorrect
authorization decisions about the connection.

This change makes the cache a one entry FIFO cache, making the assumed
property, that the last call to PublicKeyCallback represents the key
actually used for authentication, actually hold.

Thanks to Damien Tournoud, Patrick Dawkins, Vince Parker, and
Jules Duvivier from the Platform.sh / Upsun engineering team
for reporting this issue.

Fixes golang/go#70779
Fixes CVE-2024-45337

Change-Id: Ife7c7b4045d8b6bcd7e3a417bdfae370c709797f
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/635315
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Damien Neil <dneil@google.com>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-11 09:50:49 -08:00
Roland Shoemaker 7042ebcbe0 openpgp/clearsign: just use rand.Reader in tests
Instead of a convoluted fake rand, it is _basically_ just as fast, and
fixes errors that pop up due to bad entropy.

Fixes golang/go#70682

Change-Id: Ib0f605398d1092b516b03135f602c644be2a060f
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/633655
Reviewed-by: Tatiana Bradley <tatianabradley@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Roland Shoemaker <roland@golang.org>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
2024-12-04 19:36:17 +00:00
Gopher Robot 3e90321ac7 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I580d412fc4a135696d4054f8007593cfa4f64224
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/633480
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: Gopher Robot <gobot@golang.org>
2024-12-04 16:35:48 +00:00
Gopher Robot 8c4e668694 x509roots/fallback: update bundle
This is an automated CL which updates the NSS root bundle.

Change-Id: Ic5267bf9d66b676e1cfc5fc2ae153afb8f33b29c
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/631635
Auto-Submit: Gopher Robot <gobot@golang.org>
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>
2024-11-27 18:44:53 +00:00
Gopher Robot 6018723c74 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: Ib4976eb0b062bcd71c208afc9ff53e8c3068fbf9
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/626377
Reviewed-by: David Chase <drchase@google.com>
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>
2024-11-07 22:54:53 +00:00
Ian Lance Taylor 71ed71b4fa README: don't recommend go get
These days people will just import the packages and the go tool will
do the right thing. We don't need to explain it.

Add a pointer to the git repo, though.

For golang/go#62645

Change-Id: I8b1e4a877bd83fe6891688a44d27a6c7902c8979
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/624155
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Commit-Queue: Ian Lance Taylor <iant@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2024-11-04 00:10:25 +00:00
Filippo Valsorda 750a45fe5e sha3: add MarshalBinary, AppendBinary, and UnmarshalBinary
Fixes golang/go#24617

Change-Id: I1d9d529950aa8a5953435e8d3412cda44b075d55
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/616635
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: Michael Pratt <mpratt@google.com>
2024-10-22 19:51:02 +00:00
Filippo Valsorda 36b172546b sha3: avoid trailing permutation
If you read a multiple of the rate, and then stop, there is no point in
running the final permutation.

Change-Id: Ic95e70f78b6e139aca1d3e3c11e09d2bbcf54f6c
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/620555
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>
Reviewed-by: Michael Pratt <mpratt@google.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
2024-10-22 19:50:23 +00:00
Filippo Valsorda 80ea76eb17 sha3: fix padding for long cSHAKE parameters
We used to compute the incorrect value if len(initBlock) % rate == 0.

Also, add a test vector for golang/go#66232, confirmed to fail on
GOARCH=386 without CL 570876.

Fixes golang/go#69169

Change-Id: I3f2400926fca111dd0ca1327d6b5975e51b28f96
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/616576
Reviewed-by: Andrew Ekstedt <andrew.ekstedt@gmail.com>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: Michael Pratt <mpratt@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2024-10-22 19:50:19 +00:00
Filippo Valsorda c17aa50fbd sha3: avoid buffer copy
Previously, the package worked by copying the input (or the output) into
a buffer, and then XOR'ing (or copying) it into (or out of) the state.
(Except for an input fast path.) There's no need for that! We can XOR
straight into the state, and copy straight out of it, at least on little
endian machines. This is a bit faster, almost halves the state size, and
will make it easier to implement marshaling, but most importantly look
at how much simpler it makes the code!

go: go1.23.0
goos: linux
goarch: amd64
pkg: golang.org/x/crypto/sha3
cpu: AMD Ryzen 7 PRO 8700GE w/ Radeon 780M Graphics
                      │ v0.27.0-2-g42ee18b9637 │    v0.27.0-2-g42ee18b9637-dirty    │
                      │         sec/op         │   sec/op     vs base               │
PermutationFunction-8              270.8n ± 0%   270.4n ± 0%       ~ (p=0.099 n=10)
Sha3_512_MTU-8                     5.762µ ± 0%   5.658µ ± 0%  -1.80% (p=0.000 n=10)
Sha3_384_MTU-8                     4.179µ ± 0%   4.070µ ± 0%  -2.60% (p=0.000 n=10)
Sha3_256_MTU-8                     3.316µ ± 0%   3.214µ ± 0%  -3.08% (p=0.000 n=10)
Sha3_224_MTU-8                     3.175µ ± 0%   3.061µ ± 0%  -3.61% (p=0.000 n=10)
Shake128_MTU-8                     2.779µ ± 0%   2.681µ ± 0%  -3.51% (p=0.000 n=10)
Shake256_MTU-8                     2.947µ ± 0%   2.957µ ± 0%  +0.32% (p=0.000 n=10)
Shake256_16x-8                     44.15µ ± 0%   44.45µ ± 0%  +0.67% (p=0.000 n=10)
Shake256_1MiB-8                    2.319m ± 0%   2.274m ± 0%  -1.93% (p=0.000 n=10)
Sha3_512_1MiB-8                    4.204m ± 0%   4.219m ± 0%  +0.34% (p=0.000 n=10)
geomean                            13.75µ        13.54µ       -1.55%

                      │ v0.27.0-2-g42ee18b9637 │    v0.27.0-2-g42ee18b9637-dirty     │
                      │          B/s           │     B/s       vs base               │
PermutationFunction-8             704.3Mi ± 0%   705.4Mi ± 0%       ~ (p=0.105 n=10)
Sha3_512_MTU-8                    223.5Mi ± 0%   227.6Mi ± 0%  +1.83% (p=0.000 n=10)
Sha3_384_MTU-8                    308.1Mi ± 0%   316.4Mi ± 0%  +2.67% (p=0.000 n=10)
Sha3_256_MTU-8                    388.2Mi ± 0%   400.5Mi ± 0%  +3.17% (p=0.000 n=10)
Sha3_224_MTU-8                    405.5Mi ± 0%   420.7Mi ± 0%  +3.73% (p=0.000 n=10)
Shake128_MTU-8                    463.4Mi ± 0%   480.2Mi ± 0%  +3.64% (p=0.000 n=10)
Shake256_MTU-8                    436.9Mi ± 0%   435.5Mi ± 0%  -0.32% (p=0.000 n=10)
Shake256_16x-8                    353.9Mi ± 0%   351.5Mi ± 0%  -0.66% (p=0.000 n=10)
Shake256_1MiB-8                   431.2Mi ± 0%   439.7Mi ± 0%  +1.97% (p=0.000 n=10)
Sha3_512_1MiB-8                   237.8Mi ± 0%   237.1Mi ± 0%  -0.33% (p=0.000 n=10)
geomean                           375.7Mi        381.6Mi       +1.57%

Even stronger effect when patched on top of CL 616555 (forced on).

go: go1.23.0
goos: darwin
goarch: arm64
pkg: golang.org/x/crypto/sha3
cpu: Apple M2
                      │    old    │               new                   │
                      │   sec/op  │     sec/op     vs base              │
PermutationFunction-8   154.7n ± 2%   153.8n ± 1%        ~ (p=0.469 n=10)
Sha3_512_MTU-8          3.260µ ± 2%   3.143µ ± 2%   -3.60% (p=0.000 n=10)
Sha3_384_MTU-8          2.389µ ± 2%   2.244µ ± 2%   -6.07% (p=0.000 n=10)
Sha3_256_MTU-8          1.950µ ± 2%   1.758µ ± 1%   -9.87% (p=0.000 n=10)
Sha3_224_MTU-8          1.874µ ± 2%   1.686µ ± 1%  -10.06% (p=0.000 n=10)
Shake128_MTU-8          1.827µ ± 3%   1.447µ ± 1%  -20.80% (p=0.000 n=10)
Shake256_MTU-8          1.665µ ± 3%   1.604µ ± 3%   -3.63% (p=0.003 n=10)
Shake256_16x-8          25.14µ ± 1%   25.23µ ± 2%        ~ (p=0.912 n=10)
Shake256_1MiB-8         1.236m ± 2%   1.243m ± 2%        ~ (p=0.631 n=10)
Sha3_512_1MiB-8         2.296m ± 2%   2.305m ± 1%        ~ (p=0.315 n=10)
geomean                 7.906µ        7.467µ        -5.56%

                      │    old    │               new                   │
                      │    B/op   │      B/op      vs base              │
PermutationFunction-8   1.204Gi ± 2%   1.212Gi ± 1%        ~ (p=0.529 n=10)
Sha3_512_MTU-8          394.9Mi ± 2%   409.7Mi ± 2%   +3.73% (p=0.000 n=10)
Sha3_384_MTU-8          539.0Mi ± 2%   573.8Mi ± 2%   +6.45% (p=0.000 n=10)
Sha3_256_MTU-8          660.3Mi ± 2%   732.6Mi ± 1%  +10.95% (p=0.000 n=10)
Sha3_224_MTU-8          687.1Mi ± 2%   763.9Mi ± 1%  +11.17% (p=0.000 n=10)
Shake128_MTU-8          704.7Mi ± 2%   889.6Mi ± 2%  +26.24% (p=0.000 n=10)
Shake256_MTU-8          773.4Mi ± 3%   802.5Mi ± 3%   +3.76% (p=0.004 n=10)
Shake256_16x-8          621.6Mi ± 1%   619.3Mi ± 2%        ~ (p=0.912 n=10)
Shake256_1MiB-8         809.1Mi ± 2%   804.7Mi ± 2%        ~ (p=0.631 n=10)
Sha3_512_1MiB-8         435.6Mi ± 2%   433.9Mi ± 1%        ~ (p=0.315 n=10)
geomean                 653.6Mi        692.0Mi        +5.88%

Change-Id: I33a0a1ddf305c395f99bf17f81473e2f42c5ce42
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/616575
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
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>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Andrew Ekstedt <andrew.ekstedt@gmail.com>
2024-10-21 19:02:20 +00:00
samiponkanen 7cfb9161e8 ssh: return unexpected msg error when server fails keyboard-interactive auth early
Seems the OpenSSH server running on windows fails keyboard-interactive
auth this way without sending any prompt to client. In such case the
golang ssh client should not retry keyboard-interactive auth when the
auth method is wrapped in a RetryableAuthMethod(). Rather the auth
method should be immediately marked as tried&failed and the client auth
process should move on to next available and acceptable auth method.

Fixes golang/go#67855

Change-Id: I6c64ae58ff8325774e37af716601b112f8833d8f
GitHub-Last-Rev: 7fafc4d1c81284b31000d7d6ccadd934dda26d24
GitHub-Pull-Request: golang/crypto#297
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/590956
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
2024-10-16 07:16:19 +00:00
Paul E. Murphy b61b08db44 chacha20: extend ppc64le support to ppc64
This requires fixing an incorrect save of the counter. It is a word
value. It happens to work on LE because length is limited to u32.

Refactor the constant table to load correctly independent of byte
ordering.

Add byte order swapping where output needs converted to LE
ordering for storage.

Change-Id: Ic7e09bd1c769bb77dd6e817f5a8639ba765f4c0f
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/614297
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
Reviewed-by: Archana Ravindar <aravinda@redhat.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-10-11 17:09:09 +00:00
Paul E. Murphy 6c21748958 internal/poly1305: extend ppc64le support to ppc64
The cipher needs to load the stream in LE order. Use the byte
reversing loads on BE.

Also, remove the unused variable poly1305Mask in the PPC64
asm file too.

Change-Id: Ie90fe7bb0ea7a3bcb76583e0cf9c1e4133499541
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/614298
Reviewed-by: Michael Knyszek <mknyszek@google.com>
Reviewed-by: Archana Ravindar <aravinda@redhat.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: David Chase <drchase@google.com>
2024-10-04 20:59:56 +00:00
Gopher Robot adef4cc1a8 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: Id321d3b5909ecb66c0311ba86008509c7895863b
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/617958
Auto-Submit: Gopher Robot <gobot@golang.org>
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>
2024-10-04 15:35:24 +00:00
Yawning Angel a0819fbb02 sha3: fix cSHAKE initialization for extremely large N and or S
While both impractical and unlikely, the multiplication could overflow
on 32-bit architectures.

The 64-bit architecture case is unaffected by both the maximum length
of Go slices being too small to trigger the overflow (everything except
s390), and it being safe to assume no machine has more than 2 EiB of
memory.

Fixes golang/go#66232

Change-Id: I19c15d42d2d6af35e296697159d43d02f513e614
GitHub-Last-Rev: 503e180debfdc93ab99977172af2b64290cb80e8
GitHub-Pull-Request: golang/crypto#286
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/570876
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
2024-09-30 15:41:13 +00:00
Nicola Murino 42ee18b963 ssh: return ServerAuthError after too many auth failures
if a client is disconnected due to too many authentication attempts
we should return a ServerAuthError instead of a generic error.

Some users check the error returned by NewServerConn to determine
whether or not a client attempted to authenticate.

Fixes golang/go#69191

Change-Id: If68fcecdefd6c810fe9df8256b1216e320d8a916
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/566398
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Tim King <taking@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: Carlos Amedee <carlos@golang.org>
2024-09-16 20:42:53 +00:00
cuishuang 9e92970a1e bn256: add missing symbols in comment
Change-Id: Ibd48a070bd8ce35ef5795a8b73bc4ecac43a993e
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/611735
Run-TryBot: shuang cui <imcusg@gmail.com>
Commit-Queue: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@google.com>
2024-09-10 20:43:33 +00:00
Dmitri Shuralyov c9da6b9a40 all: fix printf(var) mistakes detected by latest printf checker
These were problematic but previously easy to miss. They're now
easy to spot thanks to build failures at Go tip as of CL 610736.

For golang/go#68796.

Change-Id: I167f2cce2376b4070460389c673d973e4521d3dc
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/610797
Auto-Submit: 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>
Reviewed-by: Alan Donovan <adonovan@google.com>
2024-09-04 21:26:08 +00:00
Gopher Robot b35ab4fde0 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I94bb1c6a4bb08aff8c146e84a9d4b3e353f098c2
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/610638
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>
2024-09-04 20:46:08 +00:00
Garrett Bodley bcb0f91bbc internal/poly1305: Port sum_amd64.s to Avo
This implementation utilizes the same registers found in the reference
implementation, aiming to produce a minimal semantic diff between the
Avo-generated output and the original hand-written assembly.

To verify the Avo implementation, the reference and Avo-generated
assembly files are fed to `go tool asm`, capturing the debug output into
corresponding temp files. The debug output contains supplementary
metadata (line numbers, instruction offsets, and source file references)
that must be removed in order to obtain a semantic diff of the two
files. This is accomplished via a small utility script written in awk.

Commands used to verify Avo output:

GOROOT=$(go env GOROOT)
ASM_PATH="internal/poly1305/sum_amd64.s"
REFERENCE="b2d3a6a4b4d36521cd7f653879cf6981e7c5c340"

go tool asm -o /dev/null -I "$GOROOT"/src/runtime -debug \
  <(git cat-file -p "$REFERENCE:$ASM_PATH") \
  > /tmp/reference.s

go tool asm -o /dev/null -I "$GOROOT"/src/runtime -debug \
  "$ASM_PATH" \
  > /tmp/avo.s

normalize(){
  awk '{
    $1=$2=$3="";
    print substr($0,4)
  }'
}

diff <(normalize < /tmp/reference.s) <(normalize < /tmp/avo.s)

Change-Id: I80212c95d1b05335d7f6b73a3030b6f812f6105b
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/600035
Reviewed-by: Roland Shoemaker <roland@golang.org>
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>
2024-09-04 20:35:25 +00:00
Garrett Bodley 7eace71069 chacha20poly1305: Avo port of chacha20poly1305_amd64.s
This implementation utilizes the same registers found in the reference
implementation, aiming to produce a minimal semantic diff between the
Avo-generated output and the original hand-written assembly.

To verify the Avo implementation, the reference and Avo-generated
assembly files are fed to `go tool asm`, capturing the debug output into
corresponding temp files. The debug output contains supplementary
metadata (line numbers, instruction offsets, and source file references)
that must be removed in order to obtain a semantic diff of the two
files. This is accomplished via a small utility script written in awk.

Parameter metadata not found in the reference assembly file has been
added, leading to a diff on the lines where those symbols are
referenced.

Commands used to verify Avo output:

GOROOT=$(go env GOROOT)
ASM_PATH="chacha20poly1305/chacha20poly1305_amd64.s"
REFERENCE="b2d3a6a4b4d36521cd7f653879cf6981e7c5c340"

go tool asm -o /dev/null -I "$GOROOT"/src/runtime -debug \
  <(git cat-file -p "$REFERENCE:$ASM_PATH") \
  > /tmp/reference.s

go tool asm -o /dev/null -I "$GOROOT"/src/runtime -debug \
  "$ASM_PATH" \
  > /tmp/avo.s

normalize(){
  awk '{
    $1=$2=$3="";
    print substr($0,4)
  }'
}

diff <(normalize < /tmp/reference.s) <(normalize < /tmp/avo.s)

155,157c155,157
< MOVQ dst(FP), DI
< MOVQ key+24(FP), R8
< MOVQ src+48(FP), SI
---
> MOVQ dst_base(FP), DI
> MOVQ key_base+24(FP), R8
> MOVQ src_base+48(FP), SI
159c159
< MOVQ ad+72(FP), CX
---
> MOVQ ad_base+72(FP), CX
4684,4686c4684,4686
< MOVQ dst(FP), DI
< MOVQ key+24(FP), R8
< MOVQ src+48(FP), SI
---
> MOVQ dst_base(FP), DI
> MOVQ key_base+24(FP), R8
> MOVQ src_base+48(FP), SI
4688c4688
< MOVQ ad+72(FP), CX
---
> MOVQ ad_base+72(FP), CX

Change-Id: Ia3a8e70b7440944ee739499c41ddceb70e054ef9
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/601442
Reviewed-by: Filippo Valsorda <filippo@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>
2024-09-04 20:35:14 +00:00
Garrett Bodley 620dfbc770 salsa20/salsa: Port salsa20_amd64.s to Avo
This implementation utilizes the same registers found in the reference
implementation, aiming to produce a minimal semantic diff between the
Avo-generated output and the original hand-written assembly.

To verify the Avo implementation, the reference and Avo-generated
assembly files are fed to `go tool asm`, capturing the debug output into
corresponding temp files. The debug output contains supplementary
metadata (line numbers, instruction offsets, and source file references)
that must be removed in order to obtain a semantic diff of the two
files. This is accomplished via a small utility script written in awk.

Commands used to verify Avo output:

GOROOT=$(go env GOROOT)
REFERENCE="b2d3a6a4b4d36521cd7f653879cf6981e7c5c340"

go tool asm -o /dev/null -I "$GOROOT"/src/runtime -debug \
  <(git cat-file -p "$REFERENCE":salsa20/salsa/salsa20_amd64.s) \
  > /tmp/reference.s

go tool asm -o /dev/null -I "$GOROOT"/src/runtime -debug \
  salsa20/salsa/salsa20_amd64.s \
  > /tmp/avo.s

normalize(){
  awk '{
    $1=$2=$3="";
    print substr($0,4)
  }'
}

diff <(normalize < /tmp/reference.s) <(normalize < /tmp/avo.s)

Change-Id: Ica0bb06f8b074ad566a979d33ddc81d8a38491b1
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/601217
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2024-09-04 20:34:59 +00:00
Garrett Bodley 82942cf1d8 blake2b: port blake2b_amd64.s to Avo
This implementation utilizes the same registers found in the reference
implementation, aiming to produce a minimal semantic diff between the
Avo-generated output and the original hand-written assembly.

To verify the Avo implementation, the reference and Avo-generated
assembly files are fed to `go tool asm`, capturing the debug output into
corresponding temp files. The debug output contains supplementary
metadata (line numbers, instruction offsets, and source file references)
that must be removed in order to obtain a semantic diff of the two
files. This is accomplished via a small utility script written in awk.

Commands used to verify Avo output:

GOROOT=$(go env GOROOT)
ASM_PATH="blake2b/blake2b_amd64.s"
REFERENCE="b2d3a6a4b4d36521cd7f653879cf6981e7c5c340"

go tool asm -o /dev/null -I "$GOROOT"/src/runtime -debug \
  <(git cat-file -p "$REFERENCE:$ASM_PATH") \
  > /tmp/reference.s

go tool asm -o /dev/null -I "$GOROOT"/src/runtime -debug \
  "$ASM_PATH" \
  > /tmp/avo.s

normalize(){
  awk '{
    $1=$2=$3="";
    print substr($0,4)
  }'
}

diff <(normalize < /tmp/reference.s) <(normalize < /tmp/avo.s)

Change-Id: I6dd59fb0b0365674aa5e43b69a57ea60fbcc4ba1
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/600456
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>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
2024-09-04 20:34:46 +00:00
Garrett Bodley 0484c26df7 blake2b: port blake2bAVX2_amd64.s to Avo
This implementation utilizes the same registers found in the reference
implementation, aiming to produce a minimal semantic diff between the
Avo-generated output and the original hand-written assembly.

To verify the Avo implementation, the reference and Avo-generated
assembly files are fed to `go tool asm`, capturing the debug output into
corresponding temp files. The debug output contains supplementary
metadata (line numbers, instruction offsets, and source file references)
that must be removed in order to obtain a semantic diff of the two
files. This is accomplished via a small utility script written in awk.

Commands used to verify Avo output:

GOROOT=$(go env GOROOT)
ASM_PATH="blake2b/blake2bAVX2_amd64.s"
REFERENCE="b2d3a6a4b4d36521cd7f653879cf6981e7c5c340"

go tool asm -o /dev/null -I "$GOROOT"/src/runtime -debug \
  <(git cat-file -p "$REFERENCE:$ASM_PATH") \
  > /tmp/reference.s

go tool asm -o /dev/null -I "$GOROOT"/src/runtime -debug \
  "$ASM_PATH" \
  > /tmp/avo.s

normalize(){
  awk '{
    $1=$2=$3="";
    print substr($0,4)
  }'
}

diff <(normalize < /tmp/reference.s) <(normalize < /tmp/avo.s)

Change-Id: Ia2af1b82c871e26b89bd9a2d9fb187cc49e18341
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/600836
Reviewed-by: Filippo Valsorda <filippo@golang.org>
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>
2024-09-04 20:34:34 +00:00
Garrett Bodley 38ed1bc0ec blake2s: port blake2s_amd64.s to Avo
This implementation utilizes the same registers found in the reference
implementation, aiming to produce a minimal semantic diff between the
Avo-generated output and the original hand-written assembly.

To verify the Avo implementation, the reference and Avo-generated
assembly files are fed to `go tool asm`, capturing the debug output into
corresponding temp files. The debug output contains supplementary
metadata (line numbers, instruction offsets, and source file references)
that must be removed in order to obtain a semantic diff of the two
files. This is accomplished via a small utility script written in awk.

Commands used to verify Avo output:

GOROOT=$(go env GOROOT)
ASM_PATH="blake2s/blake2s_amd64.s"
REFERENCE="b2d3a6a4b4d36521cd7f653879cf6981e7c5c340"

go tool asm -o /dev/null -I "$GOROOT"/src/runtime -debug \
  <(git cat-file -p "$REFERENCE:$ASM_PATH") \
  > /tmp/reference.s

go tool asm -o /dev/null -I "$GOROOT"/src/runtime -debug \
  "$ASM_PATH" \
  > /tmp/avo.s

normalize(){
  awk '{
    $1=$2=$3="";
    print substr($0,4)
  }'
}

diff <(normalize < /tmp/reference.s) <(normalize < /tmp/avo.s)

Change-Id: Ica8bf9f0b42dc93714aa54e783fa74ed19e6b9f4
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/601216
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>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
2024-09-04 20:34:20 +00:00
Garrett Bodley 38a0b5da75 argon2: Avo port of blamka_amd64.s
This implementation utilizes the same registers found in the reference
implementation, aiming to produce a minimal semantic diff between the
Avo-generated output and the original hand-written assembly.

To verify the Avo implementation, the reference and Avo-generated
assembly files are fed to `go tool asm`, capturing the debug output into
corresponding temp files. The debug output contains supplementary
metadata (line numbers, instruction offsets, and source file references)
that must be removed in order to obtain a semantic diff of the two
files. This is accomplished via a small utility script written in awk.

Commands used to verify Avo output:

GOROOT=$(go env GOROOT)
ASM_PATH="argon2/blamka_amd64.s"
REFERENCE="b2d3a6a4b4d36521cd7f653879cf6981e7c5c340"

go tool asm -o /dev/null -I "$GOROOT"/src/runtime -debug \
  <(git cat-file -p "$REFERENCE:$ASM_PATH") \
  > /tmp/reference.s

go tool asm -o /dev/null -I "$GOROOT"/src/runtime -debug \
  "$ASM_PATH" \
  > /tmp/avo.s

normalize(){
  awk '{
    $1=$2=$3="";
    print substr($0,4)
  }'
}

diff <(normalize < /tmp/reference.s) <(normalize < /tmp/avo.s)

Change-Id: I3567eb80ef80dff248225f17470122c0a4e6951e
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/600315
Reviewed-by: Filippo Valsorda <filippo@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>
2024-09-04 20:33:49 +00:00
Gopher Robot bf5f14f545 x509roots/fallback: update bundle
This is an automated CL which updates the NSS root bundle.

Change-Id: I95cf0b3e86f1e013d486a0bbd050a8b4bea5d6e9
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/610060
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>
2024-09-03 18:00:24 +00:00
Nicola Murino b2d3a6a4b4 ssh/agent: ensure to not add duplicated keys
When adding a new key, if we already have a Signer with the same public
key, we now replace it with the new one instead of duplicating it.

Before this change we had this:

$ ssh-add -l
3072 SHA256:bsBRHC/xgiqBJdSuvSTNpJNLTISP/G356jNMCRYC5Es nicola@p1 (RSA)
3072 SHA256:bsBRHC/xgiqBJdSuvSTNpJNLTISP/G356jNMCRYC5Es nicola@p1 (RSA-CERT)

$ ssh-add /home/nicola/ssh_certs/id_rsa
Identity added: /home/nicola/ssh_certs/id_rsa (nicola@p1)
Certificate added: /home/nicola/ssh_certs/id_rsa-cert.pub (myid)

$ ssh-add -l
3072 SHA256:bsBRHC/xgiqBJdSuvSTNpJNLTISP/G356jNMCRYC5Es nicola@p1 (RSA)
3072 SHA256:bsBRHC/xgiqBJdSuvSTNpJNLTISP/G356jNMCRYC5Es nicola@p1 (RSA-CERT)
3072 SHA256:bsBRHC/xgiqBJdSuvSTNpJNLTISP/G356jNMCRYC5Es nicola@p1 (RSA)
3072 SHA256:bsBRHC/xgiqBJdSuvSTNpJNLTISP/G356jNMCRYC5Es nicola@p1 (RSA-CERT)

Change-Id: Iad1b1a6dc94f68f53f05d7d1172f0017839976fc
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/602955
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-08-06 16:07:48 +00:00
Gopher Robot 5bcd010f1c go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: Iae75e5fcbcfe3709820dd66638a763f662f8d939
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/603396
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>
2024-08-06 15:38:17 +00:00
Ilia Mirkin 3375612bf4 ssh: add support for unpadded RSA signatures
The original SSH RFC 4253 explicitly disallows padding. This applies to
ssh-rsa signatures.

The updated SSH RFC 8332 which defines the SHA2 RSA signature variants
explicitly calls out the existence of signers who produce short
signatures and specifies that verifiers may allow this behavior.

In practice, PuTTY 0.81 and prior versions, as well as SSH.NET prior to
2024.1.0 always generated short signatures. Furthermore, PuTTY is
embedded in other software like WinSCP and FileZilla, which are updated
on their own schedules as well. This leads to occasional unexplained
login errors, when using RSA keys.

OpenSSH server allows these short signatures for all RSA algorithms.

Fixes golang/go#68286

Change-Id: Ia60ece21bf9c111c490fac0c066443ed5ff7dd29
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/598534
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
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>
2024-07-26 16:39:19 +00:00
Nicola Murino bb80217080 ssh: don't use dsa keys in integration tests
DSA has been disabled by default since OpenSSH 9.8, so tests
fail with newer versions of OpenSSH

Change-Id: I57b9abde8845cd05116a637a21cbbb8af740b2e0
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/599955
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: Roland Shoemaker <roland@golang.org>
2024-07-22 17:35:33 +00:00
Ilia Mirkin 6879722274 ssh: remove go 1.21+ dependency on slices
Fixes golang/go#68469

Change-Id: Ieea3c444b0458d169a6ff224e59b3b815264de89
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/598775
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
2024-07-17 17:59:23 +00:00
Garrett Bodley e983fa2741 sha3: Avo port of keccakf_amd64.s
This implementation utilizes the same registers found in the reference
implementation, aiming to produce a minimal semantic diff between the
Avo-generated output and the original hand-written assembly.

To verify the Avo implementation, the reference and Avo-generated
assembly files are fed to `go tool asm`, capturing the debug output into
corresponding temp files. The debug output contains supplementary
metadata (line numbers, instruction offsets, and source file references)
that must be removed in order to obtain a semantic diff of the two
files. This is accomplished via a small utility script written in awk.

Commands used to verify Avo output:

BASE="d66d9c31b4ae80d173d1187a9e40c188788dbdbc"
go tool asm -o /dev/null -debug \
  <(git cat-file -p "$BASE":sha3/keccakf_amd64.s) \
  > /tmp/reference.s

go tool asm -o /dev/null -debug \
  sha3/keccakf_amd64.s \
  > /tmp/avo.s

normalize(){
  awk '{
    $1=$2=$3="";
    print substr($0,4)
  }'
}

diff <(normalize < /tmp/reference.s) <(normalize < /tmp/avo.s)

Change-Id: I1c0ea516531355263b83d3b66a37df090e293cea
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/594655
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Russell Webb <russell.webb@protonmail.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
2024-07-16 18:24:57 +00:00
Russ Cox 80fd97208d LICENSE: update per Google Legal
Very minor tweaks:
 - Remove (c) pseudosymbol.
 - Remove "All Rights Reserved."
 - Change "Google Inc." (no longer exists) to "Google LLC".

[git-generate]
echo '
,s/\(c\) //
,s/ All rights reserved.//
,s/Google Inc./Google LLC/
w
q
' | sam -d LICENSE

Change-Id: I6e885650c5701597f57dbf00c2abdcc7b393a703
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/598520
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Russ Cox <rsc@golang.org>
2024-07-16 16:09:32 +00:00
Dmitri Shuralyov f2bc3a617a x509roots/fallback/internal/goissue52287: delete
By now Go 1.19 isn't supported, so there's no need to work around
go.dev/issue/52287 in this module anymore.

For golang/go#57792.
For golang/go#52287.

Change-Id: I3999cdb9ca419a2ab897c9143a4ec31f59da7d80
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/598495
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Dmitri Shuralyov <dmitshur@golang.org>
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>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2024-07-16 15:06:23 +00:00
Gopher Robot d66d9c31b4 x509roots/fallback: update bundle
This is an automated CL which updates the NSS root bundle.

Change-Id: I552ff9800e32294b25cc04ccc8fca3404ae3b93c
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/597095
Auto-Submit: Gopher Robot <gobot@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2024-07-09 15:54:00 +00:00
Gopher Robot 9fadb0b165 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I0024d2803498fe98af80f14a4476a504c9aa6b5b
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/596835
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Than McIntosh <thanm@google.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
2024-07-05 10:46:52 +00:00
Filippo Valsorda a6a393ffd6 all: bump go.mod version and drop compatibility shims
Also, remove the legacy import annotations.

Fixes golang/go#68147

Change-Id: Ibfcc9322f27224c0ba92ea42cd56912a7d8783fd
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/594256
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2024-06-26 15:12:35 +00:00
cuishuang 1c7450041f ssh/test: make struct comment match struct name
Change-Id: I9bfd61fe96d2bdaa890379a1a31b7e0f3f2b67ed
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/594435
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Run-TryBot: shuang cui <imcusg@gmail.com>
Reviewed-by: Joedian Reid <joedian@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2024-06-24 16:35:32 +00:00
samiponkanen d4e7c9cb6c ssh: fail client auth immediately on receiving disconnect message
Fixes golang/go#66991

Change-Id: I60dd8a807578f162fda0e49bcd6fbf289d444396
GitHub-Last-Rev: f88329d35712873d0d7e3b39b9b11e7bfbc28e71
GitHub-Pull-Request: golang/crypto#293
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/581075
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-06-04 17:03:48 +00:00
Gopher Robot 332fd656f4 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I105ee0f343768881d4fe3a2bfd1fcbaa7e1fd705
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/590218
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2024-06-04 16:30:12 +00:00
Gopher Robot 0b431c7de3 x509roots/fallback: update bundle
This is an automated CL which updates the NSS root bundle.

Change-Id: I8a1b9637e83214674e6fe82ebf584e9b90446ca3
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/589875
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>
Reviewed-by: Damien Neil <dneil@google.com>
2024-06-03 23:40:54 +00:00
Mariano Cano 349231f7e4 ssh: implement CryptoPublicKey on sk keys
This commit implements the CryptoPublicKey interface for the
skECDSAPublicKey and skEd25519PublicKey types.

Fixes golang/go#62518

Change-Id: I2b8ac89196fbb3614bf5c675127bed23f1cf6b26
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/526875
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
Reviewed-by: Than McIntosh <thanm@google.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
2024-05-29 18:20:30 +00:00
Andrew Lytvynov 44c9b0ff9e ssh: allow server auth callbacks to send additional banners
Add a new BannerError error type that auth callbacks can return to send
banner to the client. While the BannerCallback can send the initial
banner message, auth callbacks might want to communicate more
information to the client to help them diagnose failures.

Updates golang/go#64962

Change-Id: I97a26480ff4064b95a0a26042b0a5e19737cfb62
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/558695
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2024-05-22 20:07:48 +00:00
Mauri de Souza Meneguzzo 67b13616a5 sha3: reenable s390x assembly
Fixes golang/go#64897

Change-Id: I0c8c52d73a7d2df0f44fee36d407a87213f59bff
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/554435
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-05-07 22:33:54 +00:00
Filippo Valsorda 477a5b4c32 sha3: make APIs usable with zero allocations
The "buf points into storage" pattern is nice, but causes the whole
state struct to escape, since escape analysis can't track the pointer
once it's assigned to buf.

Change-Id: I31c0e83f946d66bedb5a180e96ab5d5e936eb322
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/544817
Reviewed-by: Cherry Mui <cherryyz@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Mauri de Souza Meneguzzo <mauri870@gmail.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
2024-05-07 22:04:09 +00:00
Filippo Valsorda 59b5a86796 sha3: disable s390x assembly
It was integrated in such a way that it made devirtualization
impossible, leading to allocations on every platform.

It can be reintroduced according to AssemblyPolicy and TargetSpecific.

Updates #64897

Change-Id: I3a4edc91185c2928b2c9b80655a2bc8daa6b44e3
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/544816
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Mauri de Souza Meneguzzo <mauri870@gmail.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2024-05-07 22:03:33 +00:00
Filippo Valsorda 10f366e7a2 sha3: simplify XOR functions
name                   old time/op   new time/op   delta
PermutationFunction-4    398ns ± 0%    399ns ± 1%    ~     (p=0.508 n=9+10)
Sha3_512_MTU-4          8.34µs ± 1%   8.36µs ± 1%    ~     (p=0.101 n=10+10)
Sha3_384_MTU-4          6.00µs ± 0%   6.02µs ± 1%  +0.47%  (p=0.000 n=8+10)
Sha3_256_MTU-4          4.78µs ± 0%   4.79µs ± 1%    ~     (p=0.324 n=10+10)
Sha3_224_MTU-4          4.57µs ± 1%   4.57µs ± 1%    ~     (p=0.288 n=10+10)
Shake128_MTU-4          3.87µs ± 0%   3.86µs ± 1%  -0.22%  (p=0.008 n=9+9)
Shake256_MTU-4          4.17µs ± 0%   4.17µs ± 0%    ~     (p=0.474 n=10+8)
Shake256_16x-4          59.4µs ± 0%   59.7µs ± 0%  +0.48%  (p=0.000 n=9+8)
Shake256_1MiB-4         3.19ms ± 1%   3.20ms ± 0%    ~     (p=0.105 n=10+10)
Sha3_512_1MiB-4         5.97ms ± 0%   6.01ms ± 0%  +0.75%  (p=0.000 n=10+10)

name                   old speed     new speed     delta
PermutationFunction-4  502MB/s ± 0%  502MB/s ± 0%    ~     (p=0.497 n=9+10)
Sha3_512_MTU-4         162MB/s ± 1%  161MB/s ± 1%    ~     (p=0.101 n=10+10)
Sha3_384_MTU-4         225MB/s ± 0%  224MB/s ± 1%  -0.47%  (p=0.000 n=8+10)
Sha3_256_MTU-4         282MB/s ± 0%  282MB/s ± 1%    ~     (p=0.325 n=10+10)
Sha3_224_MTU-4         296MB/s ± 1%  295MB/s ± 1%    ~     (p=0.280 n=10+10)
Shake128_MTU-4         349MB/s ± 0%  350MB/s ± 1%  +0.22%  (p=0.008 n=9+9)
Shake256_MTU-4         324MB/s ± 0%  324MB/s ± 0%    ~     (p=0.459 n=10+8)
Shake256_16x-4         276MB/s ± 0%  274MB/s ± 0%  -0.48%  (p=0.000 n=9+8)
Shake256_1MiB-4        328MB/s ± 1%  327MB/s ± 0%    ~     (p=0.105 n=10+10)
Sha3_512_1MiB-4        176MB/s ± 0%  174MB/s ± 0%  -0.74%  (p=0.000 n=10+10)

Change-Id: Ib8e571f3c9a0f84096df2f38ca96da197ad5be30
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/544815
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Cherry Mui <cherryyz@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Mauri de Souza Meneguzzo <mauri870@gmail.com>
2024-05-06 15:29:57 +00:00
Gopher Robot 905d78a692 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I19d5fc3e26b53fba06b4fbcf3817c44477265210
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/583355
Auto-Submit: Gopher Robot <gobot@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Than McIntosh <thanm@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2024-05-06 13:42:02 +00:00
Nicola Murino ebb717d630 ssh: validate key type in SSH_MSG_USERAUTH_PK_OK response
According to RFC 4252 Section 7 the algorithm in SSH_MSG_USERAUTH_PK_OK
should match that of the request but some servers send the key type instead.
OpenSSH checks for the key type, so we do the same.

Fixes golang/go#66438
Fixes golang/go#64785
Fixes golang/go#56342
Fixes golang/go#54027

Change-Id: I2f733f0faece097e44ba7a97c868d30a53e21d79
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/573360
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Run-TryBot: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Joedian Reid <joedian@google.com>
2024-05-03 13:40:56 +00:00
cuishuang 0da2a6a1bb openpgp: fix function name in comment
Change-Id: Ic788ebe311fafa0f5d9750d5f7f25fb70dc0606d
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/579175
Run-TryBot: shuang cui <imcusg@gmail.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
TryBot-Result: Gopher Robot <gobot@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: Cherry Mui <cherryyz@google.com>
2024-04-16 17:48:22 +00:00
Michael Munday 5defcc193a sha3: fix Sum results for SHAKE functions on s390x
Sum was taking the digest from the state which is correct for SHA-3
functions but not for SHAKE functions.

Updates golang/go#66804

Change-Id: If782464d773262075950e3168128c0d46e4a6530
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/578715
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Run-TryBot: Michael Munday <mike.munday@lowrisc.org>
2024-04-15 21:53:43 +00:00
Gopher Robot d042a396a6 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: Ib20227810c7e72942dd6fc33731fc613784aedec
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/576515
Reviewed-by: Than McIntosh <thanm@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
2024-04-04 16:59:43 +00:00
Nicola Murino b92bf9480d ssh: respect MaxAuthTries also for "none" auth attempts
Only the first "none" auth attempt is allowed without penality

Change-Id: Ibe776e968ba406445eeb94e8f1959383b88c98f7
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/575995
Reviewed-by: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Commit-Queue: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Than McIntosh <thanm@google.com>
2024-04-04 14:49:27 +00:00
Nicola MurinoandPeter Verraedt 6f79b5a20c ssh: add server side multi-step authentication
Add support for sending back partial success to the client while
handling authentication in the server. This is implemented by a special
error that can be returned by any of the authentication methods, which
contains the authentication methods to offer next.

This patch is based on CL 399075 with some minor changes and the
addition of test cases.

Fixes golang/go#17889
Fixes golang/go#61447
Fixes golang/go#64974

Co-authored-by: Peter Verraedt <peter.verraedt@kuleuven.be>
Change-Id: I05c8f913bb407d22c2e41c4cbe965e36ab4739b0
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/516355
Reviewed-by: Andrew Lytvynov <awly@tailscale.com>
Reviewed-by: Than McIntosh <thanm@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
2024-04-03 07:40:24 +00:00
Jayanth Krishnamurthy 8d0d405eed x/crypto/chacha20: cleanup chacha_ppc64le.s
- Adding PCALIGN before the loops
- Changing WORD directive with corresponding Vector Merge EVEN/ODD word  instructions
- Replacing Branch Conditional (BC) with its extended mnemonic form  BDNZ
- VPERMXOR instruction usage in place of VXOR instructions followed by
  VRLW (rotate left) for cases of rotating in multiples of 8. This
  replacements give performace improvement both in time and space  of around 7%-8% as listed below
  using benchstat tool.

goos: linux
goarch: ppc64le
pkg: golang.org/x/crypto/chacha20
cpu: POWER10
                 | chacha20.prev.out |       chacha20.new.out            |
                 |      sec/op       |   sec/op     vs base              |
ChaCha20/64              171.9n ± 0%   156.6n ± 1%  -8.90% (p=0.002 n=6)
ChaCha20/256             165.5n ± 0%   152.4n ± 0%  -7.92% (p=0.002 n=6)
ChaCha20/10x25           505.8n ± 0%   504.3n ± 2%  -0.32% (p=0.589 n=6)
ChaCha20/4096            2.265µ ± 0%   2.052µ ± 0%  -9.40% (p=0.002 n=6)
ChaCha20/100x40          5.359µ ± 3%   5.018µ ± 2%  -6.37% (p=0.002 n=6)
ChaCha20/65536           35.71µ ± 0%   32.29µ ± 0%  -9.57% (p=0.002 n=6)
ChaCha20/1000x65         44.63µ ± 0%   41.05µ ± 0%  -8.02% (p=0.002 n=6)
geomean                  2.235µ        2.073µ       -7.26%

                 | chacha20.prev.out |          chacha20.new.out         |
                 |       B/s         |     B/s       vs base             |
ChaCha20/64             355.1Mi ± 0%   389.8Mi ± 1%   +9.78% (p=0.002 n=6)
ChaCha20/256            1.440Gi ± 0%   1.565Gi ± 0%   +8.62% (p=0.002 n=6)
ChaCha20/10x25          471.3Mi ± 0%   472.8Mi ± 2%   +0.31% (p=0.589 n=6)
ChaCha20/4096           1.684Gi ± 0%   1.859Gi ± 0%  +10.38% (p=0.002 n=6)
ChaCha20/100x40         711.8Mi ± 3%   760.3Mi ± 2%   +6.80% (p=0.002 n=6)
ChaCha20/65536          1.709Gi ± 0%   1.890Gi ± 0%  +10.59% (p=0.002 n=6)
ChaCha20/1000x65        1.356Gi ± 0%   1.475Gi ± 0%   +8.72% (p=0.002 n=6)
geomean                 957.3Mi        1.008Gi        +7.83%
Change-Id: Ib31cb10a2a11eacdacf0272fbfd887eb5ccd8bcb
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/564797
Reviewed-by: Lynn Boger <laboger@linux.vnet.ibm.com>
Run-TryBot: Paul Murphy <murp@ibm.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Run-TryBot: Lynn Boger <laboger@linux.vnet.ibm.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2024-03-26 21:57:38 +00:00
cui fliter b91329d961 all: remove redundant words in comments and fix some typos
Change-Id: I3078492dc020770aca630e0b362df0212bd41e32
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/569156
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-03-18 09:27:23 +00:00
Gopher Robot 7067223927 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I54256afe881714f60fc37c471cd65b060090d9d6
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/568816
Reviewed-by: Than McIntosh <thanm@google.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
2024-03-04 18:29:30 +00:00
Nicola Murino 0d2316b267 ssh/test: work around for TestCiphers failures on macOS
TestCiphers is already skipped on macOS when testing data received
from the server, so move the test for sending data after the
receiving one to work around this new integration test failure.

Fixes golang/go#65732

Change-Id: Ie0c614c5373735ae8aefdd7ded643579b130f4b3
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/564457
Reviewed-by: Bryan Mills <bcmills@google.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Commit-Queue: Nicola Murino <nicola.murino@gmail.com>
2024-02-28 20:47:20 +00:00
Roland Shoemaker 0aab8d07ae all: update go.mod x/net dependency
Not necessary for anything, but need to test something harmless.

Change-Id: I4faa64ef2c8f1f14df5ccaa37836fc56beed4f50
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/566917
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: Roland Shoemaker <roland@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
2024-02-26 19:05:04 +00:00
Brad Fitzpatrick 5bead598a0 ocsp: don't use iota for externally defined constants
Style fix: iota shouldn't be used for values that come from RFCs or
things that go over the wire or to disk.

Change-Id: Ib903ec1bce7e71ff81094db3de8d0b71e16f52f3
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/564695
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2024-02-18 02:21:00 +00:00
Lynn Boger 1a865804d5 x/crypto/internal/poly1305: improve sum_ppc64le.s
This contains a few minor improvements to sum_ppc64le.s
which result in up to 10% performance improvement for
some of the benchmarks in this directory.

- ADDZE followed by ADD can be combined into ADDE
- PCALIGN added to the loop
- Eliminate a few unnecessary register moves

goos: linux
goarch: ppc64le
pkg: golang.org/x/crypto/internal/poly1305
cpu: POWER10
                 │ poly.orig.out │              poly.out              │
                 │    sec/op     │   sec/op     vs base               │
64                   40.34n ± 0%   38.13n ± 0%   -5.47% (p=0.002 n=6)
1K                   482.2n ± 0%   444.6n ± 0%   -7.81% (p=0.002 n=6)
2M                   978.4µ ± 0%   879.3µ ± 0%  -10.12% (p=0.002 n=6)
64Unaligned          40.35n ± 0%   38.16n ± 0%   -5.42% (p=0.002 n=6)
1KUnaligned          482.0n ± 0%   444.2n ± 0%   -7.84% (p=0.002 n=6)
2MUnaligned          978.4µ ± 0%   879.4µ ± 0%  -10.12% (p=0.002 n=6)
Write64              32.69n ± 0%   30.71n ± 0%   -6.04% (p=0.002 n=6)
Write1K              472.4n ± 0%   436.5n ± 0%   -7.60% (p=0.002 n=6)
Write2M              978.3µ ± 0%   879.4µ ± 0%  -10.11% (p=0.002 n=6)
Write64Unaligned     32.67n ± 0%   30.71n ± 0%   -6.00% (p=0.002 n=6)
Write1KUnaligned     472.6n ± 0%   436.4n ± 0%   -7.66% (p=0.002 n=6)
Write2MUnaligned     978.5µ ± 0%   879.6µ ± 0%  -10.10% (p=0.002 n=6)
geomean              2.569µ        2.367µ        -7.87%

Change-Id: I63314e7252ef10fb2d157f623c4bc2e31a63ae32
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/558775
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Paul Murphy <murp@ibm.com>
Run-TryBot: Lynn Boger <laboger@linux.vnet.ibm.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Than McIntosh <thanm@google.com>
2024-02-15 13:30:21 +00:00
Nicola Murino 1c981e6f81 ssh/test: don't use DSA keys in integrations tests, update test RSA key
on RHEL 9 OpenSSH does not support DSA keys and RSA keys with size less
than 2048 bits, furthermore signing with ssh-rsa (SHA-1 signatures) and
ssh-dss is not allowed, therefore:

1) replaced the 1024-bit RSA key used in the test with a new 2048-bit
   one
2) removed DSA key from itegration tests
3) allowed signature errors using ssh-rsa in agent integration tests, we
   also check SHA-2 variants that are not skipped

Fixes golang/go#65581

Change-Id: I54bf997b61ef4d91d38eb624275737ba7291bb20
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/562755
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: David Chase <drchase@google.com>
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>
2024-02-14 13:16:51 +00:00
Roland Shoemaker 62c9f1799c x509roots/nss: manually exclude a confusingly constrained root
Fixes golang/go#61963

Change-Id: I16920d160af74772ef5aa650d1274e07c3ca9adc
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/562475
Reviewed-by: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2024-02-08 16:32:26 +00:00
Gopher Robot 405cb3bdea go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I87d766a485104662172bf983d2a9deb085eddd99
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/562417
Reviewed-by: Than McIntosh <thanm@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>
Reviewed-by: David Chase <drchase@google.com>
2024-02-07 19:12:06 +00:00
Gopher Robot 913d3ae741 x509roots/fallback: update bundle
This is an automated CL which updates the NSS root bundle.

Change-Id: I6d9163026799e5d134f6bb6819e22448d7ebe719
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/561395
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>
2024-02-07 17:47:05 +00:00
Bryan C. Mills dbb6ec16ec ssh/test: skip tests on darwin that fail on the darwin-amd64-longtest LUCI builder
We don't yet understand why these tests fail, but the Apple sshd seems
to have some non-trivial vendor patches, so it is plausibly a
platform-specific bug in the test. Let's skip that failure mode on the
whole platform until/unless someone has time to reproduce and
investigate the failure.

For golang/go#64959.

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: I9e43579469de3fe9329c093b5916bbed0edd3751
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/554077
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@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: Bryan Mills <bcmills@google.com>
2024-01-08 16:44:29 +00:00
Bryan C. Mills 403f69900e ssh/test: avoid leaking a net.UnixConn in server.TryDialWithAddr
For golang/go#64959.

Change-Id: I2153166f4960058cdc2b82ae34ca250dcc6ba1c6
Cq-Include-Trybots: luci.golang.try:x_crypto-gotip-linux-amd64-longtest,x_crypto-gotip-windows-amd64-longtest
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/554062
Run-TryBot: Bryan Mills <bcmills@google.com>
Auto-Submit: Bryan Mills <bcmills@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
TryBot-Result: 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>
2024-01-08 16:33:12 +00:00
Gopher Robot 055043dfed go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I2df91d0602cd1ef94370de4a60a935edeb441333
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/553996
Reviewed-by: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2024-01-04 15:35:59 +00:00
Sebastiaan van Stijn 08396bb92b internal/poly1305: drop Go 1.12 compatibility
Other packages already dropped compatibility with go1.12, so it should be safe to remove it for this package as well.

Change-Id: Ieecc7cd06a0a4e69e8c1c09ef6fefe95d78ceb75
GitHub-Last-Rev: 1971e0309bdd31facbc60d70cd36a91f6a22f4b2
GitHub-Pull-Request: golang/crypto#239
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/448239
Reviewed-by: Joedian Reid <joedian@google.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2024-01-02 20:57:09 +00:00
Roland Shoemaker 9d2ee975ef ssh: implement strict KEX protocol changes
Implement the "strict KEX" protocol changes, as described in section
1.9 of the OpenSSH PROTOCOL file (as of OpenSSH version 9.6/9.6p1).

Namely this makes the following changes:
  * Both the server and the client add an additional algorithm to the
    initial KEXINIT message, indicating support for the strict KEX mode.
  * When one side of the connection sees the strict KEX extension
    algorithm, the strict KEX mode is enabled for messages originating
    from the other side of the connection. If the sequence number for
    the side which requested the extension is not 1 (indicating that it
    has already received non-KEXINIT packets), the connection is
    terminated.
  * When strict kex mode is enabled, unexpected messages during the
    handshake are considered fatal. Additionally when a key change
    occurs (on the receipt of the NEWKEYS message) the message sequence
    numbers are reset.

Thanks to Fabian Bäumer, Marcus Brinkmann, and Jörg Schwenk from Ruhr
University Bochum for reporting this issue.

Fixes CVE-2023-48795
Fixes golang/go#64784

Change-Id: I96b53afd2bd2fb94d2b6f2a46a5dacf325357604
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/550715
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Tatiana Bradley <tatianabradley@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: 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>
2023-12-18 16:33:08 +00:00
Edoardo Spadolini 4e5a26183e ssh: close net.Conn on all NewServerConn errors
This PR ensures that the net.Conn passed to ssh.NewServerConn is closed
on all error return paths, not just after a failed handshake. This matches
the behavior of ssh.NewClientConn.

Change-Id: Id8a51d10ae8d575cbbe26f2ef6b37de7cca840ec
GitHub-Last-Rev: 81bb2e58a881a9a85935740bda06b034b32a8ce3
GitHub-Pull-Request: golang/crypto#279
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/549095
Run-TryBot: Nicola Murino <nicola.murino@gmail.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2023-12-14 18:23:28 +00:00
Gopher Robot 152cdb1503 x509roots/fallback: update bundle
This is an automated CL which updates the NSS root bundle.

Change-Id: Ib8c85dc815297de7b59c3e23b0ad029baaf948ec
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/543735
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>
2023-11-29 16:35:42 +00:00
Will Mortensen fdfe1f8531 ssh: defer channel window adjustment
Sending a window adjustment after every read is unnecessarily chatty,
especially with a series of small reads like with TTY interactions.

Copy OpenSSH's logic for deferring these, which seemingly hasn't changed
since 2007. Note that since channelWindowSize and c.maxIncomingPayload
are currently constants here, the two checks could be combined into a
single check for c.myWindow < 2 MiB - 96 KiB (with the current values
of the constants).

Fixes golang/go#57424.

Change-Id: Ifcef5be76fcc3f0b1a6dc396096bed9c50d64f21
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/459915
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
Run-TryBot: Nicola Murino <nicola.murino@gmail.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Commit-Queue: Nicola Murino <nicola.murino@gmail.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2023-11-27 17:27:49 +00:00
Sebastiaan van Stijn b8ffc16e10 blake2b: drop Go 1.6, Go 1.8 compatibility
Other packages already dropped compatibility with go < 1.12, so it
should be safe to remove it for this package as well.

Change-Id: I7e894fd11d2e7d1fe28c647bd921399a9a6e30d0
GitHub-Last-Rev: 2b4f576a19338f185e79f39cbfd476573b986369
GitHub-Pull-Request: golang/crypto#240
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/448240
Run-TryBot: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Joedian Reid <joedian@golang.org>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Commit-Queue: Nicola Murino <nicola.murino@gmail.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2023-11-27 17:26:05 +00:00
Pavel Repin 7e6fbd82c8 ssh: wrap errors from client handshake
When an error is returned by a user defined host key callback,
it is now possible to handle it using standard Go mechanisms
such as errors.Is or errors.As.

Fixes golang/go#61309

Change-Id: I4269c5f8eacd8e7e8d85070ad249f0e27777b15f
GitHub-Last-Rev: d2a34d5c8225d6aaaee287ce3ea8b218fbe210d4
GitHub-Pull-Request: golang/crypto#266
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/508876
Run-TryBot: Nicola Murino <nicola.murino@gmail.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Muhammad Shulhan <m.shulhan@gmail.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2023-11-27 17:24:46 +00:00
Egon Elbre bda2f3f5cf argon2: avoid clobbering BP
go vet was reporting

  blamka_amd64.s:203:1: [amd64] mixBlocksSSE2: invalid offset a+24(FP); expected a+8(FP)
  blamka_amd64.s:226:1: [amd64] xorBlocksSSE2: invalid offset a+24(FP); expected a+8(FP)
  blamka_amd64.s:204:1: frame pointer is clobbered before saving
  blamka_amd64.s:227:1: frame pointer is clobbered before saving

Also fix a similar naming issue in sha3:

  sha3\keccakf_amd64.s:325:1: [amd64] keccakF1600: unknown variable state; offset 0 is a+0(FP)

Updates golang/go#47027

Change-Id: Ia74852cdb0721ae0216787054197b0cac9e1c0f8
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/332289
Reviewed-by: Michael Knyszek <mknyszek@google.com>
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: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
2023-11-27 17:24:02 +00:00
Heschi Kreinick 325b735346 ssh/test: skip TestSSHCLIAuth on Windows
It's failing with a file permissions error:

sign_and_send_pubkey: signing using rsa-sha2-512 SHA256:Anr3LjZK8YVpjrxu79myrW9Hrb/wpcMNpVvTq/RcBm8\r\nBad permissions. Try removing permissions for user: UNKNOWN\\\\UNKNOWN (S-1-15-2-2) on file C:/b/s/w/ir/x/t/TestSSHCLIAuth1586735692/001/rsa.

For golang/go#64403

Change-Id: Iece8eac4a1ac349f9f7a273ac7389315cb96568e
Cq-Include-Trybots: luci.golang.try:x_crypto-gotip-windows-amd64-longtest,x_crypto-go1.21-windows-amd64-longtest,x_crypto-go1.20-windows-amd64-longtest
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/545135
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Auto-Submit: Heschi Kreinick <heschi@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2023-11-27 16:29:38 +00:00
Gopher Robot 1eadac50a5 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: I7fdfe509173c79a63d006b27d674f869a5baa2af
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/545098
Reviewed-by: Heschi Kreinick <heschi@google.com>
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>
2023-11-27 16:00:28 +00:00
Randy Reddig b2d7c26edb ssh: add (*Client).DialContext method
This change adds DialContext to ssh.Client, which opens a TCP-IP
connection tunneled over the SSH connection. This is useful for
proxying network connections, e.g. setting
(net/http.Transport).DialContext.

Fixes golang/go#20288.

Change-Id: I110494c00962424ea803065535ebe2209364ac27
GitHub-Last-Rev: 3176984a71a9a1422702e3a071340ecfff71ff62
GitHub-Pull-Request: golang/crypto#260
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/504735
Run-TryBot: Nicola Murino <nicola.murino@gmail.com>
Run-TryBot: Han-Wen Nienhuys <hanwen@google.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Han-Wen Nienhuys <hanwen@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Commit-Queue: Nicola Murino <nicola.murino@gmail.com>
2023-11-27 15:35:52 +00:00
Nicola Murino 1c17e20020 ssh: fix certificate authentication with OpenSSH 7.2-7.7
OpenSSH 7.2-7.7 advertises support for rsa-sha2-256 and rsa-sha2-512
in the "server-sig-algs" extension but doesn't support these
algorithms for certificate authentication, so if the server rejects
the key try to use the obtained algorithm as if "server-sig-algs" had
not been implemented.

Fixes golang/go#58371

Change-Id: Id49960d3dedd32a21e2c6c2689b1696e05398286
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/510155
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Run-TryBot: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
2023-11-23 17:23:14 +00:00
Sebastiaan van Stijn 270bf2552c curve25519/internal/field/_asm: go mod tidy to fix x/sys version
Relates to CL 540537, which updated the dependency in the main module.

Change-Id: I9a745f4e03b5cf14fa62c4de63363ddf663b19fd
GitHub-Last-Rev: 836c39364e9fe4302bc26efc9dabc47680cb66d2
GitHub-Pull-Request: golang/crypto#277
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/541276
Auto-Submit: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
2023-11-21 20:13:04 +00:00
Matt Dainty 1cf1811d71 ssh: use the correct token from the client
This fixes the case where AcceptSecContext is always called with the
first token sent by the client instead of the most recently sent one.
Previously, despite being being read from the client and unmarshalled,
it was never actually used.

Fixes golang/go#43875

Change-Id: I1967d9a107af03d6778a9437b48e785d61710ee5
GitHub-Last-Rev: 0d58e4d50014fac0a9ea1eef85489172137eb8aa
GitHub-Pull-Request: golang/crypto#176
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/286252
Run-TryBot: Filippo Valsorda <filippo@golang.org>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Run-TryBot: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Than McIntosh <thanm@google.com>
2023-11-11 11:26:14 +00:00
Roland Shoemaker a2edfb5072 cryptobyte: fix ReadOptionalASN1Boolean
ReadOptionalASN1Boolean was completely broken, it would only work when
there were two BOOLEAN fields in a row, with the first being OPTIONAL
(which is itself invalid ASN.1 due to the ambiguity). This fixes it
to properly expect a BOOLEAN wrapped in a context-specific tag, as is
the case for all of the other ReadOptionalASN1* methods, and updates
its doc string.

This is a breaking change as it requires adding the tag field to
properly support context-specific tags. Given the method would
previously not work this seems like a reasonable breakage.

Fixes golang/go#43019

Change-Id: I42398256216c59988e249c90bc7aa668f64df945
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/274242
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Damien Neil <dneil@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Roland Shoemaker <roland@golang.org>
2023-11-09 20:53:37 +00:00
Bryan C. Mills ff15cd57d1 ssh: eliminate some goroutine leaks in tests and examples
This should fix the "Log in goroutine" panic seen in
https://build.golang.org/log/e42bf69fc002113dbccfe602a6c67fd52e8f31df,
as well as a few other related leaks. It also helps to verify that
none of the functions under test deadlock unexpectedly.

See https://go.dev/wiki/CodeReviewComments#goroutine-lifetimes.

Updates golang/go#58901.

Change-Id: Ica943444db381ae1accb80b101ea646e28ebf4f9
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/541095
Auto-Submit: Bryan Mills <bcmills@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: Heschi Kreinick <heschi@google.com>
2023-11-09 17:49:15 +00:00
Nicola Murino eb61739cd9 ssh: allow to configure public key auth algorithms on the server side
Fixes golang/go#61244

Change-Id: I29b43e379cf0cdb07b0d6935666491b997157e73
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/510775
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Bryan Mills <bcmills@google.com>
Commit-Queue: Nicola Murino <nicola.murino@gmail.com>
Run-TryBot: Nicola Murino <nicola.murino@gmail.com>
Auto-Submit: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Han-Wen Nienhuys <hanwen@google.com>
2023-11-08 19:10:19 +00:00
Nicola Murino 42c83fffff ssh: try harder to detect incorrect passwords for legacy PEM encryption
Because of deficiencies in the format, DecryptPEMBlock does not always
detect an incorrect password. In these cases decrypted DER bytes is
random noise. If the parsing of the key returns an asn1.StructuralError
we return x509.IncorrectPasswordError.

Fixes golang/go#62265

Change-Id: Ib8b845f2bd01662c1f1421d35859a32ac5b78da7
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/538835
Reviewed-by: Heschi Kreinick <heschi@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-11-08 18:01:48 +00:00
Gopher Robot e668aa9b45 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: Ie3a6928d78080ff7d75d6813b1760f1317baa081
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/540537
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Heschi Kreinick <heschi@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
2023-11-08 16:51:37 +00:00
Mauri de Souza Meneguzzo df0bc9e1bb chacha20poly1305: guard PSHUFB usage with GOAMD64_v2
The PSHUFB instruction is part of SSE which is only v2+ but it is being
used without the GOAMD64_v2 guard.

The ROL macros were copied from CL 516859 that adds internal/chacha8rand.

Fixes golang/go#63871

Change-Id: I3c8ba75ff284cda4fc788885643246936e617b85
GitHub-Last-Rev: e235e8eae67f16b3a58817cfdff729693faf2665
GitHub-Pull-Request: golang/crypto#275
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/538786
Reviewed-by: Keith Randall <khr@google.com>
Run-TryBot: Mauri de Souza Meneguzzo <mauri870@gmail.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Keith Randall <khr@golang.org>
Reviewed-by: Russ Cox <rsc@golang.org>
2023-11-07 22:36:17 +00:00
Eric Lagergren 74c2ba9521 crypto/hkdf: remove useless call to Reset
HKDF is commonly used to read keys that are the the same length (or
smaller) than the size of the hash digest, which means the loop inside
Read only runs once.

In that case, calling Reset is unnecesssary overhead.

name                  old time/op    new time/op    delta
16ByteMD5Single-8       1.39µs ± 1%    1.22µs ± 0%  -11.95%  (p=0.000 n=10+9)
20ByteSHA1Single-8       826ns ± 0%     746ns ± 0%   -9.70%  (p=0.000 n=9+10)
32ByteSHA256Single-8     838ns ± 1%     744ns ± 0%  -11.29%  (p=0.000 n=10+10)
64ByteSHA512Single-8    5.12µs ± 0%    4.57µs ± 0%  -10.78%  (p=0.000 n=8+10)
8ByteMD5Stream-8         137ns ± 0%     138ns ± 0%   +0.27%  (p=0.009 n=9+6)
16ByteMD5Stream-8        264ns ± 0%     265ns ± 0%   +0.29%  (p=0.000 n=10+10)
8ByteSHA1Stream-8       64.1ns ± 0%    64.4ns ± 0%   +0.60%  (p=0.000 n=9+9)
20ByteSHA1Stream-8       145ns ± 0%     146ns ± 1%   +0.69%  (p=0.000 n=9+10)
8ByteSHA256Stream-8     42.9ns ± 1%    43.1ns ± 0%   +0.48%  (p=0.005 n=10+10)
32ByteSHA256Stream-8     151ns ± 0%     152ns ± 0%   +0.35%  (p=0.006 n=10+8)
8ByteSHA512Stream-8      139ns ± 0%     139ns ± 0%   +0.08%  (p=0.035 n=9+10)
64ByteSHA512Stream-8    1.07µs ± 0%    1.07µs ± 0%   +0.33%  (p=0.000 n=9+10)

name                  old speed      new speed      delta
16ByteMD5Single-8     11.6MB/s ± 0%  13.1MB/s ± 0%  +13.50%  (p=0.000 n=9+9)
20ByteSHA1Single-8    24.2MB/s ± 0%  26.8MB/s ± 0%  +10.75%  (p=0.000 n=9+10)
32ByteSHA256Single-8  38.2MB/s ± 1%  43.0MB/s ± 0%  +12.72%  (p=0.000 n=10+10)
64ByteSHA512Single-8  12.5MB/s ± 0%  14.0MB/s ± 0%  +12.06%  (p=0.000 n=8+10)
8ByteMD5Stream-8      58.2MB/s ± 0%  58.1MB/s ± 0%   -0.27%  (p=0.004 n=9+9)
16ByteMD5Stream-8     60.6MB/s ± 0%  60.5MB/s ± 0%   -0.27%  (p=0.000 n=9+10)
8ByteSHA1Stream-8      125MB/s ± 0%   124MB/s ± 0%   -0.59%  (p=0.000 n=9+9)
20ByteSHA1Stream-8     138MB/s ± 0%   137MB/s ± 1%   -0.69%  (p=0.000 n=9+10)
8ByteSHA256Stream-8    186MB/s ± 1%   185MB/s ± 0%   -0.47%  (p=0.005 n=10+10)
32ByteSHA256Stream-8   211MB/s ± 0%   211MB/s ± 0%   -0.37%  (p=0.003 n=10+8)
8ByteSHA512Stream-8   57.4MB/s ± 1%  57.4MB/s ± 0%     ~     (p=0.137 n=10+10)
64ByteSHA512Stream-8  59.9MB/s ± 0%  59.7MB/s ± 0%   -0.33%  (p=0.000 n=9+10)

name                  old alloc/op   new alloc/op   delta
16ByteMD5Single-8       1.17kB ± 0%    0.98kB ± 0%  -16.42%  (p=0.000 n=10+10)
20ByteSHA1Single-8      1.25kB ± 0%    1.06kB ± 0%  -15.37%  (p=0.000 n=10+10)
32ByteSHA256Single-8    1.36kB ± 0%    1.14kB ± 0%  -16.46%  (p=0.000 n=10+10)
64ByteSHA512Single-8    2.26kB ± 0%    1.84kB ± 0%  -18.43%  (p=0.000 n=10+10)
8ByteMD5Stream-8         2.00B ± 0%     2.00B ± 0%     ~     (all equal)
16ByteMD5Stream-8        5.00B ± 0%     5.00B ± 0%     ~     (all equal)
8ByteSHA1Stream-8        2.00B ± 0%     2.00B ± 0%     ~     (all equal)
20ByteSHA1Stream-8       5.00B ± 0%     5.00B ± 0%     ~     (all equal)
8ByteSHA256Stream-8      1.00B ± 0%     1.00B ± 0%     ~     (all equal)
32ByteSHA256Stream-8     6.00B ± 0%     6.00B ± 0%     ~     (all equal)
8ByteSHA512Stream-8      1.00B ± 0%     1.00B ± 0%     ~     (all equal)
64ByteSHA512Stream-8     9.00B ± 0%     9.00B ± 0%     ~     (all equal)

name                  old allocs/op  new allocs/op  delta
16ByteMD5Single-8         16.0 ± 0%      14.0 ± 0%  -12.50%  (p=0.000 n=10+10)
20ByteSHA1Single-8        16.0 ± 0%      14.0 ± 0%  -12.50%  (p=0.000 n=10+10)
32ByteSHA256Single-8      16.0 ± 0%      14.0 ± 0%  -12.50%  (p=0.000 n=10+10)
64ByteSHA512Single-8      16.0 ± 0%      14.0 ± 0%  -12.50%  (p=0.000 n=10+10)
8ByteMD5Stream-8          0.00           0.00          ~     (all equal)
16ByteMD5Stream-8         1.00 ± 0%      1.00 ± 0%     ~     (all equal)
8ByteSHA1Stream-8         0.00           0.00          ~     (all equal)
20ByteSHA1Stream-8        1.00 ± 0%      1.00 ± 0%     ~     (all equal)
8ByteSHA256Stream-8       0.00           0.00          ~     (all equal)
32ByteSHA256Stream-8      1.00 ± 0%      1.00 ± 0%     ~     (all equal)
8ByteSHA512Stream-8       0.00           0.00          ~     (all equal)
64ByteSHA512Stream-8      1.00 ± 0%      1.00 ± 0%     ~     (all equal)

Change-Id: I08e5deb7045ce9aa63428e0ac7ae6140226414b4
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/423414
Reviewed-by: Roland Shoemaker <roland@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Tatiana Bradley <tatianabradley@google.com>
2023-10-30 15:29:48 +00:00
Nicola Murino cf8dcb0f7d ssh: add test case against ssh CLI
These tests try to ensure better compatibility of our server implementation
with the ssh CLI.

With these tests in place:

1) before merging CL 447757 we would have noticed that our server
   implementation was broken with OpenSSH 8.8+
2) after merging CL 447757 we would have noticed that our server
   implementation was broken with OpenSSH 7.2-7.7

The ssh CLI from $PATH is used by default, but can be overridden using
the SSH_CLI_PATH environment variable.

Change-Id: I93d64be41c7613132b0364afac8397f57c2dcbca
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/506837
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Benny Siegert <bsiegert@gmail.com>
Reviewed-by: Han-Wen Nienhuys <hanwen@google.com>
Run-TryBot: Nicola Murino <nicola.murino@gmail.com>
2023-10-24 07:12:59 +00:00
Roland Shoemaker 4f30245552 x509roots: catch the zero-roots case when generating the bundle
If the parser returns zero roots, don't attempt to completely remove
the bundle. This may happen if, i.e., the HTTP response is 200 but has
no content. An example of this may be http://go.dev/cl/535735.

Change-Id: I81fc2b49c8ec813cca17fd1c807296bfb053d992
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/536136
Reviewed-by: Damien Neil <dneil@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Auto-Submit: Roland Shoemaker <roland@golang.org>
2023-10-23 20:02:03 +00:00
Dmitri Shuralyov 1d57292618 x509roots: check HTTP response status code and media type
The HTTP response status code is expected to be 200 OK, and
the certdata.txt file media type is expected to be plain text.
Check that it is before proceeding with parsing it.

Might help avoid repeats of CL 535735.

Change-Id: I1a7896b3e20d33a23fdc53c572ae9700c9eae1ef
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/536717
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Commit-Queue: Roland Shoemaker <roland@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Roland Shoemaker <roland@golang.org>
2023-10-21 03:02:42 +00:00
Dmitri Shuralyov 8779cbd1c9 all: update go directive to 1.18
Done with:

go get go@1.18
go mod tidy
go fix ./...

Using go1.21.3.

Also update avo to v0.5.0 in the curve25519/internal/field/_asm module.
It's newer and produces no diff in the generated code.

For golang/go#60268.

Change-Id: I9bd771ee8561595d7f68aaca76df6e3e33d35013
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/534141
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Damien Neil <dneil@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2023-10-11 22:02:22 +00:00
Nicola Murino 2aeefc3f8a ssh: add support for SSH_AGENT_CONSTRAIN_EXTENSION with id 255
it was changed in the following draft

https://datatracker.ietf.org/doc/html/draft-miller-ssh-agent-03

The id 3 is now used for SSH_AGENT_CONSTRAIN_MAXSIGN key constraint,
an OpenSSH extension to the protocol that we do not currently support.
Instead, we added a compatibility layer for
SSH_AGENT_CONSTRAIN_EXTENSION with ID 3.

Fixes golang/go#62311

Change-Id: I421aee92aee9e693e43f66e6a5515c055333cb9b
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/525355
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
Run-TryBot: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Than McIntosh <thanm@google.com>
2023-10-11 10:27:03 +00:00
Gopher Robot e3cc52e598 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: Ib80d50bdd762d1ba04f9267aeddc17272ef8cd66
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/532976
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
2023-10-05 15:12:11 +00:00
Nicola Murino 833695f0a5 ssh: add server side support for ping@openssh.com protocol extension
Fixes golang/go#62390

Change-Id: Ie4dc577fb55b45a0c26a9e2dc5903af2bd382e00
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/524775
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
Reviewed-by: Than McIntosh <thanm@google.com>
Run-TryBot: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
2023-10-04 16:04:50 +00:00
Sebastiaan van Stijn ec07f4e35b chacha20: drop Go 1.10 compatibility for arm64
Other packages already dropped compatibility with go < 1.12, so it should be safe to remove it for this package as well.

Change-Id: Ib1424763e3aa94d0187a667ebee058100136f53b
GitHub-Last-Rev: 51df9690a5f37ba50d5ae5e84cf31b78fb6c5cd8
GitHub-Pull-Request: golang/crypto#241
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/448241
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Than McIntosh <thanm@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Roland Shoemaker <roland@golang.org>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Joedian Reid <joedian@golang.org>
2023-09-28 17:58:46 +00:00
Sebastiaan van Stijn b665ba6f6f all: use crypto/ed25519 instead of golang.org/x/crypto/ed25519
This is a follow-up to CL 317169, which dropped go1.12 compatibility,
and made the golang.org/x/crypto/ed25519 package an alias / wrapper for
crypto/ed25519 in stdlib.

This patch updates uses within this repository to use stdlib instead of
depending on the wrapper. With this patch applied, the only remaining
use of the wrapper is in ed25519_test, which appears to be in place to
verify compatibility of the wrapper itself.

Change-Id: I0195396102a75ae20bdd82ca8ab59855c0eb5cea
GitHub-Last-Rev: 24dbec563cbd84bc47bdc7736b0245fc83dd3353
GitHub-Pull-Request: golang/crypto#238
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/448238
Reviewed-by: Bryan Mills <bcmills@google.com>
Run-TryBot: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Joedian Reid <joedian@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Than McIntosh <thanm@google.com>
2023-09-27 14:30:17 +00:00
Nicola Murino a1aeb9b34e ssh: add test cases for compatibility with old (buggy) clients
Improved test cases for CL 506835.

Change-Id: If4a98ae4a7b39d2e59b203d10080b71283e1a80e
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/525735
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
Run-TryBot: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
2023-09-20 18:10:32 +00:00
Nicola Murino 28c53ff63c ssh: add MultiAlgorithmSigner
MultiAlgorithmSigner allows to restrict client-side, server-side and
certificate signing algorithms.

Fixes golang/go#52132
Fixes golang/go#36261

Change-Id: I295092f1bba647327aaaf294f110e9157d294159
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/508398
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Run-TryBot: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2023-09-20 18:10:30 +00:00
Matthew Dempsky 3f0842a464 sha3: have ShakeHash extend hash.Hash
Package sha3 recommends the SHAKE functions for new uses, but this is
currently somewhat inconvenient because ShakeHash does not implement
hash.Hash. This is understandable, as SHAKE supports arbitrary-length
outputs whereas hash.Hash only supports fixed-length outputs. But
there's a natural fixed-length output to provide: the minimum output
that still provides SHAKE's full-strength generic security.

While here, tweak Sum so that its temporary buffer can be stack
allocated.

Also, tweak the panic message in Write so that the error text is more
readily understandable to Go programmers without needing to be
familiar with crypto jargon, and add a similar check in Sum.

Change-Id: Icf037d3990a71de5630f8825606614443f8c5245
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/526937
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Adam Langley <agl@google.com>
Auto-Submit: Matthew Dempsky <mdempsky@google.com>
2023-09-10 18:25:15 +00:00
Daniel Mangum e90f1e17ee cryptobyte: add uint48 methods
Adds uint48 methods for cryptobyte.Builder and cryptobyte.String.
Supporting 48-bit unsigned integers is useful for working with protocols
that use them for sequence numbers, such as DTLS.

Fixes golang/go#61275

Change-Id: Ibe49422d37644b9212b28b123dc5e01850f7b05b
GitHub-Last-Rev: 11b388c240109c8f4ac23880645c901ce6d2f093
GitHub-Pull-Request: golang/crypto#265
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/508675
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: qiulaidongfeng <2645477756@qq.com>
Run-TryBot: Roland Shoemaker <roland@golang.org>
Auto-Submit: Roland Shoemaker <roland@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
2023-09-07 16:27:37 +00:00
Mariano Cano d359caa4a3 ssh: support for marshaling keys using the OpenSSH format
This adds methods to marshal private keys, encrypted and unencrypted
to the OpenSSH format.

Fixes golang/go#37132

Change-Id: I1a95301f789ce04858e6b147748c6e8b7700384b
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/218620
Run-TryBot: Roland Shoemaker <roland@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Roland Shoemaker <roland@golang.org>
2023-09-05 20:25:46 +00:00
Nicola Murino c5370d2cc6 ssh: check the declared public key algo against decoded one
This check will ensure we don't accept e.g. ssh-rsa-cert-v01@openssh.com
algorithm with ssh-rsa public key type.
The algorithm and public key type must be consistent: both must be
certificate algorithms, or neither.

Change-Id: I1d75074fb4d6db3a8796408e98ddffe577a96ab1
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/506836
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Run-TryBot: Filippo Valsorda <filippo@golang.org>
2023-09-05 16:18:45 +00:00
Gopher Robot 0d375be9b6 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.

Change-Id: Ib391e4f2f09056cb025de97d5d8f2640859d9163
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/525335
Run-TryBot: 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>
TryBot-Result: Gopher Robot <gobot@golang.org>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Heschi Kreinick <heschi@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2023-09-05 14:51:56 +00:00
Gopher Robot b4ddeeda5b go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.
Once this CL is submitted, and post-submit testing succeeds on all
first-class ports across all supported Go versions, this repository
will be tagged with its next minor version.

Change-Id: Id40feba36dfc31c7033c91b952ec824a38e048ee
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/515976
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Heschi Kreinick <heschi@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Gopher Robot <gobot@golang.org>
2023-08-04 16:57:07 +00:00
Nicola Murino edc325d13a ssh: fix call to Fatalf from a non-test goroutine
Also fix some redundant type declarations.

Change-Id: Iad2950b67b1ec2e2590c59393b8ad15421ed3add
GitHub-Last-Rev: 41cf552f11387208491dee7b867050475043b25e
GitHub-Pull-Request: golang/crypto#263
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/505798
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: David Chase <drchase@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Run-TryBot: Filippo Valsorda <filippo@golang.org>
2023-07-31 18:14:41 +00:00
Nicola Murino eab9315960 ssh: add diffie-hellman-group16-sha512 kex
This group is disabled by default because it is a bit slower than
the others.
The group18-sha512 variant is too slow to include.

Benchstat results including diffie-hellman-group18-sha512:

name                                           time/op
Kexes/diffie-hellman-group-exchange-sha256-12  22.6ms ± 9%
Kexes/diffie-hellman-group18-sha512-12          1.15s ±11%
Kexes/ecdh-sha2-nistp384-12                    3.91ms ± 6%
Kexes/ecdh-sha2-nistp256-12                     304µs ± 5%
Kexes/curve25519-sha256@libssh.org-12           413µs ± 7%
Kexes/ecdh-sha2-nistp521-12                    11.6ms ±13%
Kexes/curve25519-sha256-12                      361µs ± 5%
Kexes/diffie-hellman-group-exchange-sha1-12    22.9ms ± 9%
Kexes/diffie-hellman-group1-sha1-12            3.59ms ± 6%
Kexes/diffie-hellman-group14-sha1-12           22.1ms ±11%
Kexes/diffie-hellman-group14-sha256-12         21.6ms ± 8%
Kexes/diffie-hellman-group16-sha512-12          138ms ± 9%

name                                           alloc/op
Kexes/diffie-hellman-group-exchange-sha256-12  67.8kB ± 1%
Kexes/diffie-hellman-group18-sha512-12          243kB ± 9%
Kexes/ecdh-sha2-nistp384-12                    13.9kB ± 0%
Kexes/ecdh-sha2-nistp256-12                    12.1kB ± 0%
Kexes/curve25519-sha256@libssh.org-12          8.22kB ± 0%
Kexes/ecdh-sha2-nistp521-12                    16.5kB ± 0%
Kexes/curve25519-sha256-12                     8.22kB ± 0%
Kexes/diffie-hellman-group-exchange-sha1-12    67.5kB ± 0%
Kexes/diffie-hellman-group1-sha1-12            34.9kB ± 0%
Kexes/diffie-hellman-group14-sha1-12           61.9kB ± 0%
Kexes/diffie-hellman-group14-sha256-12         62.0kB ± 0%
Kexes/diffie-hellman-group16-sha512-12          117kB ± 0%

name                                           allocs/op
Kexes/diffie-hellman-group-exchange-sha256-12     314 ± 0%
Kexes/diffie-hellman-group18-sha512-12            271 ± 4%
Kexes/ecdh-sha2-nistp384-12                       243 ± 0%
Kexes/ecdh-sha2-nistp256-12                       213 ± 0%
Kexes/curve25519-sha256@libssh.org-12             168 ± 0%
Kexes/ecdh-sha2-nistp521-12                       245 ± 0%
Kexes/curve25519-sha256-12                        168 ± 0%
Kexes/diffie-hellman-group-exchange-sha1-12       314 ± 0%
Kexes/diffie-hellman-group1-sha1-12               255 ± 0%
Kexes/diffie-hellman-group14-sha1-12              255 ± 0%
Kexes/diffie-hellman-group14-sha256-12            255 ± 0%
Kexes/diffie-hellman-group16-sha512-12            256 ± 0%

Change-Id: Id119401fda7e417675325f37e3d442e70585206c
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/506839
Run-TryBot: Filippo Valsorda <filippo@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
2023-07-31 17:46:52 +00:00
Nicola Murino ddfa82138e ssh: ignore invalid MACs and KEXs just like we do for ciphers
Tighter validation could cause backwards incompatibility issues, eg
configurations with valid and invalid MACs, KEXs, ciphers currently work
if a supported algorithm is negotiated and that's also the scenario of
removing support for an existing algorithm.

Fixes golang/go#39397

Change-Id: If90253ba89e1d8f732cc1e1c3d24fe0a1e2dac71
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/512175
Run-TryBot: Han-Wen Nienhuys <hanwen@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Han-Wen Nienhuys <hanwen@google.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: David Chase <drchase@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2023-07-31 15:35:32 +00:00
Gopher Robot d08e19beac x509roots/fallback: update bundle
This is an automated CL which updates the NSS root bundle.

Change-Id: Ic70152e674c60e48e85d96eab244add9b4fa5eb8
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/512595
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Run-TryBot: Gopher Robot <gobot@golang.org>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
2023-07-25 17:50:45 +00:00
Dmitri Shuralyov 12e1fcd8c0 internal/wycheproof: skip all tests in short test mode
The testdata for this package is around 8 MB and downloaded dynamically
via 'go mod download' from its canonical source rather than being copied
to this repository. We're moving towards disallowing all network use in
short test mode, including proxy.golang.org, so add a corresponding test
skip.

Needing to lookup a go test flag is unfortunate, but I don't know of a
less bad available option while the test does the download in TestMain.

On balance, it becomes viable to no longer disable the checksum database
since the test will only run on builders that permit internet use and so
sum.golang.org should just work.

Change-Id: Iaffe3899351da375928aaba114c4875f5438336b
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/510695
Run-TryBot: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Heschi Kreinick <heschi@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2023-07-18 15:17:25 +00:00
Nicola Murino 3f8f0645c2 ssh: prefer sha256 based RSA key algorithms
sha256 is more optimized than sha512 in Go and is secure enough
so prefer sha256 over sha512.

Change-Id: I3fcf7457791e3ef4539e97049aa905dcd293499d
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/507556
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Run-TryBot: Filippo Valsorda <filippo@golang.org>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2023-07-14 16:27:34 +00:00
Nicola Murino 5df3b59941 ssh: disable client agent tests on Windows
ssh-agent is implemented as a Windows service and exposed on a
named pipe. We don't currently support it.

See golang/go#60981

Change-Id: Iebdc42db30b37a87ac0766231b16aff3f17b3f56
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/509035
Run-TryBot: Heschi Kreinick <heschi@google.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Heschi Kreinick <heschi@google.com>
Auto-Submit: Heschi Kreinick <heschi@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2023-07-13 13:29:36 +00:00
Boshi Lian 2e82bdd171 fix TestValidTerminalMode: missing output from echo SHELL $SHELL
add leading `echo` to have better compatibility

before

```
 go test -run ^TestValidTerminalMode -v
=== RUN   TestValidTerminalMode
    session_test.go:261: echo SHELL $SHELL && stty -a && exit:
        Last login: Thu Jul  6 12:24:38 2023 from 192.168.200.1
SHELL /bin/bashubuntu:~$
        speed 38400 baud; rows 80; columns 40;
        line = 0;
        intr = ^C; quit = ^\; erase = ^?;
        kill = ^U; eof = ^D; eol = <undef>;
        eol2 = <undef>; swtch = <undef>;
        start = ^Q; stop = ^S; susp = ^Z;
        rprnt = ^R; werase = ^W; lnext = ^V;
        discard = ^O; min = 1; time = 0;
        -parenb -parodd -cmspar cs8 -hupcl
        -cstopb cread -clocal -crtscts
        -ignbrk -brkint -ignpar -parmrk -inpck
        -istrip -inlcr -igncr icrnl ixon -ixoff
        -iuclc -ixany -imaxbel -iutf8
        opost -olcuc -ocrnl onlcr -onocr -onlret
        -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
        isig icanon iexten -echo echoe echok
        -echonl -noflsh -xcase -tostop -echoprt
        echoctl echoke -flusho -extproc
        logout
    session_test.go:266: missing output from echo SHELL $SHELL
```

after

```
 go test -run ^TestValidTerminalMode -v
=== RUN   TestValidTerminalMode
    session_test.go:261: echo SHELL $SHELL && stty -a && exit:
        Last login: Thu Jul  6 12:24:38 2023 from 192.168.200.1
        bolian@ubuntu:~$
        SHELL /bin/bash
        speed 38400 baud; rows 80; columns 40;
        line = 0;
        intr = ^C; quit = ^\; erase = ^?;
        kill = ^U; eof = ^D; eol = <undef>;
        eol2 = <undef>; swtch = <undef>;
        start = ^Q; stop = ^S; susp = ^Z;
        rprnt = ^R; werase = ^W; lnext = ^V;
        discard = ^O; min = 1; time = 0;
        -parenb -parodd -cmspar cs8 -hupcl
        -cstopb cread -clocal -crtscts
        -ignbrk -brkint -ignpar -parmrk -inpck
        -istrip -inlcr -igncr icrnl ixon -ixoff
        -iuclc -ixany -imaxbel -iutf8
        opost -olcuc -ocrnl onlcr -onocr -onlret
        -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
        isig icanon iexten -echo echoe echok
        -echonl -noflsh -xcase -tostop -echoprt
        echoctl echoke -flusho -extproc
        logout
--- PASS: TestValidTerminalMode (0.06s)
```

Change-Id: If60c040edb8c78a7d86bf58a6be47636d9e8f173
GitHub-Last-Rev: a2cc1b1af09e47df82fcb8685d829dfed945e8b0
GitHub-Pull-Request: golang/crypto#264
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/508115
Reviewed-by: Heschi Kreinick <heschi@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Heschi Kreinick <heschi@google.com>
Auto-Submit: Heschi Kreinick <heschi@google.com>
Reviewed-by: Bryan Mills <bcmills@google.com>
2023-07-11 16:17:43 +00:00
Nicola Murino 64e0e99383 ssh: fix RSA certificate and public key authentication with older clients
After adding support for rsa-sha2-256/512 on the server side some edge
cases started to arise with old clients:

1) public key authentication with gpg-agent < 2.2.6 fails because we
   receive ssh-rsa as signature format and rsa-sha2-256 or rsa-sha2-512
   as algorithm.
   This is a bug in gpg-agent fixed in this commit:

   https://github.com/gpg/gnupg/commit/80b775bdbb852aa4a80292c9357e5b1876110c00

2) certificate authentication fails with OpenSSH 7.2-7.7 because we
   receive ssh-rsa-cert-v01@openssh.com as algorithm and rsa-sha2-256
   or rsa-sha2-512 as signature format.

This patch is based on CL 412854 and has been tested with every version
of OpenSSH from 7.1 to 7.9 and OpenSSH 9.3.

Fixes golang/go#53391

Change-Id: Id71f596f73d84efb5c76d6d5388432cccad3e3b1
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/506835
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Run-TryBot: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2023-07-10 19:57:54 +00:00
Nicola Murino 23b1b90df2 ssh: prefer sha256 based MAC algorithms
sha256 is more optimized than sha512 in Go and is secure enough
so prefer sha256 over sha512.

Fixes golang/go#61138

Change-Id: I7658808655367f1ab5f4ac8b52e6b20bd30ebf87
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/507555
Run-TryBot: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Joedian Reid <joedian@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2023-07-05 20:33:07 +00:00
Gopher Robot e98487292d go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.
Once this CL is submitted, and post-submit testing succeeds on all
first-class ports across all supported Go versions, this repository
will be tagged with its next minor version.

Change-Id: Icede82501a3703fcaad524f6b91ff6e5452b4547
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/507837
Reviewed-by: Heschi Kreinick <heschi@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Run-TryBot: Gopher Robot <gobot@golang.org>
Auto-Submit: Gopher Robot <gobot@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
2023-07-05 13:50:10 +00:00
Roland Shoemaker 183630ada7 x509roots: generate a stable sort, for real this time
Sort based on the stringified subject, then break ties based on the raw
DER (which will, actually, be unique this time).

Change-Id: I3dd912fb19b103e92fabfb4562e31c6dcec40614
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/505695
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Roland Shoemaker <roland@golang.org>
2023-06-23 17:05:55 +00:00
Dmitri Shuralyov a9e447dde7 x509roots/fallback: add //go:build go1.20 to bundle.go
Package fallback has no API; its only purpose is to automatically call
x509.SetFallbackRoots with a set of fallback roots. That API was added
in Go 1.20, hence the go1.20 build constraint in fallback.go.

Add that constraint to bundle.go too, so that it fails to build rather
than quietly being a no-op in Go 1.19.

Also simplify Write(fmt.Sprintf()) into fmt.Fprintf while here.

Add a temporary workaround for go.dev/issue/52287.
It has no effect on the public API in this module.

For golang/go#57792.
For golang/go#52287.

Change-Id: I1fe13f7d54b07b0b031e8bae685cffd7a8160165
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/505578
Auto-Submit: Dmitri Shuralyov <dmitshur@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Run-TryBot: Dmitri Shuralyov <dmitshur@golang.org>
2023-06-23 16:46:51 +00:00
Stan Hu 64c3993f5c ssh: add hmac-sha2-512
This adds support for hmac-sha2-512 to ensure compatibility with SSH clients that request this MAC algorithm.

This rebases https://github.com/golang/crypto/pull/18.

Change-Id: Ia103c10a8b7e2e8dde556d5c36550eb5fa6bc1f6
GitHub-Last-Rev: 987ccae2bc7ae5e90a482d8797351c39dcb9bf33
GitHub-Pull-Request: golang/crypto#257
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/501455
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Commit-Queue: Han-Wen Nienhuys <hanwen@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Han-Wen Nienhuys <hanwen@google.com>
Run-TryBot: Han-Wen Nienhuys <hanwen@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2023-06-22 14:36:59 +00:00
Roland Shoemaker 5fe8145aca x509roots: remove list hash and generation date, change ordering
This makes the automated update workflow simpler.

Also switch the ordering from human readable subject (which is not
necessarily unique), to the raw SPKI (which should always be unique).
This makes it somewhat harder to read to a human (since it'll appear a
little jumbled) but results in a stable sort.

Note this results in adding two new roots, which were added since we
last generated the bundle.

Change-Id: Id4d34bf9e98164e7b2fc4f06f9b46b63c0013d23
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/504597
Run-TryBot: Roland Shoemaker <roland@golang.org>
Reviewed-by: Heschi Kreinick <heschi@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2023-06-20 21:21:47 +00:00
Roland Shoemaker 043e94c17a x509roots: fix generate script argument checking
Check for supply of both arguments forgot that the URL is set by
default. Instead just let the local path supersede the URL.

Change-Id: I0499137c99c735e8e453ff1c2a925435f3cd8039
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/504596
Run-TryBot: Roland Shoemaker <roland@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Roland Shoemaker <roland@golang.org>
2023-06-20 18:34:45 +00:00
Roland Shoemaker 0d502d7cd6 x509roots: use "generate" build tag
Since go generate sets it automatically.

Change-Id: I4623e523392140c0472b250ac99c8c3fa31e5b15
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/504595
Auto-Submit: Roland Shoemaker <roland@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Run-TryBot: Roland Shoemaker <roland@golang.org>
2023-06-20 18:28:47 +00:00
Bryan C. Mills 0ff60057bb ssh/test: set a timeout and WaitDelay on sshd subcommands
This uses a copy of testenv.Command copied from the main repo, with
light edits to allow the testenv helpers to build with Go 1.19.

The testenv helper revealed an exec.Command leak in TestCertLogin, so
we also fix that leak and simplify server cleanup using
testing.T.Cleanup.

For golang/go#60099.
Fixes golang/go#60343.

Change-Id: I7f79fcdb559498b987ee7689972ac53b83870aaf
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/496935
Auto-Submit: Bryan Mills <bcmills@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Run-TryBot: Bryan Mills <bcmills@google.com>
2023-06-15 16:06:57 +00:00
Gopher Robot 8e447d8cc5 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.
Once this CL is submitted, and post-submit testing succeeds on all
first-class ports across all supported Go versions, this repository
will be tagged with its next minor version.

Change-Id: If19e251a79af033583e6968766b7a831741cebb7
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/502518
Reviewed-by: Heschi Kreinick <heschi@google.com>
Run-TryBot: Gopher Robot <gobot@golang.org>
Reviewed-by: Carlos Amedee <carlos@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Auto-Submit: Gopher Robot <gobot@golang.org>
2023-06-12 19:51:08 +00:00
Heschi Kreinick 22c9997952 go.mod: tell x repo tagging to ignore dep on net
CL 475438 introduced a cycle between net and crypto. This direction is
less important, so have the tagging process ignore it.

Change-Id: Ie424fef0238702a5a16aba79bb60f86f39dc66eb
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/502595
Auto-Submit: Heschi Kreinick <heschi@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Damien Neil <dneil@google.com>
Run-TryBot: Heschi Kreinick <heschi@google.com>
2023-06-12 17:20:30 +00:00
Roland Shoemaker d0b316056b x509roots: add new module
Adds the nss parser, under x509roots/nss, and the fallback
module/package, with the initial generated bundle.

Fixes golang/go#57792

Change-Id: Iebb1052e49126fa5baba1236f4ebc8dd8a823179
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/462036
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Roland Shoemaker <roland@golang.org>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Damien Neil <dneil@google.com>
Auto-Submit: Roland Shoemaker <roland@golang.org>
2023-06-09 17:23:14 +00:00
Stefan Klein 16222386f4 Add support for "hmac-sha2-512-etm@openssh.com"
Change-Id: I0203881afd7ad72e68f76650817451d7e292c91b
GitHub-Last-Rev: 42b4119e1987e7a46aa06a2b142d5fd3ef6f216a
GitHub-Pull-Request: golang/crypto#129
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/226982
Run-TryBot: Han-Wen Nienhuys <hanwen@google.com>
Reviewed-by: Han-Wen Nienhuys <hanwen@google.com>
Auto-Submit: Han-Wen Nienhuys <hanwen@google.com>
Reviewed-by: David Chase <drchase@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2023-06-05 16:42:04 +00:00
Gopher Robot a4e984136a go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.
Once this CL is submitted, and post-submit testing succeeds on all
first-class ports across all supported Go versions, this repository
will be tagged with its next minor version.

Change-Id: I1eb2365549b72cbad23fa7c355f427c6ed75e450
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/493575
TryBot-Result: Gopher Robot <gobot@golang.org>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Run-TryBot: Gopher Robot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Heschi Kreinick <heschi@google.com>
2023-05-08 17:07:49 +00:00
Tobias Klauser 3ef8056490 ssh/test: enable on solaris
Change-Id: Icf9c867e64ef68f6f46dd7d4cec07cf7c315c2ad
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/490155
Reviewed-by: Bryan Mills <bcmills@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Run-TryBot: Tobias Klauser <tobias.klauser@gmail.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Auto-Submit: Tobias Klauser <tobias.klauser@gmail.com>
2023-05-04 16:27:40 +00:00
Tobias Klauser a8cc953517 ssh: skip unsupported tests on wasip1
Updates golang/go#32840
Updates golang/go#58141

Change-Id: Ib4425c1743d417920745205586af250dbf80c7e4
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/485695
Auto-Submit: Tobias Klauser <tobias.klauser@gmail.com>
Reviewed-by: Bryan Mills <bcmills@google.com>
Run-TryBot: Tobias Klauser <tobias.klauser@gmail.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@google.com>
2023-04-18 17:07:48 +00:00
Bryan C. Mills 7d6d3f5d4a ssh/test: skip TestValidTerminalMode on non-Bourne shells
Fixes golang/go#38037.

Change-Id: Ide77dddc9f57b3f0318a419a1474e11215623b64
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/485175
Run-TryBot: Bryan Mills <bcmills@google.com>
Commit-Queue: Bryan Mills <bcmills@google.com>
Auto-Submit: Bryan Mills <bcmills@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2023-04-17 17:20:41 +00:00
Mateusz Poliwczak 1faeef9713 cryptobyte: reject Object Identifiers with leading 0x80
Change-Id: Ie3a1b53e801077cd86963799e644b9783943933c
GitHub-Last-Rev: 6629bd74f1874eb9fde8e72bfb444ebf9073a1ab
GitHub-Pull-Request: golang/crypto#255
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/483955
Run-TryBot: Mateusz Poliwczak <mpoliwczak34@gmail.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Run-TryBot: Ian Lance Taylor <iant@google.com>
2023-04-12 18:30:42 +00:00
Gopher Robot 00fd4ff485 go.mod: update golang.org/x dependencies
Update golang.org/x dependencies to their latest tagged versions.
Once this CL is submitted, and post-submit testing succeeds on all
first-class ports across all supported Go versions, this repository
will be tagged with its next minor version.

Change-Id: I568d040817345a10881c31b8efc296f543e59113
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/482855
Reviewed-by: Heschi Kreinick <heschi@google.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Gopher Robot <gobot@golang.org>
Reviewed-by: Carlos Amedee <carlos@golang.org>
2023-04-06 17:52:09 +00:00
cui fliter 018c28f8a1 all: fix some comments
Change-Id: Ia0410f1f3bb0a9ee68c6dbe1e6f62f65f9e00955
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/477755
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Roland Shoemaker <roland@golang.org>
Run-TryBot: shuang cui <imcusg@gmail.com>
Run-TryBot: Ian Lance Taylor <iant@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2023-03-20 20:33:29 +00:00
Filippo Valsorda 9cd0187c09 curve25519: use crypto/ecdh on Go 1.20
For golang/go#52221

Change-Id: I27e867d4cc89cd52c8d510f0dbab4e89b7cd4763
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/451115
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Cherry Mui <cherryyz@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2023-03-13 18:33:59 +00:00
Anmol Sethi c6a20f9984 ssh: document that ParseRawPrivateKey supports Ed25519 keys
From CL 173457 and CL 235358.

Change-Id: Ia46ab9c7e2c57472df3126ddc7050f0068fcaab9
GitHub-Last-Rev: c38e379355602fe4ff11ff65f98c296d5c326281
GitHub-Pull-Request: golang/crypto#146
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/241282
Auto-Submit: Han-Wen Nienhuys <hanwen@google.com>
Reviewed-by: Bryan Mills <bcmills@google.com>
Reviewed-by: Han-Wen Nienhuys <hanwen@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Han-Wen Nienhuys <hanwen@google.com>
2023-03-13 12:45:00 +00:00
300 changed files with 57526 additions and 10851 deletions
+2 -2
View File
@@ -1,4 +1,4 @@
Copyright (c) 2009 The Go Authors. All rights reserved.
Copyright 2009 The Go Authors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
@@ -10,7 +10,7 @@ notice, this list of conditions and the following disclaimer.
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
* Neither the name of Google LLC nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
+5 -8
View File
@@ -2,20 +2,17 @@
[![Go Reference](https://pkg.go.dev/badge/golang.org/x/crypto.svg)](https://pkg.go.dev/golang.org/x/crypto)
This repository holds supplementary Go cryptography libraries.
## Download/Install
The easiest way to install is to run `go get -u golang.org/x/crypto/...`. You
can also manually git clone the repository to `$GOPATH/src/golang.org/x/crypto`.
This repository holds supplementary Go cryptography packages.
## Report Issues / Send Patches
This repository uses Gerrit for code changes. To learn how to submit changes to
this repository, see https://golang.org/doc/contribute.html.
this repository, see https://go.dev/doc/contribute.
The git repository is https://go.googlesource.com/crypto.
The main issue tracker for the crypto repository is located at
https://github.com/golang/go/issues. Prefix your issue with "x/crypto:" in the
https://go.dev/issues. Prefix your issue with "x/crypto:" in the
subject line, so it is easy to find.
Note that contributions to the cryptography package receive additional scrutiny
+46 -56
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"
@@ -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
+87 -111
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"
@@ -757,10 +741,11 @@ func TestTLSALPN01ChallengeCert(t *testing.T) {
}
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)
}
}
}
+10 -15
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
@@ -292,6 +293,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 +310,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 +465,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
}
@@ -609,7 +611,7 @@ 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()
}
@@ -907,7 +909,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 +921,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 +1029,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()
+5 -5
View File
@@ -561,9 +561,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 +619,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 +694,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)
}
+7 -19
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")
@@ -308,7 +308,7 @@ func (ca *CAServer) handle(w http.ResponseWriter, r *http.Request) {
}
if err := decodePayload(&req, r.Body); err != nil {
ca.httpErrorf(w, http.StatusBadRequest, err.Error())
ca.httpErrorf(w, http.StatusBadRequest, "%v", err)
return
}
@@ -328,7 +328,7 @@ func (ca *CAServer) handle(w http.ResponseWriter, r *http.Request) {
Identifiers []struct{ Value string }
}
if err := decodePayload(&req, r.Body); err != nil {
ca.httpErrorf(w, http.StatusBadRequest, err.Error())
ca.httpErrorf(w, http.StatusBadRequest, "%v", err)
return
}
ca.mu.Lock()
@@ -352,7 +352,7 @@ func (ca *CAServer) handle(w http.ResponseWriter, r *http.Request) {
defer ca.mu.Unlock()
o, err := ca.storedOrder(strings.TrimPrefix(r.URL.Path, "/orders/"))
if err != nil {
ca.httpErrorf(w, http.StatusBadRequest, err.Error())
ca.httpErrorf(w, http.StatusBadRequest, "%v", err)
return
}
if err := json.NewEncoder(w).Encode(o); err != nil {
@@ -412,7 +412,7 @@ func (ca *CAServer) handle(w http.ResponseWriter, r *http.Request) {
orderID := strings.TrimPrefix(r.URL.Path, "/new-cert/")
o, err := ca.storedOrder(orderID)
if err != nil {
ca.httpErrorf(w, http.StatusBadRequest, err.Error())
ca.httpErrorf(w, http.StatusBadRequest, "%v", err)
return
}
if o.Status != acme.StatusReady {
@@ -427,7 +427,7 @@ func (ca *CAServer) handle(w http.ResponseWriter, r *http.Request) {
b, _ := base64.RawURLEncoding.DecodeString(req.CSR)
csr, err := x509.ParseCertificateRequest(b)
if err != nil {
ca.httpErrorf(w, http.StatusBadRequest, err.Error())
ca.httpErrorf(w, http.StatusBadRequest, "%v", err)
return
}
// Issue the certificate.
@@ -449,7 +449,7 @@ func (ca *CAServer) handle(w http.ResponseWriter, r *http.Request) {
defer ca.mu.Unlock()
o, err := ca.storedOrder(strings.TrimPrefix(r.URL.Path, "/issued-cert/"))
if err != nil {
ca.httpErrorf(w, http.StatusBadRequest, err.Error())
ca.httpErrorf(w, http.StatusBadRequest, "%v", err)
return
}
if o.Status != acme.StatusValid {
@@ -782,15 +782,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 -18
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)
}
})
}
}
@@ -239,7 +272,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()
+24 -8
View File
@@ -15,6 +15,7 @@ import (
"io"
"math/big"
"net/http"
"runtime/debug"
"strconv"
"strings"
"time"
@@ -65,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
@@ -85,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,
@@ -130,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
}
@@ -230,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
}
@@ -271,9 +269,27 @@ func (c *Client) httpClient() *http.Client {
}
// packageVersion is the version of the module that contains this package, for
// sending as part of the User-Agent header. It's set in version_go112.go.
// sending as part of the User-Agent header.
var packageVersion string
func init() {
// Set packageVersion if the binary was built in modules mode and x/crypto
// was not replaced with a different module.
info, ok := debug.ReadBuildInfo()
if !ok {
return
}
for _, m := range info.Deps {
if m.Path != "golang.org/x/crypto" {
continue
}
if m.Replace == nil {
packageVersion = m.Version
}
break
}
}
// userAgent returns the User-Agent header value. It includes the package name,
// the module version (if available), and the c.UserAgent value (if set).
func (c *Client) userAgent() string {
+1 -1
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
+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.7.0"
// 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.Is(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.CreateOrderCert(ctx, order.FinalizeURL, 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",
"-dns01", 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()))
}
}
})
}
+3 -3
View File
@@ -232,7 +232,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,
@@ -272,7 +272,7 @@ func (c *Client) WaitOrder(ctx context.Context, url string) (*Order, error) {
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
}
@@ -369,7 +369,7 @@ func (c *Client) CreateOrderCert(ctx context.Context, url string, csr []byte, bu
}
// 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
+16 -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) {
+21 -3
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.
@@ -149,13 +154,16 @@ 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 {
@@ -288,7 +296,7 @@ type Directory struct {
// KeyChangeURL allows to perform account key rollover flow.
KeyChangeURL string
// Term is a URI identifying the current terms of service.
// Terms is a URI identifying the current terms of service.
Terms string
// Website is an HTTP or HTTPS URL locating a website
@@ -527,6 +535,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 +622,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)
}
-28
View File
@@ -1,28 +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 go1.12
// +build go1.12
package acme
import "runtime/debug"
func init() {
// Set packageVersion if the binary was built in modules mode and x/crypto
// was not replaced with a different module.
info, ok := debug.ReadBuildInfo()
if !ok {
return
}
for _, m := range info.Deps {
if m.Path != "golang.org/x/crypto" {
continue
}
if m.Replace == nil {
packageVersion = m.Version
}
break
}
}
+287
View File
@@ -0,0 +1,287 @@
// Copyright 2024 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 main
import (
. "github.com/mmcloughlin/avo/build"
. "github.com/mmcloughlin/avo/operand"
. "github.com/mmcloughlin/avo/reg"
_ "golang.org/x/crypto/argon2"
)
//go:generate go run . -out ../blamka_amd64.s -pkg argon2
func main() {
Package("golang.org/x/crypto/argon2")
ConstraintExpr("amd64,gc,!purego")
blamkaSSE4()
mixBlocksSSE2()
xorBlocksSSE2()
Generate()
}
func blamkaSSE4() {
Implement("blamkaSSE4")
Attributes(NOSPLIT)
AllocLocal(0)
Load(Param("b"), RAX)
c40 := c40_DATA()
c48 := c48_DATA()
MOVOU(c40, X10)
MOVOU(c48, X11)
BLAMKA_ROUND_0(AX, 0, X8, X9, X10, X11)
BLAMKA_ROUND_0(AX, 16, X8, X9, X10, X11)
BLAMKA_ROUND_0(AX, 32, X8, X9, X10, X11)
BLAMKA_ROUND_0(AX, 48, X8, X9, X10, X11)
BLAMKA_ROUND_0(AX, 64, X8, X9, X10, X11)
BLAMKA_ROUND_0(AX, 80, X8, X9, X10, X11)
BLAMKA_ROUND_0(AX, 96, X8, X9, X10, X11)
BLAMKA_ROUND_0(AX, 112, X8, X9, X10, X11)
BLAMKA_ROUND_1(AX, 0, X8, X9, X10, X11)
BLAMKA_ROUND_1(AX, 2, X8, X9, X10, X11)
BLAMKA_ROUND_1(AX, 4, X8, X9, X10, X11)
BLAMKA_ROUND_1(AX, 6, X8, X9, X10, X11)
BLAMKA_ROUND_1(AX, 8, X8, X9, X10, X11)
BLAMKA_ROUND_1(AX, 10, X8, X9, X10, X11)
BLAMKA_ROUND_1(AX, 12, X8, X9, X10, X11)
BLAMKA_ROUND_1(AX, 14, X8, X9, X10, X11)
RET()
}
func mixBlocksSSE2() {
Implement("mixBlocksSSE2")
Attributes(NOSPLIT)
AllocLocal(0)
Load(Param("out"), RDX)
Load(Param("a"), RAX)
Load(Param("b"), RBX)
Load(Param("c"), RCX)
MOVQ(U32(128), RDI)
Label("loop")
MOVOU(Mem{Base: AX}.Offset(0), X0)
MOVOU(Mem{Base: BX}.Offset(0), X1)
MOVOU(Mem{Base: CX}.Offset(0), X2)
PXOR(X1, X0)
PXOR(X2, X0)
MOVOU(X0, Mem{Base: DX}.Offset(0))
ADDQ(Imm(16), RAX)
ADDQ(Imm(16), RBX)
ADDQ(Imm(16), RCX)
ADDQ(Imm(16), RDX)
SUBQ(Imm(2), RDI)
JA(LabelRef("loop"))
RET()
}
func xorBlocksSSE2() {
Implement("xorBlocksSSE2")
Attributes(NOSPLIT)
AllocLocal(0)
Load(Param("out"), RDX)
Load(Param("a"), RAX)
Load(Param("b"), RBX)
Load(Param("c"), RCX)
MOVQ(U32(128), RDI)
Label("loop")
MOVOU(Mem{Base: AX}.Offset(0), X0)
MOVOU(Mem{Base: BX}.Offset(0), X1)
MOVOU(Mem{Base: CX}.Offset(0), X2)
MOVOU(Mem{Base: DX}.Offset(0), X3)
PXOR(X1, X0)
PXOR(X2, X0)
PXOR(X3, X0)
MOVOU(X0, Mem{Base: DX}.Offset(0))
ADDQ(Imm(16), RAX)
ADDQ(Imm(16), RBX)
ADDQ(Imm(16), RCX)
ADDQ(Imm(16), RDX)
SUBQ(Imm(2), RDI)
JA(LabelRef("loop"))
RET()
}
func SHUFFLE(v2, v3, v4, v5, v6, v7, t1, t2 VecPhysical) {
MOVO(v4, t1)
MOVO(v5, v4)
MOVO(t1, v5)
MOVO(v6, t1)
PUNPCKLQDQ(v6, t2)
PUNPCKHQDQ(v7, v6)
PUNPCKHQDQ(t2, v6)
PUNPCKLQDQ(v7, t2)
MOVO(t1, v7)
MOVO(v2, t1)
PUNPCKHQDQ(t2, v7)
PUNPCKLQDQ(v3, t2)
PUNPCKHQDQ(t2, v2)
PUNPCKLQDQ(t1, t2)
PUNPCKHQDQ(t2, v3)
}
func SHUFFLE_INV(v2, v3, v4, v5, v6, v7, t1, t2 VecPhysical) {
MOVO(v4, t1)
MOVO(v5, v4)
MOVO(t1, v5)
MOVO(v2, t1)
PUNPCKLQDQ(v2, t2)
PUNPCKHQDQ(v3, v2)
PUNPCKHQDQ(t2, v2)
PUNPCKLQDQ(v3, t2)
MOVO(t1, v3)
MOVO(v6, t1)
PUNPCKHQDQ(t2, v3)
PUNPCKLQDQ(v7, t2)
PUNPCKHQDQ(t2, v6)
PUNPCKLQDQ(t1, t2)
PUNPCKHQDQ(t2, v7)
}
func HALF_ROUND(v0, v1, v2, v3, v4, v5, v6, v7, t0, c40, c48 VecPhysical) {
MOVO(v0, t0)
PMULULQ(v2, t0)
PADDQ(v2, v0)
PADDQ(t0, v0)
PADDQ(t0, v0)
PXOR(v0, v6)
PSHUFD(Imm(0xB1), v6, v6)
MOVO(v4, t0)
PMULULQ(v6, t0)
PADDQ(v6, v4)
PADDQ(t0, v4)
PADDQ(t0, v4)
PXOR(v4, v2)
PSHUFB(c40, v2)
MOVO(v0, t0)
PMULULQ(v2, t0)
PADDQ(v2, v0)
PADDQ(t0, v0)
PADDQ(t0, v0)
PXOR(v0, v6)
PSHUFB(c48, v6)
MOVO(v4, t0)
PMULULQ(v6, t0)
PADDQ(v6, v4)
PADDQ(t0, v4)
PADDQ(t0, v4)
PXOR(v4, v2)
MOVO(v2, t0)
PADDQ(v2, t0)
PSRLQ(Imm(63), v2)
PXOR(t0, v2)
MOVO(v1, t0)
PMULULQ(v3, t0)
PADDQ(v3, v1)
PADDQ(t0, v1)
PADDQ(t0, v1)
PXOR(v1, v7)
PSHUFD(Imm(0xB1), v7, v7)
MOVO(v5, t0)
PMULULQ(v7, t0)
PADDQ(v7, v5)
PADDQ(t0, v5)
PADDQ(t0, v5)
PXOR(v5, v3)
PSHUFB(c40, v3)
MOVO(v1, t0)
PMULULQ(v3, t0)
PADDQ(v3, v1)
PADDQ(t0, v1)
PADDQ(t0, v1)
PXOR(v1, v7)
PSHUFB(c48, v7)
MOVO(v5, t0)
PMULULQ(v7, t0)
PADDQ(v7, v5)
PADDQ(t0, v5)
PADDQ(t0, v5)
PXOR(v5, v3)
MOVO(v3, t0)
PADDQ(v3, t0)
PSRLQ(Imm(63), v3)
PXOR(t0, v3)
}
func LOAD_MSG_0(block GPPhysical, off int) {
var registers = []VecPhysical{X0, X1, X2, X3, X4, X5, X6, X7}
for i, r := range registers {
MOVOU(Mem{Base: block}.Offset(8*(off+(i*2))), r)
}
}
func STORE_MSG_0(block GPPhysical, off int) {
var registers = []VecPhysical{X0, X1, X2, X3, X4, X5, X6, X7}
for i, r := range registers {
MOVOU(r, Mem{Base: block}.Offset(8*(off+(i*2))))
}
}
func LOAD_MSG_1(block GPPhysical, off int) {
var registers = []VecPhysical{X0, X1, X2, X3, X4, X5, X6, X7}
for i, r := range registers {
MOVOU(Mem{Base: block}.Offset(8*off+i*16*8), r)
}
}
func STORE_MSG_1(block GPPhysical, off int) {
var registers = []VecPhysical{X0, X1, X2, X3, X4, X5, X6, X7}
for i, r := range registers {
MOVOU(r, Mem{Base: block}.Offset(8*off+i*16*8))
}
}
func BLAMKA_ROUND_0(block GPPhysical, off int, t0, t1, c40, c48 VecPhysical) {
LOAD_MSG_0(block, off)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, t0, c40, c48)
SHUFFLE(X2, X3, X4, X5, X6, X7, t0, t1)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, t0, c40, c48)
SHUFFLE_INV(X2, X3, X4, X5, X6, X7, t0, t1)
STORE_MSG_0(block, off)
}
func BLAMKA_ROUND_1(block GPPhysical, off int, t0, t1, c40, c48 VecPhysical) {
LOAD_MSG_1(block, off)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, t0, c40, c48)
SHUFFLE(X2, X3, X4, X5, X6, X7, t0, t1)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, t0, c40, c48)
SHUFFLE_INV(X2, X3, X4, X5, X6, X7, t0, t1)
STORE_MSG_1(block, off)
}
// ##------------------DATA SECTION-------------------##
var c40_DATA_ptr, c48_DATA_ptr *Mem
func c40_DATA() Mem {
if c40_DATA_ptr != nil {
return *c40_DATA_ptr
}
c40_DATA := GLOBL("·c40", NOPTR|RODATA)
c40_DATA_ptr = &c40_DATA
DATA(0x00, U64(0x0201000706050403))
DATA(0x08, U64(0x0a09080f0e0d0c0b))
return c40_DATA
}
func c48_DATA() Mem {
if c48_DATA_ptr != nil {
return *c48_DATA_ptr
}
c48_DATA := GLOBL("·c48", NOPTR|RODATA)
c48_DATA_ptr = &c48_DATA
DATA(0x00, U64(0x0100070605040302))
DATA(0x08, U64(0x09080f0e0d0c0b0a))
return c48_DATA
}
+15
View File
@@ -0,0 +1,15 @@
module argon2/_asm
go 1.23
require (
github.com/mmcloughlin/avo v0.6.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.30.0 // indirect
golang.org/x/tools v0.24.0 // indirect
)
+12
View File
@@ -0,0 +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.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.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=
+11 -7
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,7 +17,7 @@
// 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
// parameters (taken from [RFC 9106 Section 7.3]) for non-interactive operations are time=3 and to
// use the maximum available memory.
//
// # Argon2id
@@ -27,11 +27,11 @@
// 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
// parameters for non-interactive operations (taken from [RFC 9106 Section 7.3]) are time=1 and to
// use the maximum available memory.
//
// [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 7.3]: https://www.rfc-editor.org/rfc/rfc9106.html#section-7.3
package argon2
import (
@@ -59,7 +59,7 @@ 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.
// [RFC 9106 Section 7.3] recommends time=3, and memory=32*1024 as 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.
//
@@ -69,6 +69,8 @@ const (
// adjusted to the number 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 7.3]: https://www.rfc-editor.org/rfc/rfc9106.html#section-7.3
func Key(password, salt []byte, time, memory uint32, threads uint8, keyLen uint32) []byte {
return deriveKey(argon2i, password, salt, nil, nil, time, memory, threads, keyLen)
}
@@ -83,7 +85,7 @@ func Key(password, salt []byte, time, memory uint32, threads uint8, keyLen uint3
//
// key := argon2.IDKey([]byte("some password"), salt, 1, 64*1024, 4, 32)
//
// The draft RFC recommends[2] time=1, and memory=64*1024 is a sensible number.
// [RFC 9106 Section 7.3] recommends time=1, and memory=64*1024 as 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.
//
@@ -93,6 +95,8 @@ func Key(password, salt []byte, time, memory uint32, threads uint8, keyLen uint3
// 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 7.3]: https://www.rfc-editor.org/rfc/rfc9106.html#section-7.3
func IDKey(password, salt []byte, time, memory uint32, threads uint8, keyLen uint32) []byte {
return deriveKey(argon2id, password, salt, nil, nil, time, memory, threads, keyLen)
}
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build amd64 && gc && !purego
// +build amd64,gc,!purego
package argon2
+2763 -216
View File
File diff suppressed because it is too large Load Diff
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build !amd64 || purego || !gc
// +build !amd64 purego !gc
package argon2
+2 -2
View File
@@ -4,7 +4,7 @@
// Package bcrypt implements Provos and Mazières's bcrypt adaptive hashing
// algorithm. See http://www.usenix.org/event/usenix99/provos/provos.pdf
package bcrypt // import "golang.org/x/crypto/bcrypt"
package bcrypt
// The code is a port of Provos and Mazières's C implementation.
import (
@@ -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 (
File diff suppressed because it is too large Load Diff
+16
View File
@@ -0,0 +1,16 @@
module blake2b/_asm/AVX2
go 1.23
require (
github.com/mmcloughlin/avo v0.6.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.30.0 // indirect
golang.org/x/tools v0.24.0 // indirect
)
+12
View File
@@ -0,0 +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.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.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=
+361
View File
@@ -0,0 +1,361 @@
// Copyright 2024 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 main
import (
. "github.com/mmcloughlin/avo/build"
. "github.com/mmcloughlin/avo/operand"
. "github.com/mmcloughlin/avo/reg"
_ "golang.org/x/crypto/blake2b"
)
//go:generate go run . -out ../../blake2b_amd64.s -pkg blake2b
const ThatPeskyUnicodeDot = "\u00b7"
var iv0_DATA_ptr, iv1_DATA_ptr, iv2_DATA_ptr, iv3_DATA_ptr, c40_DATA_ptr, c48_DATA_ptr *Mem
func main() {
Package("golang.org/x/crypto/blake2b")
ConstraintExpr("amd64,gc,!purego")
hashBlocksSSE4()
Generate()
}
func SHUFFLE(v2, v3, v4, v5, v6, v7, t1, t2 VecPhysical) {
MOVO(v4, t1)
MOVO(v5, v4)
MOVO(t1, v5)
MOVO(v6, t1)
PUNPCKLQDQ(v6, t2)
PUNPCKHQDQ(v7, v6)
PUNPCKHQDQ(t2, v6)
PUNPCKLQDQ(v7, t2)
MOVO(t1, v7)
MOVO(v2, t1)
PUNPCKHQDQ(t2, v7)
PUNPCKLQDQ(v3, t2)
PUNPCKHQDQ(t2, v2)
PUNPCKLQDQ(t1, t2)
PUNPCKHQDQ(t2, v3)
}
func SHUFFLE_INV(v2, v3, v4, v5, v6, v7, t1, t2 VecPhysical) {
MOVO(v4, t1)
MOVO(v5, v4)
MOVO(t1, v5)
MOVO(v2, t1)
PUNPCKLQDQ(v2, t2)
PUNPCKHQDQ(v3, v2)
PUNPCKHQDQ(t2, v2)
PUNPCKLQDQ(v3, t2)
MOVO(t1, v3)
MOVO(v6, t1)
PUNPCKHQDQ(t2, v3)
PUNPCKLQDQ(v7, t2)
PUNPCKHQDQ(t2, v6)
PUNPCKLQDQ(t1, t2)
PUNPCKHQDQ(t2, v7)
}
func HALF_ROUND(v0, v1, v2, v3, v4, v5, v6, v7 VecPhysical, m0, m1, m2, m3 Op, t0, c40, c48 VecPhysical) {
PADDQ(m0, v0)
PADDQ(m1, v1)
PADDQ(v2, v0)
PADDQ(v3, v1)
PXOR(v0, v6)
PXOR(v1, v7)
PSHUFD(Imm(0xB1), v6, v6)
PSHUFD(Imm(0xB1), v7, v7)
PADDQ(v6, v4)
PADDQ(v7, v5)
PXOR(v4, v2)
PXOR(v5, v3)
PSHUFB(c40, v2)
PSHUFB(c40, v3)
PADDQ(m2, v0)
PADDQ(m3, v1)
PADDQ(v2, v0)
PADDQ(v3, v1)
PXOR(v0, v6)
PXOR(v1, v7)
PSHUFB(c48, v6)
PSHUFB(c48, v7)
PADDQ(v6, v4)
PADDQ(v7, v5)
PXOR(v4, v2)
PXOR(v5, v3)
MOVOU(v2, t0)
PADDQ(v2, t0)
PSRLQ(Imm(63), v2)
PXOR(t0, v2)
MOVOU(v3, t0)
PADDQ(v3, t0)
PSRLQ(Imm(63), v3)
PXOR(t0, v3)
}
func LOAD_MSG(m0, m1, m2, m3 VecPhysical, src GPPhysical, i0, i1, i2, i3, i4, i5, i6, i7 int) {
MOVQ(Mem{Base: src}.Offset(i0*8), m0)
PINSRQ(Imm(1), Mem{Base: src}.Offset(i1*8), m0)
MOVQ(Mem{Base: src}.Offset(i2*8), m1)
PINSRQ(Imm(1), Mem{Base: src}.Offset(i3*8), m1)
MOVQ(Mem{Base: src}.Offset(i4*8), m2)
PINSRQ(Imm(1), Mem{Base: src}.Offset(i5*8), m2)
MOVQ(Mem{Base: src}.Offset(i6*8), m3)
PINSRQ(Imm(1), Mem{Base: src}.Offset(i7*8), m3)
}
func hashBlocksSSE4() {
Implement("hashBlocksSSE4")
Attributes(4)
AllocLocal(288) // frame size = 272 + 16 byte alignment
Load(Param("h"), RAX)
Load(Param("c"), RBX)
Load(Param("flag"), RCX)
Load(Param("blocks").Base(), RSI)
Load(Param("blocks").Len(), RDI)
MOVQ(RSP, R10)
ADDQ(Imm(15), R10)
ANDQ(I32(-16), R10)
iv3 := iv3_DATA()
MOVOU(iv3, X0)
MOVO(X0, Mem{Base: R10}.Offset(0))
XORQ(RCX, Mem{Base: R10}.Offset(0)) // 0(R10) = ·iv3 ^ (CX || 0)
c40 := c40_DATA()
c48 := c48_DATA()
MOVOU(c40, X13)
MOVOU(c48, X14)
MOVOU(Mem{Base: AX}.Offset(0), X12)
MOVOU(Mem{Base: AX}.Offset(16), X15)
MOVQ(Mem{Base: BX}.Offset(0), R8)
MOVQ(Mem{Base: BX}.Offset(8), R9)
Label("loop")
ADDQ(Imm(128), R8)
CMPQ(R8, Imm(128))
JGE(LabelRef("noinc"))
INCQ(R9)
Label("noinc")
MOVQ(R8, X8)
PINSRQ(Imm(1), R9, X8)
iv0 := iv0_DATA()
iv1 := iv1_DATA()
iv2 := iv2_DATA()
MOVO(X12, X0)
MOVO(X15, X1)
MOVOU(Mem{Base: AX}.Offset(32), X2)
MOVOU(Mem{Base: AX}.Offset(48), X3)
MOVOU(iv0, X4)
MOVOU(iv1, X5)
MOVOU(iv2, X6)
PXOR(X8, X6)
MOVO(Mem{Base: R10}.Offset(0), X7)
LOAD_MSG(X8, X9, X10, X11, SI, 0, 2, 4, 6, 1, 3, 5, 7)
MOVO(X8, Mem{Base: R10}.Offset(16))
MOVO(X9, Mem{Base: R10}.Offset(32))
MOVO(X10, Mem{Base: R10}.Offset(48))
MOVO(X11, Mem{Base: R10}.Offset(64))
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
LOAD_MSG(X8, X9, X10, X11, SI, 8, 10, 12, 14, 9, 11, 13, 15)
MOVO(X8, Mem{Base: R10}.Offset(80))
MOVO(X9, Mem{Base: R10}.Offset(96))
MOVO(X10, Mem{Base: R10}.Offset(112))
MOVO(X11, Mem{Base: R10}.Offset(128))
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
LOAD_MSG(X8, X9, X10, X11, SI, 14, 4, 9, 13, 10, 8, 15, 6)
MOVO(X8, Mem{Base: R10}.Offset(144))
MOVO(X9, Mem{Base: R10}.Offset(160))
MOVO(X10, Mem{Base: R10}.Offset(176))
MOVO(X11, Mem{Base: R10}.Offset(192))
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
LOAD_MSG(X8, X9, X10, X11, SI, 1, 0, 11, 5, 12, 2, 7, 3)
MOVO(X8, Mem{Base: R10}.Offset(208))
MOVO(X9, Mem{Base: R10}.Offset(224))
MOVO(X10, Mem{Base: R10}.Offset(240))
MOVO(X11, Mem{Base: R10}.Offset(256))
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
LOAD_MSG(X8, X9, X10, X11, SI, 11, 12, 5, 15, 8, 0, 2, 13)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
LOAD_MSG(X8, X9, X10, X11, SI, 10, 3, 7, 9, 14, 6, 1, 4)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
LOAD_MSG(X8, X9, X10, X11, SI, 7, 3, 13, 11, 9, 1, 12, 14)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
LOAD_MSG(X8, X9, X10, X11, SI, 2, 5, 4, 15, 6, 10, 0, 8)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
LOAD_MSG(X8, X9, X10, X11, SI, 9, 5, 2, 10, 0, 7, 4, 15)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
LOAD_MSG(X8, X9, X10, X11, SI, 14, 11, 6, 3, 1, 12, 8, 13)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
LOAD_MSG(X8, X9, X10, X11, SI, 2, 6, 0, 8, 12, 10, 11, 3)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
LOAD_MSG(X8, X9, X10, X11, SI, 4, 7, 15, 1, 13, 5, 14, 9)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
LOAD_MSG(X8, X9, X10, X11, SI, 12, 1, 14, 4, 5, 15, 13, 10)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
LOAD_MSG(X8, X9, X10, X11, SI, 0, 6, 9, 8, 7, 3, 2, 11)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
LOAD_MSG(X8, X9, X10, X11, SI, 13, 7, 12, 3, 11, 14, 1, 9)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
LOAD_MSG(X8, X9, X10, X11, SI, 5, 15, 8, 2, 0, 4, 6, 10)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
LOAD_MSG(X8, X9, X10, X11, SI, 6, 14, 11, 0, 15, 9, 3, 8)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
LOAD_MSG(X8, X9, X10, X11, SI, 12, 13, 1, 10, 2, 7, 4, 5)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
LOAD_MSG(X8, X9, X10, X11, SI, 10, 8, 7, 1, 2, 4, 6, 5)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
LOAD_MSG(X8, X9, X10, X11, SI, 15, 9, 3, 13, 11, 14, 12, 0)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, Mem{Base: R10}.Offset(16), Mem{Base: R10}.Offset(32), Mem{Base: R10}.Offset(48), Mem{Base: R10}.Offset(64), X11, X13, X14)
SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, Mem{Base: R10}.Offset(80), Mem{Base: R10}.Offset(96), Mem{Base: R10}.Offset(112), Mem{Base: R10}.Offset(128), X11, X13, X14)
SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, Mem{Base: R10}.Offset(144), Mem{Base: R10}.Offset(160), Mem{Base: R10}.Offset(176), Mem{Base: R10}.Offset(192), X11, X13, X14)
SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, Mem{Base: R10}.Offset(208), Mem{Base: R10}.Offset(224), Mem{Base: R10}.Offset(240), Mem{Base: R10}.Offset(256), X11, X13, X14)
SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
MOVOU(Mem{Base: AX}.Offset(32), X10)
MOVOU(Mem{Base: AX}.Offset(48), X11)
PXOR(X0, X12)
PXOR(X1, X15)
PXOR(X2, X10)
PXOR(X3, X11)
PXOR(X4, X12)
PXOR(X5, X15)
PXOR(X6, X10)
PXOR(X7, X11)
MOVOU(X10, Mem{Base: AX}.Offset(32))
MOVOU(X11, Mem{Base: AX}.Offset(48))
LEAQ(Mem{Base: SI}.Offset(128), RSI)
SUBQ(Imm(128), RDI)
JNE(LabelRef("loop"))
MOVOU(X12, Mem{Base: AX}.Offset(0))
MOVOU(X15, Mem{Base: AX}.Offset(16))
MOVQ(R8, Mem{Base: BX}.Offset(0))
MOVQ(R9, Mem{Base: BX}.Offset(8))
RET()
}
// #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~DATA SECTION~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
func iv0_DATA() Mem {
if iv0_DATA_ptr != nil {
return *iv0_DATA_ptr
}
iv0 := GLOBL(ThatPeskyUnicodeDot+"iv0", NOPTR|RODATA)
iv0_DATA_ptr = &iv0
DATA(0x00, U64(0x6a09e667f3bcc908))
DATA(0x08, U64(0xbb67ae8584caa73b))
return iv0
}
func iv1_DATA() Mem {
if iv1_DATA_ptr != nil {
return *iv1_DATA_ptr
}
iv1 := GLOBL(ThatPeskyUnicodeDot+"iv1", NOPTR|RODATA)
iv1_DATA_ptr = &iv1
DATA(0x00, U64(0x3c6ef372fe94f82b))
DATA(0x08, U64(0xa54ff53a5f1d36f1))
return iv1
}
func iv2_DATA() Mem {
if iv2_DATA_ptr != nil {
return *iv2_DATA_ptr
}
iv2 := GLOBL(ThatPeskyUnicodeDot+"iv2", NOPTR|RODATA)
iv2_DATA_ptr = &iv2
DATA(0x00, U64(0x510e527fade682d1))
DATA(0x08, U64(0x9b05688c2b3e6c1f))
return iv2
}
func iv3_DATA() Mem {
if iv3_DATA_ptr != nil {
return *iv3_DATA_ptr
}
iv3 := GLOBL(ThatPeskyUnicodeDot+"iv3", NOPTR|RODATA)
iv3_DATA_ptr = &iv3
DATA(0x00, U64(0x1f83d9abfb41bd6b))
DATA(0x08, U64(0x5be0cd19137e2179))
return iv3
}
func c40_DATA() Mem {
if c40_DATA_ptr != nil {
return *c40_DATA_ptr
}
c40 := GLOBL(ThatPeskyUnicodeDot+"c40", NOPTR|RODATA)
c40_DATA_ptr = &c40
DATA(0x00, U64(0x0201000706050403))
DATA(0x08, U64(0x0a09080f0e0d0c0b))
return c40
}
func c48_DATA() Mem {
if c48_DATA_ptr != nil {
return *c48_DATA_ptr
}
c48 := GLOBL(ThatPeskyUnicodeDot+"c48", NOPTR|RODATA)
c48_DATA_ptr = &c48
DATA(0x00, U64(0x0100070605040302))
DATA(0x08, U64(0x09080f0e0d0c0b0a))
return c48
}
+15
View File
@@ -0,0 +1,15 @@
module blake2b/_asm
go 1.23
require (
github.com/mmcloughlin/avo v0.6.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.30.0 // indirect
golang.org/x/tools v0.24.0 // indirect
)
+12
View File
@@ -0,0 +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.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.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 -2
View File
@@ -2,8 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build go1.7 && amd64 && gc && !purego
// +build go1.7,amd64,gc,!purego
//go:build amd64 && gc && !purego
package blake2b
+4493 -679
View File
File diff suppressed because it is too large Load Diff
-25
View File
@@ -1,25 +0,0 @@
// Copyright 2016 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.7 && amd64 && gc && !purego
// +build !go1.7,amd64,gc,!purego
package blake2b
import "golang.org/x/sys/cpu"
func init() {
useSSE4 = cpu.X86.HasSSE41
}
//go:noescape
func hashBlocksSSE4(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte)
func hashBlocks(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) {
if useSSE4 {
hashBlocksSSE4(h, c, flag, blocks)
} else {
hashBlocksGeneric(h, c, flag, blocks)
}
}
+1427 -265
View File
File diff suppressed because it is too large Load Diff
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build !amd64 || purego || !gc
// +build !amd64 purego !gc
package blake2b
+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
+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.25
package blake2b
import "hash"
var _ hash.XOF = (*xof)(nil)
-3
View File
@@ -2,9 +2,6 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build go1.9
// +build go1.9
package blake2b
import (
+525
View File
@@ -0,0 +1,525 @@
// Copyright 2024 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 main
import (
. "github.com/mmcloughlin/avo/build"
"github.com/mmcloughlin/avo/ir"
. "github.com/mmcloughlin/avo/operand"
. "github.com/mmcloughlin/avo/reg"
_ "golang.org/x/crypto/blake2s"
)
//go:generate go run . -out ../blake2s_amd64.s -pkg blake2s
func main() {
Package("golang.org/x/crypto/blake2s")
ConstraintExpr("amd64,gc,!purego")
hashBlocksSSE2()
hashBlocksSSSE3()
hashBlocksSSE4()
Generate()
}
func ROTL_SSE2(n uint64, t, v VecPhysical) {
MOVO(v, t)
PSLLL(Imm(n), t)
PSRLL(Imm(32-n), v)
PXOR(t, v)
}
func ROTL_SSSE3(c, v VecPhysical) {
PSHUFB(c, v)
}
func ROUND_SSE2(v0, v1, v2, v3 VecPhysical, m0, m1, m2, m3 Mem, t VecPhysical) {
PADDL(m0, v0)
PADDL(v1, v0)
PXOR(v0, v3)
ROTL_SSE2(16, t, v3)
PADDL(v3, v2)
PXOR(v2, v1)
ROTL_SSE2(20, t, v1)
PADDL(m1, v0)
PADDL(v1, v0)
PXOR(v0, v3)
ROTL_SSE2(24, t, v3)
PADDL(v3, v2)
PXOR(v2, v1)
ROTL_SSE2(25, t, v1)
PSHUFL(Imm(0x39), v1, v1)
PSHUFL(Imm(0x4E), v2, v2)
PSHUFL(Imm(0x93), v3, v3)
PADDL(m2, v0)
PADDL(v1, v0)
PXOR(v0, v3)
ROTL_SSE2(16, t, v3)
PADDL(v3, v2)
PXOR(v2, v1)
ROTL_SSE2(20, t, v1)
PADDL(m3, v0)
PADDL(v1, v0)
PXOR(v0, v3)
ROTL_SSE2(24, t, v3)
PADDL(v3, v2)
PXOR(v2, v1)
ROTL_SSE2(25, t, v1)
PSHUFL(Imm(0x39), v3, v3)
PSHUFL(Imm(0x4E), v2, v2)
PSHUFL(Imm(0x93), v1, v1)
}
func ROUND_SSSE3(v0, v1, v2, v3 VecPhysical, m0, m1, m2, m3 Op, t, c16, c8 VecPhysical) {
PADDL(m0, v0)
PADDL(v1, v0)
PXOR(v0, v3)
ROTL_SSSE3(c16, v3)
PADDL(v3, v2)
PXOR(v2, v1)
ROTL_SSE2(20, t, v1)
PADDL(m1, v0)
PADDL(v1, v0)
PXOR(v0, v3)
ROTL_SSSE3(c8, v3)
PADDL(v3, v2)
PXOR(v2, v1)
ROTL_SSE2(25, t, v1)
PSHUFL(Imm(0x39), v1, v1)
PSHUFL(Imm(0x4E), v2, v2)
PSHUFL(Imm(0x93), v3, v3)
PADDL(m2, v0)
PADDL(v1, v0)
PXOR(v0, v3)
ROTL_SSSE3(c16, v3)
PADDL(v3, v2)
PXOR(v2, v1)
ROTL_SSE2(20, t, v1)
PADDL(m3, v0)
PADDL(v1, v0)
PXOR(v0, v3)
ROTL_SSSE3(c8, v3)
PADDL(v3, v2)
PXOR(v2, v1)
ROTL_SSE2(25, t, v1)
PSHUFL(Imm(0x39), v3, v3)
PSHUFL(Imm(0x4E), v2, v2)
PSHUFL(Imm(0x93), v1, v1)
}
func LOAD_MSG_SSE4(m0, m1, m2, m3 VecPhysical, src GPPhysical, i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, i12, i13, i14, i15 int) {
// Hack to get Avo to emit a MOVL instruction with a VecPhysical as the destination
Instruction(&ir.Instruction{Opcode: "MOVL", Operands: []Op{Mem{Base: src}.Offset(i0 * 4), m0}})
PINSRD(Imm(1), Mem{Base: src}.Offset(i1*4), m0)
PINSRD(Imm(2), Mem{Base: src}.Offset(i2*4), m0)
PINSRD(Imm(3), Mem{Base: src}.Offset(i3*4), m0)
Instruction(&ir.Instruction{Opcode: "MOVL", Operands: []Op{Mem{Base: src}.Offset(i4 * 4), m1}})
PINSRD(Imm(1), Mem{Base: src}.Offset(i5*4), m1)
PINSRD(Imm(2), Mem{Base: src}.Offset(i6*4), m1)
PINSRD(Imm(3), Mem{Base: src}.Offset(i7*4), m1)
Instruction(&ir.Instruction{Opcode: "MOVL", Operands: []Op{Mem{Base: src}.Offset(i8 * 4), m2}})
PINSRD(Imm(1), Mem{Base: src}.Offset(i9*4), m2)
PINSRD(Imm(2), Mem{Base: src}.Offset(i10*4), m2)
PINSRD(Imm(3), Mem{Base: src}.Offset(i11*4), m2)
Instruction(&ir.Instruction{Opcode: "MOVL", Operands: []Op{Mem{Base: src}.Offset(i12 * 4), m3}})
PINSRD(Imm(1), Mem{Base: src}.Offset(i13*4), m3)
PINSRD(Imm(2), Mem{Base: src}.Offset(i14*4), m3)
PINSRD(Imm(3), Mem{Base: src}.Offset(i15*4), m3)
}
func PRECOMPUTE_MSG(dst GPPhysical, off int, src, R8, R9, R10, R11, R12, R13, R14, R15 GPPhysical) {
MOVQ(Mem{Base: src}.Offset(0*4), R8)
MOVQ(Mem{Base: src}.Offset(2*4), R9)
MOVQ(Mem{Base: src}.Offset(4*4), R10)
MOVQ(Mem{Base: src}.Offset(6*4), R11)
MOVQ(Mem{Base: src}.Offset(8*4), R12)
MOVQ(Mem{Base: src}.Offset(10*4), R13)
MOVQ(Mem{Base: src}.Offset(12*4), R14)
MOVQ(Mem{Base: src}.Offset(14*4), R15)
MOVL(R8L, Mem{Base: dst}.Offset(0*4+off+0))
MOVL(R8L, Mem{Base: dst}.Offset(9*4+off+64))
MOVL(R8L, Mem{Base: dst}.Offset(5*4+off+128))
MOVL(R8L, Mem{Base: dst}.Offset(14*4+off+192))
MOVL(R8L, Mem{Base: dst}.Offset(4*4+off+256))
MOVL(R8L, Mem{Base: dst}.Offset(2*4+off+320))
MOVL(R8L, Mem{Base: dst}.Offset(8*4+off+384))
MOVL(R8L, Mem{Base: dst}.Offset(12*4+off+448))
MOVL(R8L, Mem{Base: dst}.Offset(3*4+off+512))
MOVL(R8L, Mem{Base: dst}.Offset(15*4+off+576))
SHRQ(Imm(32), R8)
MOVL(R8L, Mem{Base: dst}.Offset(4*4+off+0))
MOVL(R8L, Mem{Base: dst}.Offset(8*4+off+64))
MOVL(R8L, Mem{Base: dst}.Offset(14*4+off+128))
MOVL(R8L, Mem{Base: dst}.Offset(5*4+off+192))
MOVL(R8L, Mem{Base: dst}.Offset(12*4+off+256))
MOVL(R8L, Mem{Base: dst}.Offset(11*4+off+320))
MOVL(R8L, Mem{Base: dst}.Offset(1*4+off+384))
MOVL(R8L, Mem{Base: dst}.Offset(6*4+off+448))
MOVL(R8L, Mem{Base: dst}.Offset(10*4+off+512))
MOVL(R8L, Mem{Base: dst}.Offset(3*4+off+576))
MOVL(R9L, Mem{Base: dst}.Offset(1*4+off+0))
MOVL(R9L, Mem{Base: dst}.Offset(13*4+off+64))
MOVL(R9L, Mem{Base: dst}.Offset(6*4+off+128))
MOVL(R9L, Mem{Base: dst}.Offset(8*4+off+192))
MOVL(R9L, Mem{Base: dst}.Offset(2*4+off+256))
MOVL(R9L, Mem{Base: dst}.Offset(0*4+off+320))
MOVL(R9L, Mem{Base: dst}.Offset(14*4+off+384))
MOVL(R9L, Mem{Base: dst}.Offset(11*4+off+448))
MOVL(R9L, Mem{Base: dst}.Offset(12*4+off+512))
MOVL(R9L, Mem{Base: dst}.Offset(4*4+off+576))
SHRQ(Imm(32), R9)
MOVL(R9L, Mem{Base: dst}.Offset(5*4+off+0))
MOVL(R9L, Mem{Base: dst}.Offset(15*4+off+64))
MOVL(R9L, Mem{Base: dst}.Offset(9*4+off+128))
MOVL(R9L, Mem{Base: dst}.Offset(1*4+off+192))
MOVL(R9L, Mem{Base: dst}.Offset(11*4+off+256))
MOVL(R9L, Mem{Base: dst}.Offset(7*4+off+320))
MOVL(R9L, Mem{Base: dst}.Offset(13*4+off+384))
MOVL(R9L, Mem{Base: dst}.Offset(3*4+off+448))
MOVL(R9L, Mem{Base: dst}.Offset(6*4+off+512))
MOVL(R9L, Mem{Base: dst}.Offset(10*4+off+576))
MOVL(R10L, Mem{Base: dst}.Offset(2*4+off+0))
MOVL(R10L, Mem{Base: dst}.Offset(1*4+off+64))
MOVL(R10L, Mem{Base: dst}.Offset(15*4+off+128))
MOVL(R10L, Mem{Base: dst}.Offset(10*4+off+192))
MOVL(R10L, Mem{Base: dst}.Offset(6*4+off+256))
MOVL(R10L, Mem{Base: dst}.Offset(8*4+off+320))
MOVL(R10L, Mem{Base: dst}.Offset(3*4+off+384))
MOVL(R10L, Mem{Base: dst}.Offset(13*4+off+448))
MOVL(R10L, Mem{Base: dst}.Offset(14*4+off+512))
MOVL(R10L, Mem{Base: dst}.Offset(5*4+off+576))
SHRQ(Imm(32), R10)
MOVL(R10L, Mem{Base: dst}.Offset(6*4+off+0))
MOVL(R10L, Mem{Base: dst}.Offset(11*4+off+64))
MOVL(R10L, Mem{Base: dst}.Offset(2*4+off+128))
MOVL(R10L, Mem{Base: dst}.Offset(9*4+off+192))
MOVL(R10L, Mem{Base: dst}.Offset(1*4+off+256))
MOVL(R10L, Mem{Base: dst}.Offset(13*4+off+320))
MOVL(R10L, Mem{Base: dst}.Offset(4*4+off+384))
MOVL(R10L, Mem{Base: dst}.Offset(8*4+off+448))
MOVL(R10L, Mem{Base: dst}.Offset(15*4+off+512))
MOVL(R10L, Mem{Base: dst}.Offset(7*4+off+576))
MOVL(R11L, Mem{Base: dst}.Offset(3*4+off+0))
MOVL(R11L, Mem{Base: dst}.Offset(7*4+off+64))
MOVL(R11L, Mem{Base: dst}.Offset(13*4+off+128))
MOVL(R11L, Mem{Base: dst}.Offset(12*4+off+192))
MOVL(R11L, Mem{Base: dst}.Offset(10*4+off+256))
MOVL(R11L, Mem{Base: dst}.Offset(1*4+off+320))
MOVL(R11L, Mem{Base: dst}.Offset(9*4+off+384))
MOVL(R11L, Mem{Base: dst}.Offset(14*4+off+448))
MOVL(R11L, Mem{Base: dst}.Offset(0*4+off+512))
MOVL(R11L, Mem{Base: dst}.Offset(6*4+off+576))
SHRQ(Imm(32), R11)
MOVL(R11L, Mem{Base: dst}.Offset(7*4+off+0))
MOVL(R11L, Mem{Base: dst}.Offset(14*4+off+64))
MOVL(R11L, Mem{Base: dst}.Offset(10*4+off+128))
MOVL(R11L, Mem{Base: dst}.Offset(0*4+off+192))
MOVL(R11L, Mem{Base: dst}.Offset(5*4+off+256))
MOVL(R11L, Mem{Base: dst}.Offset(9*4+off+320))
MOVL(R11L, Mem{Base: dst}.Offset(12*4+off+384))
MOVL(R11L, Mem{Base: dst}.Offset(1*4+off+448))
MOVL(R11L, Mem{Base: dst}.Offset(13*4+off+512))
MOVL(R11L, Mem{Base: dst}.Offset(2*4+off+576))
MOVL(R12L, Mem{Base: dst}.Offset(8*4+off+0))
MOVL(R12L, Mem{Base: dst}.Offset(5*4+off+64))
MOVL(R12L, Mem{Base: dst}.Offset(4*4+off+128))
MOVL(R12L, Mem{Base: dst}.Offset(15*4+off+192))
MOVL(R12L, Mem{Base: dst}.Offset(14*4+off+256))
MOVL(R12L, Mem{Base: dst}.Offset(3*4+off+320))
MOVL(R12L, Mem{Base: dst}.Offset(11*4+off+384))
MOVL(R12L, Mem{Base: dst}.Offset(10*4+off+448))
MOVL(R12L, Mem{Base: dst}.Offset(7*4+off+512))
MOVL(R12L, Mem{Base: dst}.Offset(1*4+off+576))
SHRQ(Imm(32), R12)
MOVL(R12L, Mem{Base: dst}.Offset(12*4+off+0))
MOVL(R12L, Mem{Base: dst}.Offset(2*4+off+64))
MOVL(R12L, Mem{Base: dst}.Offset(11*4+off+128))
MOVL(R12L, Mem{Base: dst}.Offset(4*4+off+192))
MOVL(R12L, Mem{Base: dst}.Offset(0*4+off+256))
MOVL(R12L, Mem{Base: dst}.Offset(15*4+off+320))
MOVL(R12L, Mem{Base: dst}.Offset(10*4+off+384))
MOVL(R12L, Mem{Base: dst}.Offset(7*4+off+448))
MOVL(R12L, Mem{Base: dst}.Offset(5*4+off+512))
MOVL(R12L, Mem{Base: dst}.Offset(9*4+off+576))
MOVL(R13L, Mem{Base: dst}.Offset(9*4+off+0))
MOVL(R13L, Mem{Base: dst}.Offset(4*4+off+64))
MOVL(R13L, Mem{Base: dst}.Offset(8*4+off+128))
MOVL(R13L, Mem{Base: dst}.Offset(13*4+off+192))
MOVL(R13L, Mem{Base: dst}.Offset(3*4+off+256))
MOVL(R13L, Mem{Base: dst}.Offset(5*4+off+320))
MOVL(R13L, Mem{Base: dst}.Offset(7*4+off+384))
MOVL(R13L, Mem{Base: dst}.Offset(15*4+off+448))
MOVL(R13L, Mem{Base: dst}.Offset(11*4+off+512))
MOVL(R13L, Mem{Base: dst}.Offset(0*4+off+576))
SHRQ(Imm(32), R13)
MOVL(R13L, Mem{Base: dst}.Offset(13*4+off+0))
MOVL(R13L, Mem{Base: dst}.Offset(10*4+off+64))
MOVL(R13L, Mem{Base: dst}.Offset(0*4+off+128))
MOVL(R13L, Mem{Base: dst}.Offset(3*4+off+192))
MOVL(R13L, Mem{Base: dst}.Offset(9*4+off+256))
MOVL(R13L, Mem{Base: dst}.Offset(6*4+off+320))
MOVL(R13L, Mem{Base: dst}.Offset(15*4+off+384))
MOVL(R13L, Mem{Base: dst}.Offset(4*4+off+448))
MOVL(R13L, Mem{Base: dst}.Offset(2*4+off+512))
MOVL(R13L, Mem{Base: dst}.Offset(12*4+off+576))
MOVL(R14L, Mem{Base: dst}.Offset(10*4+off+0))
MOVL(R14L, Mem{Base: dst}.Offset(12*4+off+64))
MOVL(R14L, Mem{Base: dst}.Offset(1*4+off+128))
MOVL(R14L, Mem{Base: dst}.Offset(6*4+off+192))
MOVL(R14L, Mem{Base: dst}.Offset(13*4+off+256))
MOVL(R14L, Mem{Base: dst}.Offset(4*4+off+320))
MOVL(R14L, Mem{Base: dst}.Offset(0*4+off+384))
MOVL(R14L, Mem{Base: dst}.Offset(2*4+off+448))
MOVL(R14L, Mem{Base: dst}.Offset(8*4+off+512))
MOVL(R14L, Mem{Base: dst}.Offset(14*4+off+576))
SHRQ(Imm(32), R14)
MOVL(R14L, Mem{Base: dst}.Offset(14*4+off+0))
MOVL(R14L, Mem{Base: dst}.Offset(3*4+off+64))
MOVL(R14L, Mem{Base: dst}.Offset(7*4+off+128))
MOVL(R14L, Mem{Base: dst}.Offset(2*4+off+192))
MOVL(R14L, Mem{Base: dst}.Offset(15*4+off+256))
MOVL(R14L, Mem{Base: dst}.Offset(12*4+off+320))
MOVL(R14L, Mem{Base: dst}.Offset(6*4+off+384))
MOVL(R14L, Mem{Base: dst}.Offset(0*4+off+448))
MOVL(R14L, Mem{Base: dst}.Offset(9*4+off+512))
MOVL(R14L, Mem{Base: dst}.Offset(11*4+off+576))
MOVL(R15L, Mem{Base: dst}.Offset(11*4+off+0))
MOVL(R15L, Mem{Base: dst}.Offset(0*4+off+64))
MOVL(R15L, Mem{Base: dst}.Offset(12*4+off+128))
MOVL(R15L, Mem{Base: dst}.Offset(7*4+off+192))
MOVL(R15L, Mem{Base: dst}.Offset(8*4+off+256))
MOVL(R15L, Mem{Base: dst}.Offset(14*4+off+320))
MOVL(R15L, Mem{Base: dst}.Offset(2*4+off+384))
MOVL(R15L, Mem{Base: dst}.Offset(5*4+off+448))
MOVL(R15L, Mem{Base: dst}.Offset(1*4+off+512))
MOVL(R15L, Mem{Base: dst}.Offset(13*4+off+576))
SHRQ(Imm(32), R15)
MOVL(R15L, Mem{Base: dst}.Offset(15*4+off+0))
MOVL(R15L, Mem{Base: dst}.Offset(6*4+off+64))
MOVL(R15L, Mem{Base: dst}.Offset(3*4+off+128))
MOVL(R15L, Mem{Base: dst}.Offset(11*4+off+192))
MOVL(R15L, Mem{Base: dst}.Offset(7*4+off+256))
MOVL(R15L, Mem{Base: dst}.Offset(10*4+off+320))
MOVL(R15L, Mem{Base: dst}.Offset(5*4+off+384))
MOVL(R15L, Mem{Base: dst}.Offset(9*4+off+448))
MOVL(R15L, Mem{Base: dst}.Offset(4*4+off+512))
MOVL(R15L, Mem{Base: dst}.Offset(8*4+off+576))
}
func BLAKE2s_SSE2() {
PRECOMPUTE_MSG(BP, 16, SI, R8, R9, R10, R11, R12, R13, R14, R15)
for i := 0; i < 10; i++ {
ROUND_SSE2(X4, X5, X6, X7, Mem{Base: BP}.Offset(16+64*i), Mem{Base: BP}.Offset(32+64*i), Mem{Base: BP}.Offset(48+64*i), Mem{Base: BP}.Offset(64+64*i), X8)
}
}
func BLAKE2s_SSSE3() {
PRECOMPUTE_MSG(BP, 16, SI, R8, R9, R10, R11, R12, R13, R14, R15)
for i := 0; i < 10; i++ {
ROUND_SSSE3(X4, X5, X6, X7, Mem{Base: BP}.Offset(16+64*i), Mem{Base: BP}.Offset(32+64*i), Mem{Base: BP}.Offset(48+64*i), Mem{Base: BP}.Offset(64+64*i), X8, X13, X14)
}
}
func BLAKE2s_SSE4() {
LOAD_MSG_SSE4(X8, X9, X10, X11, SI, 0, 2, 4, 6, 1, 3, 5, 7, 8, 10, 12, 14, 9, 11, 13, 15)
ROUND_SSSE3(X4, X5, X6, X7, X8, X9, X10, X11, X8, X13, X14)
LOAD_MSG_SSE4(X8, X9, X10, X11, SI, 14, 4, 9, 13, 10, 8, 15, 6, 1, 0, 11, 5, 12, 2, 7, 3)
ROUND_SSSE3(X4, X5, X6, X7, X8, X9, X10, X11, X8, X13, X14)
LOAD_MSG_SSE4(X8, X9, X10, X11, SI, 11, 12, 5, 15, 8, 0, 2, 13, 10, 3, 7, 9, 14, 6, 1, 4)
ROUND_SSSE3(X4, X5, X6, X7, X8, X9, X10, X11, X8, X13, X14)
LOAD_MSG_SSE4(X8, X9, X10, X11, SI, 7, 3, 13, 11, 9, 1, 12, 14, 2, 5, 4, 15, 6, 10, 0, 8)
ROUND_SSSE3(X4, X5, X6, X7, X8, X9, X10, X11, X8, X13, X14)
LOAD_MSG_SSE4(X8, X9, X10, X11, SI, 9, 5, 2, 10, 0, 7, 4, 15, 14, 11, 6, 3, 1, 12, 8, 13)
ROUND_SSSE3(X4, X5, X6, X7, X8, X9, X10, X11, X8, X13, X14)
LOAD_MSG_SSE4(X8, X9, X10, X11, SI, 2, 6, 0, 8, 12, 10, 11, 3, 4, 7, 15, 1, 13, 5, 14, 9)
ROUND_SSSE3(X4, X5, X6, X7, X8, X9, X10, X11, X8, X13, X14)
LOAD_MSG_SSE4(X8, X9, X10, X11, SI, 12, 1, 14, 4, 5, 15, 13, 10, 0, 6, 9, 8, 7, 3, 2, 11)
ROUND_SSSE3(X4, X5, X6, X7, X8, X9, X10, X11, X8, X13, X14)
LOAD_MSG_SSE4(X8, X9, X10, X11, SI, 13, 7, 12, 3, 11, 14, 1, 9, 5, 15, 8, 2, 0, 4, 6, 10)
ROUND_SSSE3(X4, X5, X6, X7, X8, X9, X10, X11, X8, X13, X14)
LOAD_MSG_SSE4(X8, X9, X10, X11, SI, 6, 14, 11, 0, 15, 9, 3, 8, 12, 13, 1, 10, 2, 7, 4, 5)
ROUND_SSSE3(X4, X5, X6, X7, X8, X9, X10, X11, X8, X13, X14)
LOAD_MSG_SSE4(X8, X9, X10, X11, SI, 10, 8, 7, 1, 2, 4, 6, 5, 15, 9, 3, 13, 11, 14, 12, 0)
ROUND_SSSE3(X4, X5, X6, X7, X8, X9, X10, X11, X8, X13, X14)
}
func HASH_BLOCKS(h, c, flag, blocks_base, blocks_len Mem, BLAKE2s_FUNC func()) {
MOVQ(h, RAX)
MOVQ(c, RBX)
MOVL(flag, ECX)
MOVQ(blocks_base, RSI)
MOVQ(blocks_len, RDX)
MOVQ(RSP, RBP)
ADDQ(Imm(15), RBP)
ANDQ(I32(^15), RBP)
MOVQ(Mem{Base: BX}.Offset(0), R9)
MOVQ(R9, Mem{Base: BP}.Offset(0))
MOVQ(RCX, Mem{Base: BP}.Offset(8))
MOVOU(Mem{Base: AX}.Offset(0), X0)
MOVOU(Mem{Base: AX}.Offset(16), X1)
iv0 := iv0_DATA()
iv1 := iv1_DATA()
MOVOU(iv0, X2)
MOVOU(iv1, X3)
counter := counter_DATA()
rol16 := rol16_DATA()
rol8 := rol8_DATA()
MOVOU(counter, X12)
MOVOU(rol16, X13)
MOVOU(rol8, X14)
MOVO(Mem{Base: BP}.Offset(0), X15)
Label("loop")
MOVO(X0, X4)
MOVO(X1, X5)
MOVO(X2, X6)
MOVO(X3, X7)
PADDQ(X12, X15)
PXOR(X15, X7)
BLAKE2s_FUNC()
PXOR(X4, X0)
PXOR(X5, X1)
PXOR(X6, X0)
PXOR(X7, X1)
LEAQ(Mem{Base: SI}.Offset(64), RSI)
SUBQ(Imm(64), RDX)
JNE(LabelRef("loop"))
MOVO(X15, Mem{Base: BP}.Offset(0))
MOVQ(Mem{Base: BP}.Offset(0), R9)
MOVQ(R9, Mem{Base: BX}.Offset(0))
MOVOU(X0, Mem{Base: AX}.Offset(0))
MOVOU(X1, Mem{Base: AX}.Offset(16))
}
func hashBlocksSSE2() {
Implement("hashBlocksSSE2")
Attributes(0)
AllocLocal(672) // frame = 656 + 16 byte alignment
h := NewParamAddr("h", 0)
c := NewParamAddr("c", 8)
flag := NewParamAddr("flag", 16)
blocks_base := NewParamAddr("blocks_base", 24)
blocks_len := NewParamAddr("blocks_len", 32)
HASH_BLOCKS(h, c, flag, blocks_base, blocks_len, BLAKE2s_SSE2)
RET()
}
func hashBlocksSSSE3() {
Implement("hashBlocksSSSE3")
Attributes(0)
AllocLocal(672) // frame = 656 + 16 byte alignment
h := NewParamAddr("h", 0)
c := NewParamAddr("c", 8)
flag := NewParamAddr("flag", 16)
blocks_base := NewParamAddr("blocks_base", 24)
blocks_len := NewParamAddr("blocks_len", 32)
HASH_BLOCKS(h, c, flag, blocks_base, blocks_len, BLAKE2s_SSSE3)
RET()
}
func hashBlocksSSE4() {
Implement("hashBlocksSSE4")
Attributes(0)
AllocLocal(32) // frame = 16 + 16 byte alignment
h := NewParamAddr("h", 0)
c := NewParamAddr("c", 8)
flag := NewParamAddr("flag", 16)
blocks_base := NewParamAddr("blocks_base", 24)
blocks_len := NewParamAddr("blocks_len", 32)
HASH_BLOCKS(h, c, flag, blocks_base, blocks_len, BLAKE2s_SSE4)
RET()
}
// ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~DATA SECTION~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
var iv0_DATA_ptr, iv1_DATA_ptr, rol16_DATA_ptr, rol8_DATA_ptr, counter_DATA_ptr *Mem
func iv0_DATA() Mem {
if iv0_DATA_ptr != nil {
return *iv0_DATA_ptr
}
iv0_DATA := GLOBL("iv0", NOPTR|RODATA)
iv0_DATA_ptr = &iv0_DATA
DATA(0x00, U32(0x6a09e667))
DATA(0x04, U32(0xbb67ae85))
DATA(0x08, U32(0x3c6ef372))
DATA(0x0c, U32(0xa54ff53a))
return iv0_DATA
}
func iv1_DATA() Mem {
if iv1_DATA_ptr != nil {
return *iv1_DATA_ptr
}
iv1_DATA := GLOBL("iv1", NOPTR|RODATA)
iv1_DATA_ptr = &iv1_DATA
DATA(0x00, U32(0x510e527f))
DATA(0x04, U32(0x9b05688c))
DATA(0x08, U32(0x1f83d9ab))
DATA(0x0c, U32(0x5be0cd19))
return iv1_DATA
}
func rol16_DATA() Mem {
if rol16_DATA_ptr != nil {
return *rol16_DATA_ptr
}
rol16_DATA := GLOBL("rol16", NOPTR|RODATA)
rol16_DATA_ptr = &rol16_DATA
DATA(0x00, U64(0x0504070601000302))
DATA(0x08, U64(0x0D0C0F0E09080B0A))
return rol16_DATA
}
func rol8_DATA() Mem {
if rol8_DATA_ptr != nil {
return *rol8_DATA_ptr
}
rol8_DATA := GLOBL("rol8", NOPTR|RODATA)
rol8_DATA_ptr = &rol8_DATA
DATA(0x00, U64(0x0407060500030201))
DATA(0x08, U64(0x0C0F0E0D080B0A09))
return rol8_DATA
}
func counter_DATA() Mem {
if counter_DATA_ptr != nil {
return *counter_DATA_ptr
}
counter_DATA := GLOBL("counter", NOPTR|RODATA)
counter_DATA_ptr = &counter_DATA
DATA(0x00, U64(0x0000000000000040))
DATA(0x08, U64(0x0000000000000000))
return counter_DATA
}
+15
View File
@@ -0,0 +1,15 @@
module blake2s/_asm
go 1.23
require (
github.com/mmcloughlin/avo v0.6.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.30.0 // indirect
golang.org/x/tools v0.24.0 // indirect
)
+12
View File
@@ -0,0 +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.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.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=
+9 -1
View File
@@ -16,9 +16,10 @@
//
// BLAKE2X is a construction to compute hash values larger than 32 bytes. It
// can produce hash values between 0 and 65535 bytes.
package blake2s // import "golang.org/x/crypto/blake2s"
package blake2s
import (
"crypto"
"encoding/binary"
"errors"
"hash"
@@ -55,6 +56,13 @@ func Sum256(data []byte) [Size]byte {
// and BinaryUnmarshaler for state (de)serialization as documented by hash.Hash.
func New256(key []byte) (hash.Hash, error) { return newDigest(Size, key) }
func init() {
crypto.RegisterHash(crypto.BLAKE2s_256, func() hash.Hash {
h, _ := New256(nil)
return h
})
}
// New128 returns a new hash.Hash computing the BLAKE2s-128 checksum given a
// non-empty key. Note that a 128-bit digest is too small to be secure as a
// cryptographic hash and should only be used as a MAC, thus the key argument
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build 386 && gc && !purego
// +build 386,gc,!purego
package blake2s
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build 386 && gc && !purego
// +build 386,gc,!purego
#include "textflag.h"
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build amd64 && gc && !purego
// +build amd64,gc,!purego
package blake2s
+2160 -420
View File
File diff suppressed because it is too large Load Diff
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build (!amd64 && !386) || !gc || purego
// +build !amd64,!386 !gc purego
package blake2s
-22
View File
@@ -1,22 +0,0 @@
// Copyright 2017 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.9
// +build go1.9
package blake2s
import (
"crypto"
"hash"
)
func init() {
newHash256 := func() hash.Hash {
h, _ := New256(nil)
return h
}
crypto.RegisterHash(crypto.BLAKE2s_256, newHash256)
}
+1 -1
View File
@@ -11,7 +11,7 @@
// Deprecated: any new system should use AES (from crypto/aes, if necessary in
// an AEAD mode like crypto/cipher.NewGCM) or XChaCha20-Poly1305 (from
// golang.org/x/crypto/chacha20poly1305).
package blowfish // import "golang.org/x/crypto/blowfish"
package blowfish
// The code is a port of Bruce Schneier's C implementation.
// See https://www.schneier.com/blowfish.html.
+1 -1
View File
@@ -23,7 +23,7 @@
// elliptic curve. This package is frozen, and not implemented in constant time.
// There is a more complete implementation at github.com/cloudflare/bn256, but
// note that it suffers from the same security issues of the underlying curve.
package bn256 // import "golang.org/x/crypto/bn256"
package bn256
import (
"crypto/rand"
+1 -1
View File
@@ -5,7 +5,7 @@
package bn256
// For details of the algorithms used, see "Multiplication and Squaring on
// Pairing-Friendly Fields, Devegili et al.
// Pairing-Friendly Fields", Devegili et al.
// http://eprint.iacr.org/2006/471.pdf.
import (
+1 -1
View File
@@ -5,7 +5,7 @@
package bn256
// For details of the algorithms used, see "Multiplication and Squaring on
// Pairing-Friendly Fields, Devegili et al.
// Pairing-Friendly Fields", Devegili et al.
// http://eprint.iacr.org/2006/471.pdf.
import (
+1 -1
View File
@@ -5,7 +5,7 @@
package bn256
// For details of the algorithms used, see "Multiplication and Squaring on
// Pairing-Friendly Fields, Devegili et al.
// Pairing-Friendly Fields", Devegili et al.
// http://eprint.iacr.org/2006/471.pdf.
import (
+1 -1
View File
@@ -11,7 +11,7 @@
// Deprecated: any new system should use AES (from crypto/aes, if necessary in
// an AEAD mode like crypto/cipher.NewGCM) or XChaCha20-Poly1305 (from
// golang.org/x/crypto/chacha20poly1305).
package cast5 // import "golang.org/x/crypto/cast5"
package cast5
import (
"errors"
+1 -2
View File
@@ -2,8 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build go1.11 && gc && !purego
// +build go1.11,gc,!purego
//go:build gc && !purego
package chacha20
+2 -3
View File
@@ -2,8 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build go1.11 && gc && !purego
// +build go1.11,gc,!purego
//go:build gc && !purego
#include "textflag.h"
@@ -30,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
+1 -2
View File
@@ -2,8 +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 && !ppc64le) || (arm64 && !go1.11) || !gc || purego
// +build !arm64,!s390x,!ppc64le arm64,!go1.11 !gc purego
//go:build (!arm64 && !s390x && !ppc64 && !ppc64le) || !gc || purego
package chacha20
@@ -2,8 +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
// +build gc,!purego
//go:build gc && !purego && (ppc64 || ppc64le)
package chacha20
@@ -19,8 +19,7 @@
// The differences in this and the original implementation are
// due to the calling conventions and initialization of constants.
//go:build gc && !purego
// +build gc,!purego
//go:build gc && !purego && (ppc64 || ppc64le)
#include "textflag.h"
@@ -34,27 +33,70 @@
#define CONSTBASE R16
#define BLOCKS R17
DATA consts<>+0x00(SB)/8, $0x3320646e61707865
DATA consts<>+0x08(SB)/8, $0x6b20657479622d32
DATA consts<>+0x10(SB)/8, $0x0000000000000001
DATA consts<>+0x18(SB)/8, $0x0000000000000000
DATA consts<>+0x20(SB)/8, $0x0000000000000004
DATA consts<>+0x28(SB)/8, $0x0000000000000000
DATA consts<>+0x30(SB)/8, $0x0a0b08090e0f0c0d
DATA consts<>+0x38(SB)/8, $0x0203000106070405
DATA consts<>+0x40(SB)/8, $0x090a0b080d0e0f0c
DATA consts<>+0x48(SB)/8, $0x0102030005060704
DATA consts<>+0x50(SB)/8, $0x6170786561707865
DATA consts<>+0x58(SB)/8, $0x6170786561707865
DATA consts<>+0x60(SB)/8, $0x3320646e3320646e
DATA consts<>+0x68(SB)/8, $0x3320646e3320646e
DATA consts<>+0x70(SB)/8, $0x79622d3279622d32
DATA consts<>+0x78(SB)/8, $0x79622d3279622d32
DATA consts<>+0x80(SB)/8, $0x6b2065746b206574
DATA consts<>+0x88(SB)/8, $0x6b2065746b206574
DATA consts<>+0x90(SB)/8, $0x0000000100000000
DATA consts<>+0x98(SB)/8, $0x0000000300000002
GLOBL consts<>(SB), RODATA, $0xa0
// for VPERMXOR
#define MASK R18
DATA consts<>+0x00(SB)/4, $0x61707865
DATA consts<>+0x04(SB)/4, $0x3320646e
DATA consts<>+0x08(SB)/4, $0x79622d32
DATA consts<>+0x0c(SB)/4, $0x6b206574
DATA consts<>+0x10(SB)/4, $0x00000001
DATA consts<>+0x14(SB)/4, $0x00000000
DATA consts<>+0x18(SB)/4, $0x00000000
DATA consts<>+0x1c(SB)/4, $0x00000000
DATA consts<>+0x20(SB)/4, $0x00000004
DATA consts<>+0x24(SB)/4, $0x00000000
DATA consts<>+0x28(SB)/4, $0x00000000
DATA consts<>+0x2c(SB)/4, $0x00000000
DATA consts<>+0x30(SB)/4, $0x0e0f0c0d
DATA consts<>+0x34(SB)/4, $0x0a0b0809
DATA consts<>+0x38(SB)/4, $0x06070405
DATA consts<>+0x3c(SB)/4, $0x02030001
DATA consts<>+0x40(SB)/4, $0x0d0e0f0c
DATA consts<>+0x44(SB)/4, $0x090a0b08
DATA consts<>+0x48(SB)/4, $0x05060704
DATA consts<>+0x4c(SB)/4, $0x01020300
DATA consts<>+0x50(SB)/4, $0x61707865
DATA consts<>+0x54(SB)/4, $0x61707865
DATA consts<>+0x58(SB)/4, $0x61707865
DATA consts<>+0x5c(SB)/4, $0x61707865
DATA consts<>+0x60(SB)/4, $0x3320646e
DATA consts<>+0x64(SB)/4, $0x3320646e
DATA consts<>+0x68(SB)/4, $0x3320646e
DATA consts<>+0x6c(SB)/4, $0x3320646e
DATA consts<>+0x70(SB)/4, $0x79622d32
DATA consts<>+0x74(SB)/4, $0x79622d32
DATA consts<>+0x78(SB)/4, $0x79622d32
DATA consts<>+0x7c(SB)/4, $0x79622d32
DATA consts<>+0x80(SB)/4, $0x6b206574
DATA consts<>+0x84(SB)/4, $0x6b206574
DATA consts<>+0x88(SB)/4, $0x6b206574
DATA consts<>+0x8c(SB)/4, $0x6b206574
DATA consts<>+0x90(SB)/4, $0x00000000
DATA consts<>+0x94(SB)/4, $0x00000001
DATA consts<>+0x98(SB)/4, $0x00000002
DATA consts<>+0x9c(SB)/4, $0x00000003
DATA consts<>+0xa0(SB)/4, $0x11223300
DATA consts<>+0xa4(SB)/4, $0x55667744
DATA consts<>+0xa8(SB)/4, $0x99aabb88
DATA consts<>+0xac(SB)/4, $0xddeeffcc
DATA consts<>+0xb0(SB)/4, $0x22330011
DATA consts<>+0xb4(SB)/4, $0x66774455
DATA consts<>+0xb8(SB)/4, $0xaabb8899
DATA consts<>+0xbc(SB)/4, $0xeeffccdd
GLOBL consts<>(SB), RODATA, $0xc0
#ifdef GOARCH_ppc64
#define BE_XXBRW_INIT() \
LVSL (R0)(R0), V24 \
VSPLTISB $3, V25 \
VXOR V24, V25, V24 \
#define BE_XXBRW(vr) VPERM vr, vr, V24, vr
#else
#define BE_XXBRW_INIT()
#define BE_XXBRW(vr)
#endif
//func chaCha20_ctr32_vsx(out, inp *byte, len int, key *[8]uint32, counter *uint32)
TEXT ·chaCha20_ctr32_vsx(SB),NOSPLIT,$64-40
@@ -71,6 +113,9 @@ TEXT ·chaCha20_ctr32_vsx(SB),NOSPLIT,$64-40
MOVD $48, R10
MOVD $64, R11
SRD $6, LEN, BLOCKS
// for VPERMXOR
MOVD $consts<>+0xa0(SB), MASK
MOVD $16, R20
// V16
LXVW4X (CONSTBASE)(R0), VS48
ADD $80,CONSTBASE
@@ -85,9 +130,15 @@ TEXT ·chaCha20_ctr32_vsx(SB),NOSPLIT,$64-40
// Clear V27
VXOR V27, V27, V27
BE_XXBRW_INIT()
// V28
LXVW4X (CONSTBASE)(R11), VS60
// Load mask constants for VPERMXOR
LXVW4X (MASK)(R0), V20
LXVW4X (MASK)(R20), V21
// splat slot from V19 -> V26
VSPLTW $0, V19, V26
@@ -98,7 +149,7 @@ TEXT ·chaCha20_ctr32_vsx(SB),NOSPLIT,$64-40
MOVD $10, R14
MOVD R14, CTR
PCALIGN $16
loop_outer_vsx:
// V0, V1, V2, V3
LXVW4X (R0)(CONSTBASE), VS32
@@ -129,22 +180,17 @@ loop_outer_vsx:
VSPLTISW $12, V28
VSPLTISW $8, V29
VSPLTISW $7, V30
PCALIGN $16
loop_vsx:
VADDUWM V0, V4, V0
VADDUWM V1, V5, V1
VADDUWM V2, V6, V2
VADDUWM V3, V7, V3
VXOR V12, V0, V12
VXOR V13, V1, V13
VXOR V14, V2, V14
VXOR V15, V3, V15
VRLW V12, V27, V12
VRLW V13, V27, V13
VRLW V14, V27, V14
VRLW V15, V27, V15
VPERMXOR V12, V0, V21, V12
VPERMXOR V13, V1, V21, V13
VPERMXOR V14, V2, V21, V14
VPERMXOR V15, V3, V21, V15
VADDUWM V8, V12, V8
VADDUWM V9, V13, V9
@@ -166,15 +212,10 @@ loop_vsx:
VADDUWM V2, V6, V2
VADDUWM V3, V7, V3
VXOR V12, V0, V12
VXOR V13, V1, V13
VXOR V14, V2, V14
VXOR V15, V3, V15
VRLW V12, V29, V12
VRLW V13, V29, V13
VRLW V14, V29, V14
VRLW V15, V29, V15
VPERMXOR V12, V0, V20, V12
VPERMXOR V13, V1, V20, V13
VPERMXOR V14, V2, V20, V14
VPERMXOR V15, V3, V20, V15
VADDUWM V8, V12, V8
VADDUWM V9, V13, V9
@@ -196,15 +237,10 @@ loop_vsx:
VADDUWM V2, V7, V2
VADDUWM V3, V4, V3
VXOR V15, V0, V15
VXOR V12, V1, V12
VXOR V13, V2, V13
VXOR V14, V3, V14
VRLW V15, V27, V15
VRLW V12, V27, V12
VRLW V13, V27, V13
VRLW V14, V27, V14
VPERMXOR V15, V0, V21, V15
VPERMXOR V12, V1, V21, V12
VPERMXOR V13, V2, V21, V13
VPERMXOR V14, V3, V21, V14
VADDUWM V10, V15, V10
VADDUWM V11, V12, V11
@@ -226,15 +262,10 @@ loop_vsx:
VADDUWM V2, V7, V2
VADDUWM V3, V4, V3
VXOR V15, V0, V15
VXOR V12, V1, V12
VXOR V13, V2, V13
VXOR V14, V3, V14
VRLW V15, V29, V15
VRLW V12, V29, V12
VRLW V13, V29, V13
VRLW V14, V29, V14
VPERMXOR V15, V0, V20, V15
VPERMXOR V12, V1, V20, V12
VPERMXOR V13, V2, V20, V13
VPERMXOR V14, V3, V20, V14
VADDUWM V10, V15, V10
VADDUWM V11, V12, V11
@@ -250,48 +281,48 @@ loop_vsx:
VRLW V6, V30, V6
VRLW V7, V30, V7
VRLW V4, V30, V4
BC 16, LT, loop_vsx
BDNZ loop_vsx
VADDUWM V12, V26, V12
WORD $0x13600F8C // VMRGEW V0, V1, V27
WORD $0x13821F8C // VMRGEW V2, V3, V28
VMRGEW V0, V1, V27
VMRGEW V2, V3, V28
WORD $0x10000E8C // VMRGOW V0, V1, V0
WORD $0x10421E8C // VMRGOW V2, V3, V2
VMRGOW V0, V1, V0
VMRGOW V2, V3, V2
WORD $0x13A42F8C // VMRGEW V4, V5, V29
WORD $0x13C63F8C // VMRGEW V6, V7, V30
VMRGEW V4, V5, V29
VMRGEW V6, V7, V30
XXPERMDI VS32, VS34, $0, VS33
XXPERMDI VS32, VS34, $3, VS35
XXPERMDI VS59, VS60, $0, VS32
XXPERMDI VS59, VS60, $3, VS34
WORD $0x10842E8C // VMRGOW V4, V5, V4
WORD $0x10C63E8C // VMRGOW V6, V7, V6
VMRGOW V4, V5, V4
VMRGOW V6, V7, V6
WORD $0x13684F8C // VMRGEW V8, V9, V27
WORD $0x138A5F8C // VMRGEW V10, V11, V28
VMRGEW V8, V9, V27
VMRGEW V10, V11, V28
XXPERMDI VS36, VS38, $0, VS37
XXPERMDI VS36, VS38, $3, VS39
XXPERMDI VS61, VS62, $0, VS36
XXPERMDI VS61, VS62, $3, VS38
WORD $0x11084E8C // VMRGOW V8, V9, V8
WORD $0x114A5E8C // VMRGOW V10, V11, V10
VMRGOW V8, V9, V8
VMRGOW V10, V11, V10
WORD $0x13AC6F8C // VMRGEW V12, V13, V29
WORD $0x13CE7F8C // VMRGEW V14, V15, V30
VMRGEW V12, V13, V29
VMRGEW V14, V15, V30
XXPERMDI VS40, VS42, $0, VS41
XXPERMDI VS40, VS42, $3, VS43
XXPERMDI VS59, VS60, $0, VS40
XXPERMDI VS59, VS60, $3, VS42
WORD $0x118C6E8C // VMRGOW V12, V13, V12
WORD $0x11CE7E8C // VMRGOW V14, V15, V14
VMRGOW V12, V13, V12
VMRGOW V14, V15, V14
VSPLTISW $4, V27
VADDUWM V26, V27, V26
@@ -306,6 +337,11 @@ loop_vsx:
VADDUWM V8, V18, V8
VADDUWM V12, V19, V12
BE_XXBRW(V0)
BE_XXBRW(V4)
BE_XXBRW(V8)
BE_XXBRW(V12)
CMPU LEN, $64
BLT tail_vsx
@@ -334,6 +370,11 @@ loop_vsx:
VADDUWM V9, V18, V8
VADDUWM V13, V19, V12
BE_XXBRW(V0)
BE_XXBRW(V4)
BE_XXBRW(V8)
BE_XXBRW(V12)
CMPU LEN, $64
BLT tail_vsx
@@ -341,8 +382,8 @@ loop_vsx:
LXVW4X (INP)(R8), VS60
LXVW4X (INP)(R9), VS61
LXVW4X (INP)(R10), VS62
VXOR V27, V0, V27
VXOR V27, V0, V27
VXOR V28, V4, V28
VXOR V29, V8, V29
VXOR V30, V12, V30
@@ -361,6 +402,11 @@ loop_vsx:
VADDUWM V10, V18, V8
VADDUWM V14, V19, V12
BE_XXBRW(V0)
BE_XXBRW(V4)
BE_XXBRW(V8)
BE_XXBRW(V12)
CMPU LEN, $64
BLT tail_vsx
@@ -388,6 +434,11 @@ loop_vsx:
VADDUWM V11, V18, V8
VADDUWM V15, V19, V12
BE_XXBRW(V0)
BE_XXBRW(V4)
BE_XXBRW(V8)
BE_XXBRW(V12)
CMPU LEN, $64
BLT tail_vsx
@@ -415,9 +466,9 @@ loop_vsx:
done_vsx:
// Increment counter by number of 64 byte blocks
MOVD (CNT), R14
MOVWZ (CNT), R14
ADD BLOCKS, R14
MOVD R14, (CNT)
MOVWZ R14, (CNT)
RET
tail_vsx:
@@ -432,7 +483,7 @@ tail_vsx:
ADD $-1, R11, R12
ADD $-1, INP
ADD $-1, OUT
PCALIGN $16
looptail_vsx:
// Copying the result to OUT
// in bytes.
@@ -440,7 +491,7 @@ looptail_vsx:
MOVBZU 1(INP), TMP
XOR KEY, TMP, KEY
MOVBU KEY, 1(OUT)
BC 16, LT, looptail_vsx
BDNZ looptail_vsx
// Clear the stack values
STXVW4X VS48, (R11)(R0)
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build gc && !purego
// +build gc,!purego
package chacha20
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build gc && !purego
// +build gc,!purego
#include "go_asm.h"
#include "textflag.h"
File diff suppressed because it is too large Load Diff
+15
View File
@@ -0,0 +1,15 @@
module chacha20poly1305/_asm
go 1.23
require (
github.com/mmcloughlin/avo v0.6.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.30.0 // indirect
golang.org/x/tools v0.24.0 // indirect
)
+12
View File
@@ -0,0 +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.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.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
@@ -5,7 +5,7 @@
// Package chacha20poly1305 implements the ChaCha20-Poly1305 AEAD and its
// extended nonce variant XChaCha20-Poly1305, as specified in RFC 8439 and
// draft-irtf-cfrg-xchacha-01.
package chacha20poly1305 // import "golang.org/x/crypto/chacha20poly1305"
package chacha20poly1305
import (
"crypto/cipher"
+8 -3
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build gc && !purego
// +build gc,!purego
package chacha20poly1305
@@ -57,7 +56,10 @@ 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
@@ -74,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 {
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build !amd64 || !gc || purego
// +build !amd64 !gc purego
package chacha20poly1305
+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)
})
}
}
+16 -7
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))
@@ -431,6 +431,14 @@ func (s *String) readBase128Int(out *int) bool {
}
ret <<= 7
b := s.read(1)[0]
// ITU-T X.690, section 8.19.2:
// The subidentifier shall be encoded in the fewest possible octets,
// that is, the leading octet of the subidentifier shall not have the value 0x80.
if i == 0 && b == 0x80 {
return false
}
ret |= int(b & 0x7f)
if b&0x80 == 0 {
*out = ret
@@ -725,13 +733,14 @@ func (s *String) ReadOptionalASN1OctetString(out *[]byte, outPresent *bool, tag
return true
}
// ReadOptionalASN1Boolean sets *out to the value of the next ASN.1 BOOLEAN or,
// if the next bytes are not an ASN.1 BOOLEAN, to the value of defaultValue.
// It reports whether the operation was successful.
func (s *String) ReadOptionalASN1Boolean(out *bool, defaultValue bool) bool {
// ReadOptionalASN1Boolean attempts to read an optional ASN.1 BOOLEAN
// explicitly tagged with tag into out and advances. If no element with a
// matching tag is present, it sets "out" to defaultValue instead. It reports
// whether the read was successful.
func (s *String) ReadOptionalASN1Boolean(out *bool, tag asn1.Tag, defaultValue bool) bool {
var present bool
var child String
if !s.ReadOptionalASN1(&child, &present, asn1.BOOLEAN) {
if !s.ReadOptionalASN1(&child, &present, tag) {
return false
}
@@ -740,7 +749,7 @@ func (s *String) ReadOptionalASN1Boolean(out *bool, defaultValue bool) bool {
return true
}
return s.ReadASN1Boolean(out)
return child.ReadASN1Boolean(out)
}
func (s *String) readASN1(out *String, outTag *asn1.Tag, skipHeader bool) bool {
+1 -1
View File
@@ -4,7 +4,7 @@
// Package asn1 contains supporting types for parsing and building ASN.1
// messages with the cryptobyte package.
package asn1 // import "golang.org/x/crypto/cryptobyte/asn1"
package asn1
// Tag represents an ASN.1 identifier octet, consisting of a tag number
// (indicating a type) and class (such as context-specific or constructed).
+23
View File
@@ -115,6 +115,28 @@ func TestReadASN1OptionalInteger(t *testing.T) {
}
}
const defaultBool = false
var optionalBoolTestData = []readASN1Test{
{"empty", []byte{}, 0xa0, true, false},
{"invalid", []byte{0xa1, 0x3, 0x1, 0x2, 0x7f}, 0xa1, false, defaultBool},
{"missing", []byte{0xa1, 0x3, 0x1, 0x1, 0x7f}, 0xa0, true, defaultBool},
{"present", []byte{0xa1, 0x3, 0x1, 0x1, 0xff}, 0xa1, true, true},
}
func TestReadASN1OptionalBoolean(t *testing.T) {
for _, test := range optionalBoolTestData {
t.Run(test.name, func(t *testing.T) {
in := String(test.in)
var out bool
ok := in.ReadOptionalASN1Boolean(&out, test.tag, defaultBool)
if ok != test.ok || ok && out != test.out.(bool) {
t.Errorf("in.ReadOptionalASN1Boolean() = %v, want %v; out = %v, want %v", ok, test.ok, out, test.out)
}
})
}
}
func TestReadASN1IntegerSigned(t *testing.T) {
testData64 := []struct {
in []byte
@@ -276,6 +298,7 @@ func TestASN1ObjectIdentifier(t *testing.T) {
{[]byte{6, 7, 85, 0x02, 0x85, 0xc7, 0xcc, 0xfb, 0x01}, true, []int{2, 5, 2, 1492336001}},
{[]byte{6, 7, 0x55, 0x02, 0x87, 0xff, 0xff, 0xff, 0x7f}, true, []int{2, 5, 2, 2147483647}}, // 2**31-1
{[]byte{6, 7, 0x55, 0x02, 0x88, 0x80, 0x80, 0x80, 0x00}, false, []int{}}, // 2**31
{[]byte{6, 3, 85, 0x80, 0x02}, false, []int{}}, // leading 0x80 octet
}
for i, test := range testData {
+5
View File
@@ -95,6 +95,11 @@ func (b *Builder) AddUint32(v uint32) {
b.add(byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
}
// AddUint48 appends a big-endian, 48-bit value to the byte string.
func (b *Builder) AddUint48(v uint64) {
b.add(byte(v>>40), byte(v>>32), byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
}
// AddUint64 appends a big-endian, 64-bit value to the byte string.
func (b *Builder) AddUint64(v uint64) {
b.add(byte(v>>56), byte(v>>48), byte(v>>40), byte(v>>32), byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
+21
View File
@@ -179,6 +179,27 @@ func TestUint32(t *testing.T) {
}
}
func TestUint48(t *testing.T) {
var b Builder
var u uint64 = 0xfefcff3cfdfc
b.AddUint48(u)
if err := builderBytesEq(&b, 254, 252, 255, 60, 253, 252); err != nil {
t.Error(err)
}
var s String = b.BytesOrPanic()
var v uint64
if !s.ReadUint48(&v) {
t.Error("ReadUint48() = false, want true")
}
if v != u {
t.Errorf("v = %x, want %x", v, u)
}
if len(s) != 0 {
t.Errorf("len(s) = %d, want 0", len(s))
}
}
func TestUint64(t *testing.T) {
var b Builder
b.AddUint64(0xf2fefefcff3cfdfc)
+12 -1
View File
@@ -15,7 +15,7 @@
//
// See the documentation and examples for the Builder and String types to get
// started.
package cryptobyte // import "golang.org/x/crypto/cryptobyte"
package cryptobyte
// String represents a string of bytes. It provides methods for parsing
// fixed-length and length-prefixed values from it.
@@ -81,6 +81,17 @@ func (s *String) ReadUint32(out *uint32) bool {
return true
}
// ReadUint48 decodes a big-endian, 48-bit value into out and advances over it.
// It reports whether the read was successful.
func (s *String) ReadUint48(out *uint64) bool {
v := s.read(6)
if v == nil {
return false
}
*out = uint64(v[0])<<40 | uint64(v[1])<<32 | uint64(v[2])<<24 | uint64(v[3])<<16 | uint64(v[4])<<8 | uint64(v[5])
return true
}
// ReadUint64 decodes a big-endian, 64-bit value into out and advances over it.
// It reports whether the read was successful.
func (s *String) ReadUint64(out *uint64) bool {
+34 -87
View File
@@ -3,17 +3,17 @@
// 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.
package curve25519 // import "golang.org/x/crypto/curve25519"
// performs scalar multiplication on the elliptic curve known as Curve25519
// according to [RFC 7748].
//
// 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/subtle"
"errors"
"strconv"
"golang.org/x/crypto/curve25519/internal/field"
)
import "crypto/ecdh"
// ScalarMult sets dst to the product scalar * point.
//
@@ -21,55 +21,13 @@ import (
// zeroes, irrespective of the scalar. Instead, use the X25519 function, which
// will return an error.
func ScalarMult(dst, scalar, point *[32]byte) {
var e [32]byte
copy(e[:], scalar[:])
e[0] &= 248
e[31] &= 127
e[31] |= 64
var x1, x2, z2, x3, z3, tmp0, tmp1 field.Element
x1.SetBytes(point[:])
x2.One()
x3.Set(&x1)
z3.One()
swap := 0
for pos := 254; pos >= 0; pos-- {
b := e[pos/8] >> uint(pos&7)
b &= 1
swap ^= int(b)
x2.Swap(&x3, swap)
z2.Swap(&z3, swap)
swap = int(b)
tmp0.Subtract(&x3, &z3)
tmp1.Subtract(&x2, &z2)
x2.Add(&x2, &z2)
z2.Add(&x3, &z3)
z3.Multiply(&tmp0, &x2)
z2.Multiply(&z2, &tmp1)
tmp0.Square(&tmp1)
tmp1.Square(&x2)
x3.Add(&z3, &z2)
z2.Subtract(&z3, &z2)
x2.Multiply(&tmp1, &tmp0)
tmp1.Subtract(&tmp1, &tmp0)
z2.Square(&z2)
z3.Mult32(&tmp1, 121666)
x3.Square(&x3)
tmp0.Add(&tmp0, &z3)
z3.Multiply(&x1, &z2)
z2.Multiply(&tmp1, &tmp0)
if _, err := x25519(dst, scalar[:], point[:]); err != nil {
// The only error condition for x25519 when the inputs are 32 bytes long
// is if the output would have been the all-zero value.
for i := range dst {
dst[i] = 0
}
}
x2.Swap(&x3, swap)
z2.Swap(&z3, swap)
z2.Invert(&z2)
x2.Multiply(&x2, &z2)
copy(dst[:], x2.Bytes())
}
// ScalarBaseMult sets dst to the product scalar * base where base is the
@@ -78,7 +36,12 @@ func ScalarMult(dst, scalar, point *[32]byte) {
// It is recommended to use the X25519 function with Basepoint instead, as
// copying into fixed size arrays can lead to unexpected bugs.
func ScalarBaseMult(dst, scalar *[32]byte) {
ScalarMult(dst, scalar, &basePoint)
curve := ecdh.X25519()
priv, err := curve.NewPrivateKey(scalar[:])
if err != nil {
panic("curve25519: " + err.Error())
}
copy(dst[:], priv.PublicKey().Bytes())
}
const (
@@ -91,21 +54,10 @@ const (
// Basepoint is the canonical Curve25519 generator.
var Basepoint []byte
var basePoint = [32]byte{9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
var basePoint = [32]byte{9}
func init() { Basepoint = basePoint[:] }
func checkBasepoint() {
if subtle.ConstantTimeCompare(Basepoint, []byte{
0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
}) != 1 {
panic("curve25519: global Basepoint value was modified")
}
}
// X25519 returns the result of the scalar multiplication (scalar * point),
// according to RFC 7748, Section 5. scalar, point and the return value are
// slices of 32 bytes.
@@ -123,24 +75,19 @@ func X25519(scalar, point []byte) ([]byte, error) {
}
func x25519(dst *[32]byte, scalar, point []byte) ([]byte, error) {
var in [32]byte
if l := len(scalar); l != 32 {
return nil, errors.New("bad scalar length: " + strconv.Itoa(l) + ", expected 32")
curve := ecdh.X25519()
pub, err := curve.NewPublicKey(point)
if err != nil {
return nil, err
}
if l := len(point); l != 32 {
return nil, errors.New("bad point length: " + strconv.Itoa(l) + ", expected 32")
priv, err := curve.NewPrivateKey(scalar)
if err != nil {
return nil, err
}
copy(in[:], scalar)
if &point[0] == &Basepoint[0] {
checkBasepoint()
ScalarBaseMult(dst, &in)
} else {
var base, zero [32]byte
copy(base[:], point)
ScalarMult(dst, &in, &base)
if subtle.ConstantTimeCompare(dst[:], zero[:]) == 1 {
return nil, errors.New("bad input point: low order point")
}
out, err := priv.ECDH(pub)
if err != nil {
return nil, err
}
copy(dst[:], out)
return dst[:], nil
}
+15 -13
View File
@@ -2,13 +2,15 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package curve25519
package curve25519_test
import (
"bytes"
"crypto/rand"
"encoding/hex"
"testing"
"golang.org/x/crypto/curve25519"
)
const expectedHex = "89161fde887b2b53de549af483940106ecc114d6982daa98256de23bdf77661a"
@@ -19,7 +21,7 @@ func TestX25519Basepoint(t *testing.T) {
for i := 0; i < 200; i++ {
var err error
x, err = X25519(x, Basepoint)
x, err = curve25519.X25519(x, curve25519.Basepoint)
if err != nil {
t.Fatal(err)
}
@@ -32,12 +34,12 @@ func TestX25519Basepoint(t *testing.T) {
}
func TestLowOrderPoints(t *testing.T) {
scalar := make([]byte, ScalarSize)
scalar := make([]byte, curve25519.ScalarSize)
if _, err := rand.Read(scalar); err != nil {
t.Fatal(err)
}
for i, p := range lowOrderPoints {
out, err := X25519(scalar, p)
out, err := curve25519.X25519(scalar, p)
if err == nil {
t.Errorf("%d: expected error, got nil", i)
}
@@ -48,10 +50,10 @@ func TestLowOrderPoints(t *testing.T) {
}
func TestTestVectors(t *testing.T) {
t.Run("Legacy", func(t *testing.T) { testTestVectors(t, ScalarMult) })
t.Run("Legacy", func(t *testing.T) { testTestVectors(t, curve25519.ScalarMult) })
t.Run("X25519", func(t *testing.T) {
testTestVectors(t, func(dst, scalar, point *[32]byte) {
out, err := X25519(scalar[:], point[:])
out, err := curve25519.X25519(scalar[:], point[:])
if err != nil {
t.Fatal(err)
}
@@ -88,10 +90,10 @@ func TestHighBitIgnored(t *testing.T) {
var hi0, hi1 [32]byte
u[31] &= 0x7f
ScalarMult(&hi0, &s, &u)
curve25519.ScalarMult(&hi0, &s, &u)
u[31] |= 0x80
ScalarMult(&hi1, &s, &u)
curve25519.ScalarMult(&hi1, &s, &u)
if !bytes.Equal(hi0[:], hi1[:]) {
t.Errorf("high bit of group point should not affect result")
@@ -101,14 +103,14 @@ func TestHighBitIgnored(t *testing.T) {
var benchmarkSink byte
func BenchmarkX25519Basepoint(b *testing.B) {
scalar := make([]byte, ScalarSize)
scalar := make([]byte, curve25519.ScalarSize)
if _, err := rand.Read(scalar); err != nil {
b.Fatal(err)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
out, err := X25519(scalar, Basepoint)
out, err := curve25519.X25519(scalar, curve25519.Basepoint)
if err != nil {
b.Fatal(err)
}
@@ -117,11 +119,11 @@ func BenchmarkX25519Basepoint(b *testing.B) {
}
func BenchmarkX25519(b *testing.B) {
scalar := make([]byte, ScalarSize)
scalar := make([]byte, curve25519.ScalarSize)
if _, err := rand.Read(scalar); err != nil {
b.Fatal(err)
}
point, err := X25519(scalar, Basepoint)
point, err := curve25519.X25519(scalar, curve25519.Basepoint)
if err != nil {
b.Fatal(err)
}
@@ -131,7 +133,7 @@ func BenchmarkX25519(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
out, err := X25519(scalar, point)
out, err := curve25519.X25519(scalar, point)
if err != nil {
b.Fatal(err)
}
-7
View File
@@ -1,7 +0,0 @@
This package is kept in sync with crypto/ed25519/internal/edwards25519/field in
the standard library.
If there are any changes in the standard library that need to be synced to this
package, run sync.sh. It will not overwrite any local changes made since the
previous sync, so it's ok to land changes in this package first, and then sync
to the standard library later.
@@ -1,298 +0,0 @@
// Copyright (c) 2021 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 main
import (
"fmt"
. "github.com/mmcloughlin/avo/build"
. "github.com/mmcloughlin/avo/gotypes"
. "github.com/mmcloughlin/avo/operand"
. "github.com/mmcloughlin/avo/reg"
// Ensure "go mod tidy" doesn't remove the golang.org/x/crypto module
// dependency, which is necessary to access the field.Element type.
_ "golang.org/x/crypto/curve25519"
)
//go:generate go run . -out ../fe_amd64.s -stubs ../fe_amd64.go -pkg field
func main() {
Package("golang.org/x/crypto/curve25519/internal/field")
ConstraintExpr("amd64,gc,!purego")
feMul()
feSquare()
Generate()
}
type namedComponent struct {
Component
name string
}
func (c namedComponent) String() string { return c.name }
type uint128 struct {
name string
hi, lo GPVirtual
}
func (c uint128) String() string { return c.name }
func feSquare() {
TEXT("feSquare", NOSPLIT, "func(out, a *Element)")
Doc("feSquare sets out = a * a. It works like feSquareGeneric.")
Pragma("noescape")
a := Dereference(Param("a"))
l0 := namedComponent{a.Field("l0"), "l0"}
l1 := namedComponent{a.Field("l1"), "l1"}
l2 := namedComponent{a.Field("l2"), "l2"}
l3 := namedComponent{a.Field("l3"), "l3"}
l4 := namedComponent{a.Field("l4"), "l4"}
// r0 = l0×l0 + 19×2×(l1×l4 + l2×l3)
r0 := uint128{"r0", GP64(), GP64()}
mul64(r0, 1, l0, l0)
addMul64(r0, 38, l1, l4)
addMul64(r0, 38, l2, l3)
// r1 = 2×l0×l1 + 19×2×l2×l4 + 19×l3×l3
r1 := uint128{"r1", GP64(), GP64()}
mul64(r1, 2, l0, l1)
addMul64(r1, 38, l2, l4)
addMul64(r1, 19, l3, l3)
// r2 = = 2×l0×l2 + l1×l1 + 19×2×l3×l4
r2 := uint128{"r2", GP64(), GP64()}
mul64(r2, 2, l0, l2)
addMul64(r2, 1, l1, l1)
addMul64(r2, 38, l3, l4)
// r3 = = 2×l0×l3 + 2×l1×l2 + 19×l4×l4
r3 := uint128{"r3", GP64(), GP64()}
mul64(r3, 2, l0, l3)
addMul64(r3, 2, l1, l2)
addMul64(r3, 19, l4, l4)
// r4 = = 2×l0×l4 + 2×l1×l3 + l2×l2
r4 := uint128{"r4", GP64(), GP64()}
mul64(r4, 2, l0, l4)
addMul64(r4, 2, l1, l3)
addMul64(r4, 1, l2, l2)
Comment("First reduction chain")
maskLow51Bits := GP64()
MOVQ(Imm((1<<51)-1), maskLow51Bits)
c0, r0lo := shiftRightBy51(&r0)
c1, r1lo := shiftRightBy51(&r1)
c2, r2lo := shiftRightBy51(&r2)
c3, r3lo := shiftRightBy51(&r3)
c4, r4lo := shiftRightBy51(&r4)
maskAndAdd(r0lo, maskLow51Bits, c4, 19)
maskAndAdd(r1lo, maskLow51Bits, c0, 1)
maskAndAdd(r2lo, maskLow51Bits, c1, 1)
maskAndAdd(r3lo, maskLow51Bits, c2, 1)
maskAndAdd(r4lo, maskLow51Bits, c3, 1)
Comment("Second reduction chain (carryPropagate)")
// c0 = r0 >> 51
MOVQ(r0lo, c0)
SHRQ(Imm(51), c0)
// c1 = r1 >> 51
MOVQ(r1lo, c1)
SHRQ(Imm(51), c1)
// c2 = r2 >> 51
MOVQ(r2lo, c2)
SHRQ(Imm(51), c2)
// c3 = r3 >> 51
MOVQ(r3lo, c3)
SHRQ(Imm(51), c3)
// c4 = r4 >> 51
MOVQ(r4lo, c4)
SHRQ(Imm(51), c4)
maskAndAdd(r0lo, maskLow51Bits, c4, 19)
maskAndAdd(r1lo, maskLow51Bits, c0, 1)
maskAndAdd(r2lo, maskLow51Bits, c1, 1)
maskAndAdd(r3lo, maskLow51Bits, c2, 1)
maskAndAdd(r4lo, maskLow51Bits, c3, 1)
Comment("Store output")
out := Dereference(Param("out"))
Store(r0lo, out.Field("l0"))
Store(r1lo, out.Field("l1"))
Store(r2lo, out.Field("l2"))
Store(r3lo, out.Field("l3"))
Store(r4lo, out.Field("l4"))
RET()
}
func feMul() {
TEXT("feMul", NOSPLIT, "func(out, a, b *Element)")
Doc("feMul sets out = a * b. It works like feMulGeneric.")
Pragma("noescape")
a := Dereference(Param("a"))
a0 := namedComponent{a.Field("l0"), "a0"}
a1 := namedComponent{a.Field("l1"), "a1"}
a2 := namedComponent{a.Field("l2"), "a2"}
a3 := namedComponent{a.Field("l3"), "a3"}
a4 := namedComponent{a.Field("l4"), "a4"}
b := Dereference(Param("b"))
b0 := namedComponent{b.Field("l0"), "b0"}
b1 := namedComponent{b.Field("l1"), "b1"}
b2 := namedComponent{b.Field("l2"), "b2"}
b3 := namedComponent{b.Field("l3"), "b3"}
b4 := namedComponent{b.Field("l4"), "b4"}
// r0 = a0×b0 + 19×(a1×b4 + a2×b3 + a3×b2 + a4×b1)
r0 := uint128{"r0", GP64(), GP64()}
mul64(r0, 1, a0, b0)
addMul64(r0, 19, a1, b4)
addMul64(r0, 19, a2, b3)
addMul64(r0, 19, a3, b2)
addMul64(r0, 19, a4, b1)
// r1 = a0×b1 + a1×b0 + 19×(a2×b4 + a3×b3 + a4×b2)
r1 := uint128{"r1", GP64(), GP64()}
mul64(r1, 1, a0, b1)
addMul64(r1, 1, a1, b0)
addMul64(r1, 19, a2, b4)
addMul64(r1, 19, a3, b3)
addMul64(r1, 19, a4, b2)
// r2 = a0×b2 + a1×b1 + a2×b0 + 19×(a3×b4 + a4×b3)
r2 := uint128{"r2", GP64(), GP64()}
mul64(r2, 1, a0, b2)
addMul64(r2, 1, a1, b1)
addMul64(r2, 1, a2, b0)
addMul64(r2, 19, a3, b4)
addMul64(r2, 19, a4, b3)
// r3 = a0×b3 + a1×b2 + a2×b1 + a3×b0 + 19×a4×b4
r3 := uint128{"r3", GP64(), GP64()}
mul64(r3, 1, a0, b3)
addMul64(r3, 1, a1, b2)
addMul64(r3, 1, a2, b1)
addMul64(r3, 1, a3, b0)
addMul64(r3, 19, a4, b4)
// r4 = a0×b4 + a1×b3 + a2×b2 + a3×b1 + a4×b0
r4 := uint128{"r4", GP64(), GP64()}
mul64(r4, 1, a0, b4)
addMul64(r4, 1, a1, b3)
addMul64(r4, 1, a2, b2)
addMul64(r4, 1, a3, b1)
addMul64(r4, 1, a4, b0)
Comment("First reduction chain")
maskLow51Bits := GP64()
MOVQ(Imm((1<<51)-1), maskLow51Bits)
c0, r0lo := shiftRightBy51(&r0)
c1, r1lo := shiftRightBy51(&r1)
c2, r2lo := shiftRightBy51(&r2)
c3, r3lo := shiftRightBy51(&r3)
c4, r4lo := shiftRightBy51(&r4)
maskAndAdd(r0lo, maskLow51Bits, c4, 19)
maskAndAdd(r1lo, maskLow51Bits, c0, 1)
maskAndAdd(r2lo, maskLow51Bits, c1, 1)
maskAndAdd(r3lo, maskLow51Bits, c2, 1)
maskAndAdd(r4lo, maskLow51Bits, c3, 1)
Comment("Second reduction chain (carryPropagate)")
// c0 = r0 >> 51
MOVQ(r0lo, c0)
SHRQ(Imm(51), c0)
// c1 = r1 >> 51
MOVQ(r1lo, c1)
SHRQ(Imm(51), c1)
// c2 = r2 >> 51
MOVQ(r2lo, c2)
SHRQ(Imm(51), c2)
// c3 = r3 >> 51
MOVQ(r3lo, c3)
SHRQ(Imm(51), c3)
// c4 = r4 >> 51
MOVQ(r4lo, c4)
SHRQ(Imm(51), c4)
maskAndAdd(r0lo, maskLow51Bits, c4, 19)
maskAndAdd(r1lo, maskLow51Bits, c0, 1)
maskAndAdd(r2lo, maskLow51Bits, c1, 1)
maskAndAdd(r3lo, maskLow51Bits, c2, 1)
maskAndAdd(r4lo, maskLow51Bits, c3, 1)
Comment("Store output")
out := Dereference(Param("out"))
Store(r0lo, out.Field("l0"))
Store(r1lo, out.Field("l1"))
Store(r2lo, out.Field("l2"))
Store(r3lo, out.Field("l3"))
Store(r4lo, out.Field("l4"))
RET()
}
// mul64 sets r to i * aX * bX.
func mul64(r uint128, i int, aX, bX namedComponent) {
switch i {
case 1:
Comment(fmt.Sprintf("%s = %s×%s", r, aX, bX))
Load(aX, RAX)
case 2:
Comment(fmt.Sprintf("%s = 2×%s×%s", r, aX, bX))
Load(aX, RAX)
SHLQ(Imm(1), RAX)
default:
panic("unsupported i value")
}
MULQ(mustAddr(bX)) // RDX, RAX = RAX * bX
MOVQ(RAX, r.lo)
MOVQ(RDX, r.hi)
}
// addMul64 sets r to r + i * aX * bX.
func addMul64(r uint128, i uint64, aX, bX namedComponent) {
switch i {
case 1:
Comment(fmt.Sprintf("%s += %s×%s", r, aX, bX))
Load(aX, RAX)
default:
Comment(fmt.Sprintf("%s += %d×%s×%s", r, i, aX, bX))
IMUL3Q(Imm(i), Load(aX, GP64()), RAX)
}
MULQ(mustAddr(bX)) // RDX, RAX = RAX * bX
ADDQ(RAX, r.lo)
ADCQ(RDX, r.hi)
}
// shiftRightBy51 returns r >> 51 and r.lo.
//
// After this function is called, the uint128 may not be used anymore.
func shiftRightBy51(r *uint128) (out, lo GPVirtual) {
out = r.hi
lo = r.lo
SHLQ(Imm(64-51), r.lo, r.hi)
r.lo, r.hi = nil, nil // make sure the uint128 is unusable
return
}
// maskAndAdd sets r = r&mask + c*i.
func maskAndAdd(r, mask, c GPVirtual, i uint64) {
ANDQ(mask, r)
if i != 1 {
IMUL3Q(Imm(i), c, c)
}
ADDQ(c, r)
}
func mustAddr(c Component) Op {
b, err := c.Resolve()
if err != nil {
panic(err)
}
return b.Addr
}
-10
View File
@@ -1,10 +0,0 @@
module asm
go 1.16
require (
github.com/mmcloughlin/avo v0.4.0
golang.org/x/crypto v0.0.0
)
replace golang.org/x/crypto v0.0.0 => ../../../..
-34
View File
@@ -1,34 +0,0 @@
github.com/mmcloughlin/avo v0.4.0 h1:jeHDRktVD+578ULxWpQHkilor6pkdLF7u7EiTzDbfcU=
github.com/mmcloughlin/avo v0.4.0/go.mod h1:RW9BfYA3TgO9uCdNrKU2h6J8cPD8ZLznvfgHAeszb1s=
github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211030160813-b3129d9d1021 h1:giLT+HuUP/gXYrG2Plg9WTjj4qhfgaW424ZIFog3rlk=
golang.org/x/sys v0.0.0-20211030160813-b3129d9d1021/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.7 h1:6j8CgantCy3yc8JGBqkDLMKWqZ0RDU2g1HVgacojGWQ=
golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
-416
View File
@@ -1,416 +0,0 @@
// Copyright (c) 2017 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 field implements fast arithmetic modulo 2^255-19.
package field
import (
"crypto/subtle"
"encoding/binary"
"math/bits"
)
// Element represents an element of the field GF(2^255-19). Note that this
// is not a cryptographically secure group, and should only be used to interact
// with edwards25519.Point coordinates.
//
// This type works similarly to math/big.Int, and all arguments and receivers
// are allowed to alias.
//
// The zero value is a valid zero element.
type Element struct {
// An element t represents the integer
// t.l0 + t.l1*2^51 + t.l2*2^102 + t.l3*2^153 + t.l4*2^204
//
// Between operations, all limbs are expected to be lower than 2^52.
l0 uint64
l1 uint64
l2 uint64
l3 uint64
l4 uint64
}
const maskLow51Bits uint64 = (1 << 51) - 1
var feZero = &Element{0, 0, 0, 0, 0}
// Zero sets v = 0, and returns v.
func (v *Element) Zero() *Element {
*v = *feZero
return v
}
var feOne = &Element{1, 0, 0, 0, 0}
// One sets v = 1, and returns v.
func (v *Element) One() *Element {
*v = *feOne
return v
}
// reduce reduces v modulo 2^255 - 19 and returns it.
func (v *Element) reduce() *Element {
v.carryPropagate()
// After the light reduction we now have a field element representation
// v < 2^255 + 2^13 * 19, but need v < 2^255 - 19.
// If v >= 2^255 - 19, then v + 19 >= 2^255, which would overflow 2^255 - 1,
// generating a carry. That is, c will be 0 if v < 2^255 - 19, and 1 otherwise.
c := (v.l0 + 19) >> 51
c = (v.l1 + c) >> 51
c = (v.l2 + c) >> 51
c = (v.l3 + c) >> 51
c = (v.l4 + c) >> 51
// If v < 2^255 - 19 and c = 0, this will be a no-op. Otherwise, it's
// effectively applying the reduction identity to the carry.
v.l0 += 19 * c
v.l1 += v.l0 >> 51
v.l0 = v.l0 & maskLow51Bits
v.l2 += v.l1 >> 51
v.l1 = v.l1 & maskLow51Bits
v.l3 += v.l2 >> 51
v.l2 = v.l2 & maskLow51Bits
v.l4 += v.l3 >> 51
v.l3 = v.l3 & maskLow51Bits
// no additional carry
v.l4 = v.l4 & maskLow51Bits
return v
}
// Add sets v = a + b, and returns v.
func (v *Element) Add(a, b *Element) *Element {
v.l0 = a.l0 + b.l0
v.l1 = a.l1 + b.l1
v.l2 = a.l2 + b.l2
v.l3 = a.l3 + b.l3
v.l4 = a.l4 + b.l4
// Using the generic implementation here is actually faster than the
// assembly. Probably because the body of this function is so simple that
// the compiler can figure out better optimizations by inlining the carry
// propagation. TODO
return v.carryPropagateGeneric()
}
// Subtract sets v = a - b, and returns v.
func (v *Element) Subtract(a, b *Element) *Element {
// We first add 2 * p, to guarantee the subtraction won't underflow, and
// then subtract b (which can be up to 2^255 + 2^13 * 19).
v.l0 = (a.l0 + 0xFFFFFFFFFFFDA) - b.l0
v.l1 = (a.l1 + 0xFFFFFFFFFFFFE) - b.l1
v.l2 = (a.l2 + 0xFFFFFFFFFFFFE) - b.l2
v.l3 = (a.l3 + 0xFFFFFFFFFFFFE) - b.l3
v.l4 = (a.l4 + 0xFFFFFFFFFFFFE) - b.l4
return v.carryPropagate()
}
// Negate sets v = -a, and returns v.
func (v *Element) Negate(a *Element) *Element {
return v.Subtract(feZero, a)
}
// Invert sets v = 1/z mod p, and returns v.
//
// If z == 0, Invert returns v = 0.
func (v *Element) Invert(z *Element) *Element {
// Inversion is implemented as exponentiation with exponent p − 2. It uses the
// same sequence of 255 squarings and 11 multiplications as [Curve25519].
var z2, z9, z11, z2_5_0, z2_10_0, z2_20_0, z2_50_0, z2_100_0, t Element
z2.Square(z) // 2
t.Square(&z2) // 4
t.Square(&t) // 8
z9.Multiply(&t, z) // 9
z11.Multiply(&z9, &z2) // 11
t.Square(&z11) // 22
z2_5_0.Multiply(&t, &z9) // 31 = 2^5 - 2^0
t.Square(&z2_5_0) // 2^6 - 2^1
for i := 0; i < 4; i++ {
t.Square(&t) // 2^10 - 2^5
}
z2_10_0.Multiply(&t, &z2_5_0) // 2^10 - 2^0
t.Square(&z2_10_0) // 2^11 - 2^1
for i := 0; i < 9; i++ {
t.Square(&t) // 2^20 - 2^10
}
z2_20_0.Multiply(&t, &z2_10_0) // 2^20 - 2^0
t.Square(&z2_20_0) // 2^21 - 2^1
for i := 0; i < 19; i++ {
t.Square(&t) // 2^40 - 2^20
}
t.Multiply(&t, &z2_20_0) // 2^40 - 2^0
t.Square(&t) // 2^41 - 2^1
for i := 0; i < 9; i++ {
t.Square(&t) // 2^50 - 2^10
}
z2_50_0.Multiply(&t, &z2_10_0) // 2^50 - 2^0
t.Square(&z2_50_0) // 2^51 - 2^1
for i := 0; i < 49; i++ {
t.Square(&t) // 2^100 - 2^50
}
z2_100_0.Multiply(&t, &z2_50_0) // 2^100 - 2^0
t.Square(&z2_100_0) // 2^101 - 2^1
for i := 0; i < 99; i++ {
t.Square(&t) // 2^200 - 2^100
}
t.Multiply(&t, &z2_100_0) // 2^200 - 2^0
t.Square(&t) // 2^201 - 2^1
for i := 0; i < 49; i++ {
t.Square(&t) // 2^250 - 2^50
}
t.Multiply(&t, &z2_50_0) // 2^250 - 2^0
t.Square(&t) // 2^251 - 2^1
t.Square(&t) // 2^252 - 2^2
t.Square(&t) // 2^253 - 2^3
t.Square(&t) // 2^254 - 2^4
t.Square(&t) // 2^255 - 2^5
return v.Multiply(&t, &z11) // 2^255 - 21
}
// Set sets v = a, and returns v.
func (v *Element) Set(a *Element) *Element {
*v = *a
return v
}
// SetBytes sets v to x, which must be a 32-byte little-endian encoding.
//
// Consistent with RFC 7748, the most significant bit (the high bit of the
// last byte) is ignored, and non-canonical values (2^255-19 through 2^255-1)
// are accepted. Note that this is laxer than specified by RFC 8032.
func (v *Element) SetBytes(x []byte) *Element {
if len(x) != 32 {
panic("edwards25519: invalid field element input size")
}
// Bits 0:51 (bytes 0:8, bits 0:64, shift 0, mask 51).
v.l0 = binary.LittleEndian.Uint64(x[0:8])
v.l0 &= maskLow51Bits
// Bits 51:102 (bytes 6:14, bits 48:112, shift 3, mask 51).
v.l1 = binary.LittleEndian.Uint64(x[6:14]) >> 3
v.l1 &= maskLow51Bits
// Bits 102:153 (bytes 12:20, bits 96:160, shift 6, mask 51).
v.l2 = binary.LittleEndian.Uint64(x[12:20]) >> 6
v.l2 &= maskLow51Bits
// Bits 153:204 (bytes 19:27, bits 152:216, shift 1, mask 51).
v.l3 = binary.LittleEndian.Uint64(x[19:27]) >> 1
v.l3 &= maskLow51Bits
// Bits 204:251 (bytes 24:32, bits 192:256, shift 12, mask 51).
// Note: not bytes 25:33, shift 4, to avoid overread.
v.l4 = binary.LittleEndian.Uint64(x[24:32]) >> 12
v.l4 &= maskLow51Bits
return v
}
// Bytes returns the canonical 32-byte little-endian encoding of v.
func (v *Element) Bytes() []byte {
// This function is outlined to make the allocations inline in the caller
// rather than happen on the heap.
var out [32]byte
return v.bytes(&out)
}
func (v *Element) bytes(out *[32]byte) []byte {
t := *v
t.reduce()
var buf [8]byte
for i, l := range [5]uint64{t.l0, t.l1, t.l2, t.l3, t.l4} {
bitsOffset := i * 51
binary.LittleEndian.PutUint64(buf[:], l<<uint(bitsOffset%8))
for i, bb := range buf {
off := bitsOffset/8 + i
if off >= len(out) {
break
}
out[off] |= bb
}
}
return out[:]
}
// Equal returns 1 if v and u are equal, and 0 otherwise.
func (v *Element) Equal(u *Element) int {
sa, sv := u.Bytes(), v.Bytes()
return subtle.ConstantTimeCompare(sa, sv)
}
// mask64Bits returns 0xffffffff if cond is 1, and 0 otherwise.
func mask64Bits(cond int) uint64 { return ^(uint64(cond) - 1) }
// Select sets v to a if cond == 1, and to b if cond == 0.
func (v *Element) Select(a, b *Element, cond int) *Element {
m := mask64Bits(cond)
v.l0 = (m & a.l0) | (^m & b.l0)
v.l1 = (m & a.l1) | (^m & b.l1)
v.l2 = (m & a.l2) | (^m & b.l2)
v.l3 = (m & a.l3) | (^m & b.l3)
v.l4 = (m & a.l4) | (^m & b.l4)
return v
}
// Swap swaps v and u if cond == 1 or leaves them unchanged if cond == 0, and returns v.
func (v *Element) Swap(u *Element, cond int) {
m := mask64Bits(cond)
t := m & (v.l0 ^ u.l0)
v.l0 ^= t
u.l0 ^= t
t = m & (v.l1 ^ u.l1)
v.l1 ^= t
u.l1 ^= t
t = m & (v.l2 ^ u.l2)
v.l2 ^= t
u.l2 ^= t
t = m & (v.l3 ^ u.l3)
v.l3 ^= t
u.l3 ^= t
t = m & (v.l4 ^ u.l4)
v.l4 ^= t
u.l4 ^= t
}
// IsNegative returns 1 if v is negative, and 0 otherwise.
func (v *Element) IsNegative() int {
return int(v.Bytes()[0] & 1)
}
// Absolute sets v to |u|, and returns v.
func (v *Element) Absolute(u *Element) *Element {
return v.Select(new(Element).Negate(u), u, u.IsNegative())
}
// Multiply sets v = x * y, and returns v.
func (v *Element) Multiply(x, y *Element) *Element {
feMul(v, x, y)
return v
}
// Square sets v = x * x, and returns v.
func (v *Element) Square(x *Element) *Element {
feSquare(v, x)
return v
}
// Mult32 sets v = x * y, and returns v.
func (v *Element) Mult32(x *Element, y uint32) *Element {
x0lo, x0hi := mul51(x.l0, y)
x1lo, x1hi := mul51(x.l1, y)
x2lo, x2hi := mul51(x.l2, y)
x3lo, x3hi := mul51(x.l3, y)
x4lo, x4hi := mul51(x.l4, y)
v.l0 = x0lo + 19*x4hi // carried over per the reduction identity
v.l1 = x1lo + x0hi
v.l2 = x2lo + x1hi
v.l3 = x3lo + x2hi
v.l4 = x4lo + x3hi
// The hi portions are going to be only 32 bits, plus any previous excess,
// so we can skip the carry propagation.
return v
}
// mul51 returns lo + hi * 2⁵¹ = a * b.
func mul51(a uint64, b uint32) (lo uint64, hi uint64) {
mh, ml := bits.Mul64(a, uint64(b))
lo = ml & maskLow51Bits
hi = (mh << 13) | (ml >> 51)
return
}
// Pow22523 set v = x^((p-5)/8), and returns v. (p-5)/8 is 2^252-3.
func (v *Element) Pow22523(x *Element) *Element {
var t0, t1, t2 Element
t0.Square(x) // x^2
t1.Square(&t0) // x^4
t1.Square(&t1) // x^8
t1.Multiply(x, &t1) // x^9
t0.Multiply(&t0, &t1) // x^11
t0.Square(&t0) // x^22
t0.Multiply(&t1, &t0) // x^31
t1.Square(&t0) // x^62
for i := 1; i < 5; i++ { // x^992
t1.Square(&t1)
}
t0.Multiply(&t1, &t0) // x^1023 -> 1023 = 2^10 - 1
t1.Square(&t0) // 2^11 - 2
for i := 1; i < 10; i++ { // 2^20 - 2^10
t1.Square(&t1)
}
t1.Multiply(&t1, &t0) // 2^20 - 1
t2.Square(&t1) // 2^21 - 2
for i := 1; i < 20; i++ { // 2^40 - 2^20
t2.Square(&t2)
}
t1.Multiply(&t2, &t1) // 2^40 - 1
t1.Square(&t1) // 2^41 - 2
for i := 1; i < 10; i++ { // 2^50 - 2^10
t1.Square(&t1)
}
t0.Multiply(&t1, &t0) // 2^50 - 1
t1.Square(&t0) // 2^51 - 2
for i := 1; i < 50; i++ { // 2^100 - 2^50
t1.Square(&t1)
}
t1.Multiply(&t1, &t0) // 2^100 - 1
t2.Square(&t1) // 2^101 - 2
for i := 1; i < 100; i++ { // 2^200 - 2^100
t2.Square(&t2)
}
t1.Multiply(&t2, &t1) // 2^200 - 1
t1.Square(&t1) // 2^201 - 2
for i := 1; i < 50; i++ { // 2^250 - 2^50
t1.Square(&t1)
}
t0.Multiply(&t1, &t0) // 2^250 - 1
t0.Square(&t0) // 2^251 - 2
t0.Square(&t0) // 2^252 - 4
return v.Multiply(&t0, x) // 2^252 - 3 -> x^(2^252-3)
}
// sqrtM1 is 2^((p-1)/4), which squared is equal to -1 by Euler's Criterion.
var sqrtM1 = &Element{1718705420411056, 234908883556509,
2233514472574048, 2117202627021982, 765476049583133}
// SqrtRatio sets r to the non-negative square root of the ratio of u and v.
//
// If u/v is square, SqrtRatio returns r and 1. If u/v is not square, SqrtRatio
// sets r according to Section 4.3 of draft-irtf-cfrg-ristretto255-decaf448-00,
// and returns r and 0.
func (r *Element) SqrtRatio(u, v *Element) (rr *Element, wasSquare int) {
var a, b Element
// r = (u * v3) * (u * v7)^((p-5)/8)
v2 := a.Square(v)
uv3 := b.Multiply(u, b.Multiply(v2, v))
uv7 := a.Multiply(uv3, a.Square(v2))
r.Multiply(uv3, r.Pow22523(uv7))
check := a.Multiply(v, a.Square(r)) // check = v * r^2
uNeg := b.Negate(u)
correctSignSqrt := check.Equal(u)
flippedSignSqrt := check.Equal(uNeg)
flippedSignSqrtI := check.Equal(uNeg.Multiply(uNeg, sqrtM1))
rPrime := b.Multiply(r, sqrtM1) // r_prime = SQRT_M1 * r
// r = CT_SELECT(r_prime IF flipped_sign_sqrt | flipped_sign_sqrt_i ELSE r)
r.Select(rPrime, r, flippedSignSqrt|flippedSignSqrtI)
r.Absolute(r) // Choose the nonnegative square root.
return r, correctSignSqrt | flippedSignSqrt
}
-126
View File
@@ -1,126 +0,0 @@
// Copyright (c) 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 field
import (
"testing"
"testing/quick"
)
func checkAliasingOneArg(f func(v, x *Element) *Element) func(v, x Element) bool {
return func(v, x Element) bool {
x1, v1 := x, x
// Calculate a reference f(x) without aliasing.
if out := f(&v, &x); out != &v && isInBounds(out) {
return false
}
// Test aliasing the argument and the receiver.
if out := f(&v1, &v1); out != &v1 || v1 != v {
return false
}
// Ensure the arguments was not modified.
return x == x1
}
}
func checkAliasingTwoArgs(f func(v, x, y *Element) *Element) func(v, x, y Element) bool {
return func(v, x, y Element) bool {
x1, y1, v1 := x, y, Element{}
// Calculate a reference f(x, y) without aliasing.
if out := f(&v, &x, &y); out != &v && isInBounds(out) {
return false
}
// Test aliasing the first argument and the receiver.
v1 = x
if out := f(&v1, &v1, &y); out != &v1 || v1 != v {
return false
}
// Test aliasing the second argument and the receiver.
v1 = y
if out := f(&v1, &x, &v1); out != &v1 || v1 != v {
return false
}
// Calculate a reference f(x, x) without aliasing.
if out := f(&v, &x, &x); out != &v {
return false
}
// Test aliasing the first argument and the receiver.
v1 = x
if out := f(&v1, &v1, &x); out != &v1 || v1 != v {
return false
}
// Test aliasing the second argument and the receiver.
v1 = x
if out := f(&v1, &x, &v1); out != &v1 || v1 != v {
return false
}
// Test aliasing both arguments and the receiver.
v1 = x
if out := f(&v1, &v1, &v1); out != &v1 || v1 != v {
return false
}
// Ensure the arguments were not modified.
return x == x1 && y == y1
}
}
// TestAliasing checks that receivers and arguments can alias each other without
// leading to incorrect results. That is, it ensures that it's safe to write
//
// v.Invert(v)
//
// or
//
// v.Add(v, v)
//
// without any of the inputs getting clobbered by the output being written.
func TestAliasing(t *testing.T) {
type target struct {
name string
oneArgF func(v, x *Element) *Element
twoArgsF func(v, x, y *Element) *Element
}
for _, tt := range []target{
{name: "Absolute", oneArgF: (*Element).Absolute},
{name: "Invert", oneArgF: (*Element).Invert},
{name: "Negate", oneArgF: (*Element).Negate},
{name: "Set", oneArgF: (*Element).Set},
{name: "Square", oneArgF: (*Element).Square},
{name: "Multiply", twoArgsF: (*Element).Multiply},
{name: "Add", twoArgsF: (*Element).Add},
{name: "Subtract", twoArgsF: (*Element).Subtract},
{
name: "Select0",
twoArgsF: func(v, x, y *Element) *Element {
return (*Element).Select(v, x, y, 0)
},
},
{
name: "Select1",
twoArgsF: func(v, x, y *Element) *Element {
return (*Element).Select(v, x, y, 1)
},
},
} {
var err error
switch {
case tt.oneArgF != nil:
err = quick.Check(checkAliasingOneArg(tt.oneArgF), &quick.Config{MaxCountScale: 1 << 8})
case tt.twoArgsF != nil:
err = quick.Check(checkAliasingTwoArgs(tt.twoArgsF), &quick.Config{MaxCountScale: 1 << 8})
}
if err != nil {
t.Errorf("%v: %v", tt.name, err)
}
}
}
-16
View File
@@ -1,16 +0,0 @@
// Code generated by command: go run fe_amd64_asm.go -out ../fe_amd64.s -stubs ../fe_amd64.go -pkg field. DO NOT EDIT.
//go:build amd64 && gc && !purego
// +build amd64,gc,!purego
package field
// feMul sets out = a * b. It works like feMulGeneric.
//
//go:noescape
func feMul(out *Element, a *Element, b *Element)
// feSquare sets out = a * a. It works like feSquareGeneric.
//
//go:noescape
func feSquare(out *Element, a *Element)
-379
View File
@@ -1,379 +0,0 @@
// Code generated by command: go run fe_amd64_asm.go -out ../fe_amd64.s -stubs ../fe_amd64.go -pkg field. DO NOT EDIT.
//go:build amd64 && gc && !purego
// +build amd64,gc,!purego
#include "textflag.h"
// func feMul(out *Element, a *Element, b *Element)
TEXT ·feMul(SB), NOSPLIT, $0-24
MOVQ a+8(FP), CX
MOVQ b+16(FP), BX
// r0 = a0×b0
MOVQ (CX), AX
MULQ (BX)
MOVQ AX, DI
MOVQ DX, SI
// r0 += 19×a1×b4
MOVQ 8(CX), AX
IMUL3Q $0x13, AX, AX
MULQ 32(BX)
ADDQ AX, DI
ADCQ DX, SI
// r0 += 19×a2×b3
MOVQ 16(CX), AX
IMUL3Q $0x13, AX, AX
MULQ 24(BX)
ADDQ AX, DI
ADCQ DX, SI
// r0 += 19×a3×b2
MOVQ 24(CX), AX
IMUL3Q $0x13, AX, AX
MULQ 16(BX)
ADDQ AX, DI
ADCQ DX, SI
// r0 += 19×a4×b1
MOVQ 32(CX), AX
IMUL3Q $0x13, AX, AX
MULQ 8(BX)
ADDQ AX, DI
ADCQ DX, SI
// r1 = a0×b1
MOVQ (CX), AX
MULQ 8(BX)
MOVQ AX, R9
MOVQ DX, R8
// r1 += a1×b0
MOVQ 8(CX), AX
MULQ (BX)
ADDQ AX, R9
ADCQ DX, R8
// r1 += 19×a2×b4
MOVQ 16(CX), AX
IMUL3Q $0x13, AX, AX
MULQ 32(BX)
ADDQ AX, R9
ADCQ DX, R8
// r1 += 19×a3×b3
MOVQ 24(CX), AX
IMUL3Q $0x13, AX, AX
MULQ 24(BX)
ADDQ AX, R9
ADCQ DX, R8
// r1 += 19×a4×b2
MOVQ 32(CX), AX
IMUL3Q $0x13, AX, AX
MULQ 16(BX)
ADDQ AX, R9
ADCQ DX, R8
// r2 = a0×b2
MOVQ (CX), AX
MULQ 16(BX)
MOVQ AX, R11
MOVQ DX, R10
// r2 += a1×b1
MOVQ 8(CX), AX
MULQ 8(BX)
ADDQ AX, R11
ADCQ DX, R10
// r2 += a2×b0
MOVQ 16(CX), AX
MULQ (BX)
ADDQ AX, R11
ADCQ DX, R10
// r2 += 19×a3×b4
MOVQ 24(CX), AX
IMUL3Q $0x13, AX, AX
MULQ 32(BX)
ADDQ AX, R11
ADCQ DX, R10
// r2 += 19×a4×b3
MOVQ 32(CX), AX
IMUL3Q $0x13, AX, AX
MULQ 24(BX)
ADDQ AX, R11
ADCQ DX, R10
// r3 = a0×b3
MOVQ (CX), AX
MULQ 24(BX)
MOVQ AX, R13
MOVQ DX, R12
// r3 += a1×b2
MOVQ 8(CX), AX
MULQ 16(BX)
ADDQ AX, R13
ADCQ DX, R12
// r3 += a2×b1
MOVQ 16(CX), AX
MULQ 8(BX)
ADDQ AX, R13
ADCQ DX, R12
// r3 += a3×b0
MOVQ 24(CX), AX
MULQ (BX)
ADDQ AX, R13
ADCQ DX, R12
// r3 += 19×a4×b4
MOVQ 32(CX), AX
IMUL3Q $0x13, AX, AX
MULQ 32(BX)
ADDQ AX, R13
ADCQ DX, R12
// r4 = a0×b4
MOVQ (CX), AX
MULQ 32(BX)
MOVQ AX, R15
MOVQ DX, R14
// r4 += a1×b3
MOVQ 8(CX), AX
MULQ 24(BX)
ADDQ AX, R15
ADCQ DX, R14
// r4 += a2×b2
MOVQ 16(CX), AX
MULQ 16(BX)
ADDQ AX, R15
ADCQ DX, R14
// r4 += a3×b1
MOVQ 24(CX), AX
MULQ 8(BX)
ADDQ AX, R15
ADCQ DX, R14
// r4 += a4×b0
MOVQ 32(CX), AX
MULQ (BX)
ADDQ AX, R15
ADCQ DX, R14
// First reduction chain
MOVQ $0x0007ffffffffffff, AX
SHLQ $0x0d, DI, SI
SHLQ $0x0d, R9, R8
SHLQ $0x0d, R11, R10
SHLQ $0x0d, R13, R12
SHLQ $0x0d, R15, R14
ANDQ AX, DI
IMUL3Q $0x13, R14, R14
ADDQ R14, DI
ANDQ AX, R9
ADDQ SI, R9
ANDQ AX, R11
ADDQ R8, R11
ANDQ AX, R13
ADDQ R10, R13
ANDQ AX, R15
ADDQ R12, R15
// Second reduction chain (carryPropagate)
MOVQ DI, SI
SHRQ $0x33, SI
MOVQ R9, R8
SHRQ $0x33, R8
MOVQ R11, R10
SHRQ $0x33, R10
MOVQ R13, R12
SHRQ $0x33, R12
MOVQ R15, R14
SHRQ $0x33, R14
ANDQ AX, DI
IMUL3Q $0x13, R14, R14
ADDQ R14, DI
ANDQ AX, R9
ADDQ SI, R9
ANDQ AX, R11
ADDQ R8, R11
ANDQ AX, R13
ADDQ R10, R13
ANDQ AX, R15
ADDQ R12, R15
// Store output
MOVQ out+0(FP), AX
MOVQ DI, (AX)
MOVQ R9, 8(AX)
MOVQ R11, 16(AX)
MOVQ R13, 24(AX)
MOVQ R15, 32(AX)
RET
// func feSquare(out *Element, a *Element)
TEXT ·feSquare(SB), NOSPLIT, $0-16
MOVQ a+8(FP), CX
// r0 = l0×l0
MOVQ (CX), AX
MULQ (CX)
MOVQ AX, SI
MOVQ DX, BX
// r0 += 38×l1×l4
MOVQ 8(CX), AX
IMUL3Q $0x26, AX, AX
MULQ 32(CX)
ADDQ AX, SI
ADCQ DX, BX
// r0 += 38×l2×l3
MOVQ 16(CX), AX
IMUL3Q $0x26, AX, AX
MULQ 24(CX)
ADDQ AX, SI
ADCQ DX, BX
// r1 = 2×l0×l1
MOVQ (CX), AX
SHLQ $0x01, AX
MULQ 8(CX)
MOVQ AX, R8
MOVQ DX, DI
// r1 += 38×l2×l4
MOVQ 16(CX), AX
IMUL3Q $0x26, AX, AX
MULQ 32(CX)
ADDQ AX, R8
ADCQ DX, DI
// r1 += 19×l3×l3
MOVQ 24(CX), AX
IMUL3Q $0x13, AX, AX
MULQ 24(CX)
ADDQ AX, R8
ADCQ DX, DI
// r2 = 2×l0×l2
MOVQ (CX), AX
SHLQ $0x01, AX
MULQ 16(CX)
MOVQ AX, R10
MOVQ DX, R9
// r2 += l1×l1
MOVQ 8(CX), AX
MULQ 8(CX)
ADDQ AX, R10
ADCQ DX, R9
// r2 += 38×l3×l4
MOVQ 24(CX), AX
IMUL3Q $0x26, AX, AX
MULQ 32(CX)
ADDQ AX, R10
ADCQ DX, R9
// r3 = 2×l0×l3
MOVQ (CX), AX
SHLQ $0x01, AX
MULQ 24(CX)
MOVQ AX, R12
MOVQ DX, R11
// r3 += 2×l1×l2
MOVQ 8(CX), AX
IMUL3Q $0x02, AX, AX
MULQ 16(CX)
ADDQ AX, R12
ADCQ DX, R11
// r3 += 19×l4×l4
MOVQ 32(CX), AX
IMUL3Q $0x13, AX, AX
MULQ 32(CX)
ADDQ AX, R12
ADCQ DX, R11
// r4 = 2×l0×l4
MOVQ (CX), AX
SHLQ $0x01, AX
MULQ 32(CX)
MOVQ AX, R14
MOVQ DX, R13
// r4 += 2×l1×l3
MOVQ 8(CX), AX
IMUL3Q $0x02, AX, AX
MULQ 24(CX)
ADDQ AX, R14
ADCQ DX, R13
// r4 += l2×l2
MOVQ 16(CX), AX
MULQ 16(CX)
ADDQ AX, R14
ADCQ DX, R13
// First reduction chain
MOVQ $0x0007ffffffffffff, AX
SHLQ $0x0d, SI, BX
SHLQ $0x0d, R8, DI
SHLQ $0x0d, R10, R9
SHLQ $0x0d, R12, R11
SHLQ $0x0d, R14, R13
ANDQ AX, SI
IMUL3Q $0x13, R13, R13
ADDQ R13, SI
ANDQ AX, R8
ADDQ BX, R8
ANDQ AX, R10
ADDQ DI, R10
ANDQ AX, R12
ADDQ R9, R12
ANDQ AX, R14
ADDQ R11, R14
// Second reduction chain (carryPropagate)
MOVQ SI, BX
SHRQ $0x33, BX
MOVQ R8, DI
SHRQ $0x33, DI
MOVQ R10, R9
SHRQ $0x33, R9
MOVQ R12, R11
SHRQ $0x33, R11
MOVQ R14, R13
SHRQ $0x33, R13
ANDQ AX, SI
IMUL3Q $0x13, R13, R13
ADDQ R13, SI
ANDQ AX, R8
ADDQ BX, R8
ANDQ AX, R10
ADDQ DI, R10
ANDQ AX, R12
ADDQ R9, R12
ANDQ AX, R14
ADDQ R11, R14
// Store output
MOVQ out+0(FP), AX
MOVQ SI, (AX)
MOVQ R8, 8(AX)
MOVQ R10, 16(AX)
MOVQ R12, 24(AX)
MOVQ R14, 32(AX)
RET
@@ -1,12 +0,0 @@
// Copyright (c) 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 !amd64 || !gc || purego
// +build !amd64 !gc purego
package field
func feMul(v, x, y *Element) { feMulGeneric(v, x, y) }
func feSquare(v, x *Element) { feSquareGeneric(v, x) }
-16
View File
@@ -1,16 +0,0 @@
// Copyright (c) 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.
//go:build arm64 && gc && !purego
// +build arm64,gc,!purego
package field
//go:noescape
func carryPropagate(v *Element)
func (v *Element) carryPropagate() *Element {
carryPropagate(v)
return v
}
-43
View File
@@ -1,43 +0,0 @@
// Copyright (c) 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.
//go:build arm64 && gc && !purego
// +build arm64,gc,!purego
#include "textflag.h"
// carryPropagate works exactly like carryPropagateGeneric and uses the
// same AND, ADD, and LSR+MADD instructions emitted by the compiler, but
// avoids loading R0-R4 twice and uses LDP and STP.
//
// See https://golang.org/issues/43145 for the main compiler issue.
//
// func carryPropagate(v *Element)
TEXT ·carryPropagate(SB),NOFRAME|NOSPLIT,$0-8
MOVD v+0(FP), R20
LDP 0(R20), (R0, R1)
LDP 16(R20), (R2, R3)
MOVD 32(R20), R4
AND $0x7ffffffffffff, R0, R10
AND $0x7ffffffffffff, R1, R11
AND $0x7ffffffffffff, R2, R12
AND $0x7ffffffffffff, R3, R13
AND $0x7ffffffffffff, R4, R14
ADD R0>>51, R11, R11
ADD R1>>51, R12, R12
ADD R2>>51, R13, R13
ADD R3>>51, R14, R14
// R4>>51 * 19 + R10 -> R10
LSR $51, R4, R21
MOVD $19, R22
MADD R22, R10, R21, R10
STP (R10, R11), 0(R20)
STP (R12, R13), 16(R20)
MOVD R14, 32(R20)
RET
@@ -1,12 +0,0 @@
// Copyright (c) 2021 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 !arm64 || !gc || purego
// +build !arm64 !gc purego
package field
func (v *Element) carryPropagate() *Element {
return v.carryPropagateGeneric()
}
@@ -1,36 +0,0 @@
// Copyright (c) 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 field
import "testing"
func BenchmarkAdd(b *testing.B) {
var x, y Element
x.One()
y.Add(feOne, feOne)
b.ResetTimer()
for i := 0; i < b.N; i++ {
x.Add(&x, &y)
}
}
func BenchmarkMultiply(b *testing.B) {
var x, y Element
x.One()
y.Add(feOne, feOne)
b.ResetTimer()
for i := 0; i < b.N; i++ {
x.Multiply(&x, &y)
}
}
func BenchmarkMult32(b *testing.B) {
var x Element
x.One()
b.ResetTimer()
for i := 0; i < b.N; i++ {
x.Mult32(&x, 0xaa42aa42)
}
}
-264
View File
@@ -1,264 +0,0 @@
// Copyright (c) 2017 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 field
import "math/bits"
// uint128 holds a 128-bit number as two 64-bit limbs, for use with the
// bits.Mul64 and bits.Add64 intrinsics.
type uint128 struct {
lo, hi uint64
}
// mul64 returns a * b.
func mul64(a, b uint64) uint128 {
hi, lo := bits.Mul64(a, b)
return uint128{lo, hi}
}
// addMul64 returns v + a * b.
func addMul64(v uint128, a, b uint64) uint128 {
hi, lo := bits.Mul64(a, b)
lo, c := bits.Add64(lo, v.lo, 0)
hi, _ = bits.Add64(hi, v.hi, c)
return uint128{lo, hi}
}
// shiftRightBy51 returns a >> 51. a is assumed to be at most 115 bits.
func shiftRightBy51(a uint128) uint64 {
return (a.hi << (64 - 51)) | (a.lo >> 51)
}
func feMulGeneric(v, a, b *Element) {
a0 := a.l0
a1 := a.l1
a2 := a.l2
a3 := a.l3
a4 := a.l4
b0 := b.l0
b1 := b.l1
b2 := b.l2
b3 := b.l3
b4 := b.l4
// Limb multiplication works like pen-and-paper columnar multiplication, but
// with 51-bit limbs instead of digits.
//
// a4 a3 a2 a1 a0 x
// b4 b3 b2 b1 b0 =
// ------------------------
// a4b0 a3b0 a2b0 a1b0 a0b0 +
// a4b1 a3b1 a2b1 a1b1 a0b1 +
// a4b2 a3b2 a2b2 a1b2 a0b2 +
// a4b3 a3b3 a2b3 a1b3 a0b3 +
// a4b4 a3b4 a2b4 a1b4 a0b4 =
// ----------------------------------------------
// r8 r7 r6 r5 r4 r3 r2 r1 r0
//
// We can then use the reduction identity (a * 2²⁵⁵ + b = a * 19 + b) to
// reduce the limbs that would overflow 255 bits. r5 * 2²⁵⁵ becomes 19 * r5,
// r6 * 2³⁰⁶ becomes 19 * r6 * 2⁵¹, etc.
//
// Reduction can be carried out simultaneously to multiplication. For
// example, we do not compute r5: whenever the result of a multiplication
// belongs to r5, like a1b4, we multiply it by 19 and add the result to r0.
//
// a4b0 a3b0 a2b0 a1b0 a0b0 +
// a3b1 a2b1 a1b1 a0b1 19×a4b1 +
// a2b2 a1b2 a0b2 19×a4b2 19×a3b2 +
// a1b3 a0b3 19×a4b3 19×a3b3 19×a2b3 +
// a0b4 19×a4b4 19×a3b4 19×a2b4 19×a1b4 =
// --------------------------------------
// r4 r3 r2 r1 r0
//
// Finally we add up the columns into wide, overlapping limbs.
a1_19 := a1 * 19
a2_19 := a2 * 19
a3_19 := a3 * 19
a4_19 := a4 * 19
// r0 = a0×b0 + 19×(a1×b4 + a2×b3 + a3×b2 + a4×b1)
r0 := mul64(a0, b0)
r0 = addMul64(r0, a1_19, b4)
r0 = addMul64(r0, a2_19, b3)
r0 = addMul64(r0, a3_19, b2)
r0 = addMul64(r0, a4_19, b1)
// r1 = a0×b1 + a1×b0 + 19×(a2×b4 + a3×b3 + a4×b2)
r1 := mul64(a0, b1)
r1 = addMul64(r1, a1, b0)
r1 = addMul64(r1, a2_19, b4)
r1 = addMul64(r1, a3_19, b3)
r1 = addMul64(r1, a4_19, b2)
// r2 = a0×b2 + a1×b1 + a2×b0 + 19×(a3×b4 + a4×b3)
r2 := mul64(a0, b2)
r2 = addMul64(r2, a1, b1)
r2 = addMul64(r2, a2, b0)
r2 = addMul64(r2, a3_19, b4)
r2 = addMul64(r2, a4_19, b3)
// r3 = a0×b3 + a1×b2 + a2×b1 + a3×b0 + 19×a4×b4
r3 := mul64(a0, b3)
r3 = addMul64(r3, a1, b2)
r3 = addMul64(r3, a2, b1)
r3 = addMul64(r3, a3, b0)
r3 = addMul64(r3, a4_19, b4)
// r4 = a0×b4 + a1×b3 + a2×b2 + a3×b1 + a4×b0
r4 := mul64(a0, b4)
r4 = addMul64(r4, a1, b3)
r4 = addMul64(r4, a2, b2)
r4 = addMul64(r4, a3, b1)
r4 = addMul64(r4, a4, b0)
// After the multiplication, we need to reduce (carry) the five coefficients
// to obtain a result with limbs that are at most slightly larger than 2⁵¹,
// to respect the Element invariant.
//
// Overall, the reduction works the same as carryPropagate, except with
// wider inputs: we take the carry for each coefficient by shifting it right
// by 51, and add it to the limb above it. The top carry is multiplied by 19
// according to the reduction identity and added to the lowest limb.
//
// The largest coefficient (r0) will be at most 111 bits, which guarantees
// that all carries are at most 111 - 51 = 60 bits, which fits in a uint64.
//
// r0 = a0×b0 + 19×(a1×b4 + a2×b3 + a3×b2 + a4×b1)
// r0 < 2⁵²×2⁵² + 19×(2⁵²×2⁵² + 2⁵²×2⁵² + 2⁵²×2⁵² + 2⁵²×2⁵²)
// r0 < (1 + 19 × 4) × 2⁵² × 2⁵²
// r0 < 2⁷ × 2⁵² × 2⁵²
// r0 < 2¹¹¹
//
// Moreover, the top coefficient (r4) is at most 107 bits, so c4 is at most
// 56 bits, and c4 * 19 is at most 61 bits, which again fits in a uint64 and
// allows us to easily apply the reduction identity.
//
// r4 = a0×b4 + a1×b3 + a2×b2 + a3×b1 + a4×b0
// r4 < 5 × 2⁵² × 2⁵²
// r4 < 2¹⁰⁷
//
c0 := shiftRightBy51(r0)
c1 := shiftRightBy51(r1)
c2 := shiftRightBy51(r2)
c3 := shiftRightBy51(r3)
c4 := shiftRightBy51(r4)
rr0 := r0.lo&maskLow51Bits + c4*19
rr1 := r1.lo&maskLow51Bits + c0
rr2 := r2.lo&maskLow51Bits + c1
rr3 := r3.lo&maskLow51Bits + c2
rr4 := r4.lo&maskLow51Bits + c3
// Now all coefficients fit into 64-bit registers but are still too large to
// be passed around as a Element. We therefore do one last carry chain,
// where the carries will be small enough to fit in the wiggle room above 2⁵¹.
*v = Element{rr0, rr1, rr2, rr3, rr4}
v.carryPropagate()
}
func feSquareGeneric(v, a *Element) {
l0 := a.l0
l1 := a.l1
l2 := a.l2
l3 := a.l3
l4 := a.l4
// Squaring works precisely like multiplication above, but thanks to its
// symmetry we get to group a few terms together.
//
// l4 l3 l2 l1 l0 x
// l4 l3 l2 l1 l0 =
// ------------------------
// l4l0 l3l0 l2l0 l1l0 l0l0 +
// l4l1 l3l1 l2l1 l1l1 l0l1 +
// l4l2 l3l2 l2l2 l1l2 l0l2 +
// l4l3 l3l3 l2l3 l1l3 l0l3 +
// l4l4 l3l4 l2l4 l1l4 l0l4 =
// ----------------------------------------------
// r8 r7 r6 r5 r4 r3 r2 r1 r0
//
// l4l0 l3l0 l2l0 l1l0 l0l0 +
// l3l1 l2l1 l1l1 l0l1 19×l4l1 +
// l2l2 l1l2 l0l2 19×l4l2 19×l3l2 +
// l1l3 l0l3 19×l4l3 19×l3l3 19×l2l3 +
// l0l4 19×l4l4 19×l3l4 19×l2l4 19×l1l4 =
// --------------------------------------
// r4 r3 r2 r1 r0
//
// With precomputed 2×, 19×, and 2×19× terms, we can compute each limb with
// only three Mul64 and four Add64, instead of five and eight.
l0_2 := l0 * 2
l1_2 := l1 * 2
l1_38 := l1 * 38
l2_38 := l2 * 38
l3_38 := l3 * 38
l3_19 := l3 * 19
l4_19 := l4 * 19
// r0 = l0×l0 + 19×(l1×l4 + l2×l3 + l3×l2 + l4×l1) = l0×l0 + 19×2×(l1×l4 + l2×l3)
r0 := mul64(l0, l0)
r0 = addMul64(r0, l1_38, l4)
r0 = addMul64(r0, l2_38, l3)
// r1 = l0×l1 + l1×l0 + 19×(l2×l4 + l3×l3 + l4×l2) = 2×l0×l1 + 19×2×l2×l4 + 19×l3×l3
r1 := mul64(l0_2, l1)
r1 = addMul64(r1, l2_38, l4)
r1 = addMul64(r1, l3_19, l3)
// r2 = l0×l2 + l1×l1 + l2×l0 + 19×(l3×l4 + l4×l3) = 2×l0×l2 + l1×l1 + 19×2×l3×l4
r2 := mul64(l0_2, l2)
r2 = addMul64(r2, l1, l1)
r2 = addMul64(r2, l3_38, l4)
// r3 = l0×l3 + l1×l2 + l2×l1 + l3×l0 + 19×l4×l4 = 2×l0×l3 + 2×l1×l2 + 19×l4×l4
r3 := mul64(l0_2, l3)
r3 = addMul64(r3, l1_2, l2)
r3 = addMul64(r3, l4_19, l4)
// r4 = l0×l4 + l1×l3 + l2×l2 + l3×l1 + l4×l0 = 2×l0×l4 + 2×l1×l3 + l2×l2
r4 := mul64(l0_2, l4)
r4 = addMul64(r4, l1_2, l3)
r4 = addMul64(r4, l2, l2)
c0 := shiftRightBy51(r0)
c1 := shiftRightBy51(r1)
c2 := shiftRightBy51(r2)
c3 := shiftRightBy51(r3)
c4 := shiftRightBy51(r4)
rr0 := r0.lo&maskLow51Bits + c4*19
rr1 := r1.lo&maskLow51Bits + c0
rr2 := r2.lo&maskLow51Bits + c1
rr3 := r3.lo&maskLow51Bits + c2
rr4 := r4.lo&maskLow51Bits + c3
*v = Element{rr0, rr1, rr2, rr3, rr4}
v.carryPropagate()
}
// carryPropagateGeneric brings the limbs below 52 bits by applying the reduction
// identity (a * 2²⁵⁵ + b = a * 19 + b) to the l4 carry. TODO inline
func (v *Element) carryPropagateGeneric() *Element {
c0 := v.l0 >> 51
c1 := v.l1 >> 51
c2 := v.l2 >> 51
c3 := v.l3 >> 51
c4 := v.l4 >> 51
v.l0 = v.l0&maskLow51Bits + c4*19
v.l1 = v.l1&maskLow51Bits + c0
v.l2 = v.l2&maskLow51Bits + c1
v.l3 = v.l3&maskLow51Bits + c2
v.l4 = v.l4&maskLow51Bits + c3
return v
}
-558
View File
@@ -1,558 +0,0 @@
// Copyright (c) 2017 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 field
import (
"bytes"
"crypto/rand"
"encoding/hex"
"io"
"math/big"
"math/bits"
mathrand "math/rand"
"reflect"
"testing"
"testing/quick"
)
func (v Element) String() string {
return hex.EncodeToString(v.Bytes())
}
// quickCheckConfig1024 will make each quickcheck test run (1024 * -quickchecks)
// times. The default value of -quickchecks is 100.
var quickCheckConfig1024 = &quick.Config{MaxCountScale: 1 << 10}
func generateFieldElement(rand *mathrand.Rand) Element {
const maskLow52Bits = (1 << 52) - 1
return Element{
rand.Uint64() & maskLow52Bits,
rand.Uint64() & maskLow52Bits,
rand.Uint64() & maskLow52Bits,
rand.Uint64() & maskLow52Bits,
rand.Uint64() & maskLow52Bits,
}
}
// weirdLimbs can be combined to generate a range of edge-case field elements.
// 0 and -1 are intentionally more weighted, as they combine well.
var (
weirdLimbs51 = []uint64{
0, 0, 0, 0,
1,
19 - 1,
19,
0x2aaaaaaaaaaaa,
0x5555555555555,
(1 << 51) - 20,
(1 << 51) - 19,
(1 << 51) - 1, (1 << 51) - 1,
(1 << 51) - 1, (1 << 51) - 1,
}
weirdLimbs52 = []uint64{
0, 0, 0, 0, 0, 0,
1,
19 - 1,
19,
0x2aaaaaaaaaaaa,
0x5555555555555,
(1 << 51) - 20,
(1 << 51) - 19,
(1 << 51) - 1, (1 << 51) - 1,
(1 << 51) - 1, (1 << 51) - 1,
(1 << 51) - 1, (1 << 51) - 1,
1 << 51,
(1 << 51) + 1,
(1 << 52) - 19,
(1 << 52) - 1,
}
)
func generateWeirdFieldElement(rand *mathrand.Rand) Element {
return Element{
weirdLimbs52[rand.Intn(len(weirdLimbs52))],
weirdLimbs51[rand.Intn(len(weirdLimbs51))],
weirdLimbs51[rand.Intn(len(weirdLimbs51))],
weirdLimbs51[rand.Intn(len(weirdLimbs51))],
weirdLimbs51[rand.Intn(len(weirdLimbs51))],
}
}
func (Element) Generate(rand *mathrand.Rand, size int) reflect.Value {
if rand.Intn(2) == 0 {
return reflect.ValueOf(generateWeirdFieldElement(rand))
}
return reflect.ValueOf(generateFieldElement(rand))
}
// isInBounds returns whether the element is within the expected bit size bounds
// after a light reduction.
func isInBounds(x *Element) bool {
return bits.Len64(x.l0) <= 52 &&
bits.Len64(x.l1) <= 52 &&
bits.Len64(x.l2) <= 52 &&
bits.Len64(x.l3) <= 52 &&
bits.Len64(x.l4) <= 52
}
func TestMultiplyDistributesOverAdd(t *testing.T) {
multiplyDistributesOverAdd := func(x, y, z Element) bool {
// Compute t1 = (x+y)*z
t1 := new(Element)
t1.Add(&x, &y)
t1.Multiply(t1, &z)
// Compute t2 = x*z + y*z
t2 := new(Element)
t3 := new(Element)
t2.Multiply(&x, &z)
t3.Multiply(&y, &z)
t2.Add(t2, t3)
return t1.Equal(t2) == 1 && isInBounds(t1) && isInBounds(t2)
}
if err := quick.Check(multiplyDistributesOverAdd, quickCheckConfig1024); err != nil {
t.Error(err)
}
}
func TestMul64to128(t *testing.T) {
a := uint64(5)
b := uint64(5)
r := mul64(a, b)
if r.lo != 0x19 || r.hi != 0 {
t.Errorf("lo-range wide mult failed, got %d + %d*(2**64)", r.lo, r.hi)
}
a = uint64(18014398509481983) // 2^54 - 1
b = uint64(18014398509481983) // 2^54 - 1
r = mul64(a, b)
if r.lo != 0xff80000000000001 || r.hi != 0xfffffffffff {
t.Errorf("hi-range wide mult failed, got %d + %d*(2**64)", r.lo, r.hi)
}
a = uint64(1125899906842661)
b = uint64(2097155)
r = mul64(a, b)
r = addMul64(r, a, b)
r = addMul64(r, a, b)
r = addMul64(r, a, b)
r = addMul64(r, a, b)
if r.lo != 16888498990613035 || r.hi != 640 {
t.Errorf("wrong answer: %d + %d*(2**64)", r.lo, r.hi)
}
}
func TestSetBytesRoundTrip(t *testing.T) {
f1 := func(in [32]byte, fe Element) bool {
fe.SetBytes(in[:])
// Mask the most significant bit as it's ignored by SetBytes. (Now
// instead of earlier so we check the masking in SetBytes is working.)
in[len(in)-1] &= (1 << 7) - 1
return bytes.Equal(in[:], fe.Bytes()) && isInBounds(&fe)
}
if err := quick.Check(f1, nil); err != nil {
t.Errorf("failed bytes->FE->bytes round-trip: %v", err)
}
f2 := func(fe, r Element) bool {
r.SetBytes(fe.Bytes())
// Intentionally not using Equal not to go through Bytes again.
// Calling reduce because both Generate and SetBytes can produce
// non-canonical representations.
fe.reduce()
r.reduce()
return fe == r
}
if err := quick.Check(f2, nil); err != nil {
t.Errorf("failed FE->bytes->FE round-trip: %v", err)
}
// Check some fixed vectors from dalek
type feRTTest struct {
fe Element
b []byte
}
var tests = []feRTTest{
{
fe: Element{358744748052810, 1691584618240980, 977650209285361, 1429865912637724, 560044844278676},
b: []byte{74, 209, 69, 197, 70, 70, 161, 222, 56, 226, 229, 19, 112, 60, 25, 92, 187, 74, 222, 56, 50, 153, 51, 233, 40, 74, 57, 6, 160, 185, 213, 31},
},
{
fe: Element{84926274344903, 473620666599931, 365590438845504, 1028470286882429, 2146499180330972},
b: []byte{199, 23, 106, 112, 61, 77, 216, 79, 186, 60, 11, 118, 13, 16, 103, 15, 42, 32, 83, 250, 44, 57, 204, 198, 78, 199, 253, 119, 146, 172, 3, 122},
},
}
for _, tt := range tests {
b := tt.fe.Bytes()
if !bytes.Equal(b, tt.b) || new(Element).SetBytes(tt.b).Equal(&tt.fe) != 1 {
t.Errorf("Failed fixed roundtrip: %v", tt)
}
}
}
func swapEndianness(buf []byte) []byte {
for i := 0; i < len(buf)/2; i++ {
buf[i], buf[len(buf)-i-1] = buf[len(buf)-i-1], buf[i]
}
return buf
}
func TestBytesBigEquivalence(t *testing.T) {
f1 := func(in [32]byte, fe, fe1 Element) bool {
fe.SetBytes(in[:])
in[len(in)-1] &= (1 << 7) - 1 // mask the most significant bit
b := new(big.Int).SetBytes(swapEndianness(in[:]))
fe1.fromBig(b)
if fe != fe1 {
return false
}
buf := make([]byte, 32) // pad with zeroes
copy(buf, swapEndianness(fe1.toBig().Bytes()))
return bytes.Equal(fe.Bytes(), buf) && isInBounds(&fe) && isInBounds(&fe1)
}
if err := quick.Check(f1, nil); err != nil {
t.Error(err)
}
}
// fromBig sets v = n, and returns v. The bit length of n must not exceed 256.
func (v *Element) fromBig(n *big.Int) *Element {
if n.BitLen() > 32*8 {
panic("edwards25519: invalid field element input size")
}
buf := make([]byte, 0, 32)
for _, word := range n.Bits() {
for i := 0; i < bits.UintSize; i += 8 {
if len(buf) >= cap(buf) {
break
}
buf = append(buf, byte(word))
word >>= 8
}
}
return v.SetBytes(buf[:32])
}
func (v *Element) fromDecimal(s string) *Element {
n, ok := new(big.Int).SetString(s, 10)
if !ok {
panic("not a valid decimal: " + s)
}
return v.fromBig(n)
}
// toBig returns v as a big.Int.
func (v *Element) toBig() *big.Int {
buf := v.Bytes()
words := make([]big.Word, 32*8/bits.UintSize)
for n := range words {
for i := 0; i < bits.UintSize; i += 8 {
if len(buf) == 0 {
break
}
words[n] |= big.Word(buf[0]) << big.Word(i)
buf = buf[1:]
}
}
return new(big.Int).SetBits(words)
}
func TestDecimalConstants(t *testing.T) {
sqrtM1String := "19681161376707505956807079304988542015446066515923890162744021073123829784752"
if exp := new(Element).fromDecimal(sqrtM1String); sqrtM1.Equal(exp) != 1 {
t.Errorf("sqrtM1 is %v, expected %v", sqrtM1, exp)
}
// d is in the parent package, and we don't want to expose d or fromDecimal.
// dString := "37095705934669439343138083508754565189542113879843219016388785533085940283555"
// if exp := new(Element).fromDecimal(dString); d.Equal(exp) != 1 {
// t.Errorf("d is %v, expected %v", d, exp)
// }
}
func TestSetBytesRoundTripEdgeCases(t *testing.T) {
// TODO: values close to 0, close to 2^255-19, between 2^255-19 and 2^255-1,
// and between 2^255 and 2^256-1. Test both the documented SetBytes
// behavior, and that Bytes reduces them.
}
// Tests self-consistency between Multiply and Square.
func TestConsistency(t *testing.T) {
var x Element
var x2, x2sq Element
x = Element{1, 1, 1, 1, 1}
x2.Multiply(&x, &x)
x2sq.Square(&x)
if x2 != x2sq {
t.Fatalf("all ones failed\nmul: %x\nsqr: %x\n", x2, x2sq)
}
var bytes [32]byte
_, err := io.ReadFull(rand.Reader, bytes[:])
if err != nil {
t.Fatal(err)
}
x.SetBytes(bytes[:])
x2.Multiply(&x, &x)
x2sq.Square(&x)
if x2 != x2sq {
t.Fatalf("all ones failed\nmul: %x\nsqr: %x\n", x2, x2sq)
}
}
func TestEqual(t *testing.T) {
x := Element{1, 1, 1, 1, 1}
y := Element{5, 4, 3, 2, 1}
eq := x.Equal(&x)
if eq != 1 {
t.Errorf("wrong about equality")
}
eq = x.Equal(&y)
if eq != 0 {
t.Errorf("wrong about inequality")
}
}
func TestInvert(t *testing.T) {
x := Element{1, 1, 1, 1, 1}
one := Element{1, 0, 0, 0, 0}
var xinv, r Element
xinv.Invert(&x)
r.Multiply(&x, &xinv)
r.reduce()
if one != r {
t.Errorf("inversion identity failed, got: %x", r)
}
var bytes [32]byte
_, err := io.ReadFull(rand.Reader, bytes[:])
if err != nil {
t.Fatal(err)
}
x.SetBytes(bytes[:])
xinv.Invert(&x)
r.Multiply(&x, &xinv)
r.reduce()
if one != r {
t.Errorf("random inversion identity failed, got: %x for field element %x", r, x)
}
zero := Element{}
x.Set(&zero)
if xx := xinv.Invert(&x); xx != &xinv {
t.Errorf("inverting zero did not return the receiver")
} else if xinv.Equal(&zero) != 1 {
t.Errorf("inverting zero did not return zero")
}
}
func TestSelectSwap(t *testing.T) {
a := Element{358744748052810, 1691584618240980, 977650209285361, 1429865912637724, 560044844278676}
b := Element{84926274344903, 473620666599931, 365590438845504, 1028470286882429, 2146499180330972}
var c, d Element
c.Select(&a, &b, 1)
d.Select(&a, &b, 0)
if c.Equal(&a) != 1 || d.Equal(&b) != 1 {
t.Errorf("Select failed")
}
c.Swap(&d, 0)
if c.Equal(&a) != 1 || d.Equal(&b) != 1 {
t.Errorf("Swap failed")
}
c.Swap(&d, 1)
if c.Equal(&b) != 1 || d.Equal(&a) != 1 {
t.Errorf("Swap failed")
}
}
func TestMult32(t *testing.T) {
mult32EquivalentToMul := func(x Element, y uint32) bool {
t1 := new(Element)
for i := 0; i < 100; i++ {
t1.Mult32(&x, y)
}
ty := new(Element)
ty.l0 = uint64(y)
t2 := new(Element)
for i := 0; i < 100; i++ {
t2.Multiply(&x, ty)
}
return t1.Equal(t2) == 1 && isInBounds(t1) && isInBounds(t2)
}
if err := quick.Check(mult32EquivalentToMul, quickCheckConfig1024); err != nil {
t.Error(err)
}
}
func TestSqrtRatio(t *testing.T) {
// From draft-irtf-cfrg-ristretto255-decaf448-00, Appendix A.4.
type test struct {
u, v string
wasSquare int
r string
}
var tests = []test{
// If u is 0, the function is defined to return (0, TRUE), even if v
// is zero. Note that where used in this package, the denominator v
// is never zero.
{
"0000000000000000000000000000000000000000000000000000000000000000",
"0000000000000000000000000000000000000000000000000000000000000000",
1, "0000000000000000000000000000000000000000000000000000000000000000",
},
// 0/1 == 0²
{
"0000000000000000000000000000000000000000000000000000000000000000",
"0100000000000000000000000000000000000000000000000000000000000000",
1, "0000000000000000000000000000000000000000000000000000000000000000",
},
// If u is non-zero and v is zero, defined to return (0, FALSE).
{
"0100000000000000000000000000000000000000000000000000000000000000",
"0000000000000000000000000000000000000000000000000000000000000000",
0, "0000000000000000000000000000000000000000000000000000000000000000",
},
// 2/1 is not square in this field.
{
"0200000000000000000000000000000000000000000000000000000000000000",
"0100000000000000000000000000000000000000000000000000000000000000",
0, "3c5ff1b5d8e4113b871bd052f9e7bcd0582804c266ffb2d4f4203eb07fdb7c54",
},
// 4/1 == 2²
{
"0400000000000000000000000000000000000000000000000000000000000000",
"0100000000000000000000000000000000000000000000000000000000000000",
1, "0200000000000000000000000000000000000000000000000000000000000000",
},
// 1/4 == (2⁻¹)² == (2^(p-2))² per Euler's theorem
{
"0100000000000000000000000000000000000000000000000000000000000000",
"0400000000000000000000000000000000000000000000000000000000000000",
1, "f6ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff3f",
},
}
for i, tt := range tests {
u := new(Element).SetBytes(decodeHex(tt.u))
v := new(Element).SetBytes(decodeHex(tt.v))
want := new(Element).SetBytes(decodeHex(tt.r))
got, wasSquare := new(Element).SqrtRatio(u, v)
if got.Equal(want) == 0 || wasSquare != tt.wasSquare {
t.Errorf("%d: got (%v, %v), want (%v, %v)", i, got, wasSquare, want, tt.wasSquare)
}
}
}
func TestCarryPropagate(t *testing.T) {
asmLikeGeneric := func(a [5]uint64) bool {
t1 := &Element{a[0], a[1], a[2], a[3], a[4]}
t2 := &Element{a[0], a[1], a[2], a[3], a[4]}
t1.carryPropagate()
t2.carryPropagateGeneric()
if *t1 != *t2 {
t.Logf("got: %#v,\nexpected: %#v", t1, t2)
}
return *t1 == *t2 && isInBounds(t2)
}
if err := quick.Check(asmLikeGeneric, quickCheckConfig1024); err != nil {
t.Error(err)
}
if !asmLikeGeneric([5]uint64{0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff}) {
t.Errorf("failed for {0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff}")
}
}
func TestFeSquare(t *testing.T) {
asmLikeGeneric := func(a Element) bool {
t1 := a
t2 := a
feSquareGeneric(&t1, &t1)
feSquare(&t2, &t2)
if t1 != t2 {
t.Logf("got: %#v,\nexpected: %#v", t1, t2)
}
return t1 == t2 && isInBounds(&t2)
}
if err := quick.Check(asmLikeGeneric, quickCheckConfig1024); err != nil {
t.Error(err)
}
}
func TestFeMul(t *testing.T) {
asmLikeGeneric := func(a, b Element) bool {
a1 := a
a2 := a
b1 := b
b2 := b
feMulGeneric(&a1, &a1, &b1)
feMul(&a2, &a2, &b2)
if a1 != a2 || b1 != b2 {
t.Logf("got: %#v,\nexpected: %#v", a1, a2)
t.Logf("got: %#v,\nexpected: %#v", b1, b2)
}
return a1 == a2 && isInBounds(&a2) &&
b1 == b2 && isInBounds(&b2)
}
if err := quick.Check(asmLikeGeneric, quickCheckConfig1024); err != nil {
t.Error(err)
}
}
func decodeHex(s string) []byte {
b, err := hex.DecodeString(s)
if err != nil {
panic(err)
}
return b
}
@@ -1 +0,0 @@
b0c49ae9f59d233526f8934262c5bbbe14d4358d
-19
View File
@@ -1,19 +0,0 @@
#! /bin/bash
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"
STD_PATH=src/crypto/ed25519/internal/edwards25519/field
LOCAL_PATH=curve25519/internal/field
LAST_SYNC_REF=$(cat $LOCAL_PATH/sync.checkpoint)
git fetch https://go.googlesource.com/go master
if git diff --quiet $LAST_SYNC_REF:$STD_PATH FETCH_HEAD:$STD_PATH; then
echo "No changes."
else
NEW_REF=$(git rev-parse FETCH_HEAD | tee $LOCAL_PATH/sync.checkpoint)
echo "Applying changes from $LAST_SYNC_REF to $NEW_REF..."
git diff $LAST_SYNC_REF:$STD_PATH FETCH_HEAD:$STD_PATH | \
git apply -3 --directory=$LOCAL_PATH
fi
+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.
package curve25519
package curve25519_test
// lowOrderPoints from libsodium.
// https://github.com/jedisct1/libsodium/blob/65621a1059a37d/src/libsodium/crypto_scalarmult/curve25519/ref10/x25519_ref10.c#L11-L70
+7 -6
View File
@@ -2,18 +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”.
//
// Beginning with Go 1.13, the functionality of this package was moved to the
// standard library as crypto/ed25519. This package only acts as a compatibility
// wrapper.
// 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.17
go 1.24.0
require (
golang.org/x/net v0.8.0
golang.org/x/sys v0.6.0
golang.org/x/term v0.6.0
golang.org/x/net v0.47.0 // tagx:ignore
golang.org/x/sys v0.38.0
golang.org/x/term v0.37.0
)
require golang.org/x/text v0.8.0 // indirect
require golang.org/x/text v0.31.0 // indirect
+8 -38
View File
@@ -1,38 +1,8 @@
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ=
golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw=
golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68=
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU=
golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=

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