Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions pkg/generate/checksumfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import (
type ChecksumFile struct {
// Asset is the file's name in the release.
Asset string
// Algorithm is the hash the file lists, which is always the one every entry records.
// Algorithm is the hash the file's name says it lists. What is compared goes by each
// digest's length instead, since a name can be wrong: caddy's checksums.txt lists SHA512.
Algorithm string
// Cosign is how the file is signed, held to the signer the signature names.
Cosign *aquaregistry.Cosign
Expand All @@ -39,8 +40,9 @@ func (g *Generator) checksumFiles(ctx context.Context, logger *slog.Logger, inpu
// an asset whose digest disagrees with what the signed file lists isn't what the release
// published, however it got there.
//
// Only the files listing sha256 are read, which is the hash every entry records. A file
// nothing signs vouches for nothing, and is left alone. The signer is read off the
// Whatever hash a file lists, it is read: what an asset hashes to is computed under each one
// a checksum file may list as it is downloaded. A file nothing signs vouches for nothing, and
// is left alone. The signer is read off the
// signature, the way it is for an asset.
func (g *Generator) signedChecksumFiles(ctx context.Context, logger *slog.Logger, input *Input, names map[string]struct{}) []*ChecksumFile {
owner, name, err := repo(input.PkgName)
Expand All @@ -50,7 +52,7 @@ func (g *Generator) signedChecksumFiles(ctx context.Context, logger *slog.Logger
var out []*ChecksumFile
for _, file := range slices.Sorted(maps.Keys(names)) {
cfg := checksum.GetChecksumConfigFromFilename(file, input.Version)
if cfg == nil || cfg.Algorithm != checksumAlgorithm {
if cfg == nil {
continue
}
cosign := genrgst.InferCosign(owner, name, file, names)
Expand Down
21 changes: 18 additions & 3 deletions pkg/generate/checksumfile_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import (
"testing"
)

// A checksum file cosign signs is found, held to the signer its certificate names. One
// nothing signs, and one listing a hash no entry records, are left alone.
// A checksum file cosign signs is found, held to the signer its certificate names, One nothing
// signs is left alone.
func TestSignedChecksumFiles(t *testing.T) {
t.Parallel()
const signedBy = "https://github.com/foo/foo/.github/workflows/release.yaml@refs/tags/v1.0.0"
Expand All @@ -15,7 +15,6 @@ func TestSignedChecksumFiles(t *testing.T) {
files := g.signedChecksumFiles(context.Background(), discardLogger(), &Input{PkgName: "foo/foo", Version: "v1.0.0"}, names(
"foo_linux_amd64.tar.gz",
"checksums.txt", "checksums.txt.sig", "checksums.txt.pem",
"sha512sums.txt", "sha512sums.txt.sig", "sha512sums.txt.pem",
"other_checksums.txt",
))
if len(files) != 1 {
Expand All @@ -38,3 +37,19 @@ func TestSignedChecksumFiles(t *testing.T) {
t.Errorf("the signer isn't the one the certificate names: %v", f.Cosign.Opts)
}
}

// A checksum file listing a hash other than SHA256 is read too: what is compared goes by
// each digest's length, and every algorithm a file may list is computed as the asset is
// downloaded.
func TestSignedChecksumFiles_sha512(t *testing.T) {
t.Parallel()
const signedBy = "https://github.com/foo/foo/.github/workflows/release.yaml@refs/tags/v1.0.0"
download := "/foo/foo/releases/download/v1.0.0/"
g := serving(t, map[string][]byte{download + "sha512sums.txt.pem": certificatePEM(t, signedBy, issuer)})
files := g.signedChecksumFiles(context.Background(), discardLogger(), &Input{PkgName: "foo/foo", Version: "v1.0.0"}, names(
"foo_linux_amd64.tar.gz", "sha512sums.txt", "sha512sums.txt.sig", "sha512sums.txt.pem",
))
if len(files) != 1 || files[0].Asset != "sha512sums.txt" || files[0].Algorithm != "sha512" {
t.Fatalf("the signed checksum files are %+v", files)
}
}
42 changes: 36 additions & 6 deletions pkg/verify/checksumfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,19 @@ import (
"github.com/aquaproj/ar2/pkg/generate"
)

// CheckChecksumFiles holds each entry's checksum to what the release's signed checksum files
// list for its asset.
// CheckChecksumFiles holds each entry's asset to what the release's signed checksum files
// list for it.
//
// The signature is checked first, the way an asset's is, and the file is read only once it
// holds. An asset the file lists under another digest isn't what the release published,
// which is ErrTampered; an asset the file doesn't list is nothing the file says anything
// about.
//
// Which algorithm the file lists is read off each digest's length rather than the file's
// name: caddy's checksums.txt lists SHA512. A SHA256 is held to the entry's checksum, and
// any other to what the asset hashed to when it was downloaded. An asset that wasn't
// downloaded has only its SHA256, so a digest of another algorithm says nothing checkable
// about it.
func (v *Verifier) CheckChecksumFiles(ctx context.Context, logger *slog.Logger, pkgName, version string, reg *generate.Registry, files []*generate.ChecksumFile) error {
if v.signatures == nil || len(files) == 0 || len(reg.Assets) == 0 {
return nil
Expand All @@ -31,12 +37,19 @@ func (v *Verifier) CheckChecksumFiles(ctx context.Context, logger *slog.Logger,
}
for _, asset := range reg.Assets {
want, ok := checksum.FindChecksum(listed, asset.Asset)
if !ok || asset.Checksum == "" {
if !ok {
continue
}
algo := algorithmOf(want)
got := v.digestOf(version, asset, algo)
if got == "" {
logger.Debug("the checksum file lists a digest nothing here can be compared with",
"checksum_file", file.Asset, "asset", asset.Asset, "algorithm", algo)
continue
}
if !strings.EqualFold(want, asset.Checksum) {
return fmt.Errorf("%w: %s lists %s for %s, which hashes to %s",
ErrTampered, file.Asset, want, asset.Asset, asset.Checksum)
if !strings.EqualFold(want, got) {
return fmt.Errorf("%w: %s lists %s %s for %s, which hashes to %s",
ErrTampered, file.Asset, algo, want, asset.Asset, got)
}
}
logger.Debug("the entries agree with the signed checksum file", "checksum_file", file.Asset)
Expand Down Expand Up @@ -92,3 +105,20 @@ func (v *Verifier) checksumFile(ctx context.Context, logger *slog.Logger, pkgNam
}
return listed, nil
}

// digestOf returns what the entry's asset hashes to under algo, or an empty string when
// nothing here knows: an algorithm the length named none of, or an asset that wasn't
// downloaded and so has only the SHA256 its entry records.
func (v *Verifier) digestOf(version string, asset *generate.Asset, algo string) string {
if algo == "" {
return ""
}
if algo == algoSHA256 && asset.Checksum != "" {
return asset.Checksum
}
url, err := downloadURL(version, asset)
if err != nil {
return ""
}
return v.digests.of(url, algo)
}
92 changes: 87 additions & 5 deletions pkg/verify/checksumfile_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,17 @@ package verify
import (
"context"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"

"github.com/aquaproj/ar2/pkg/generate"
"github.com/aquaproj/ar2/pkg/sign"
"github.com/google/go-cmp/cmp"
)

// toServer sends every request to the test server, whatever host it names: the checksum file
Expand Down Expand Up @@ -38,8 +41,8 @@ func (failingSignatures) Check(_ context.Context, _ *slog.Logger, _, _ string, _

func checksumRegistry() *generate.Registry {
return &generate.Registry{Assets: []*generate.Asset{
{OS: "linux", Arch: "amd64", Type: "github_release", RepoOwner: "foo", RepoName: "foo", Asset: "foo_linux_amd64.tar.gz", Checksum: "aaaa"},
{OS: "darwin", Arch: "arm64", Type: "github_release", RepoOwner: "foo", RepoName: "foo", Asset: "foo_darwin_arm64.tar.gz", Checksum: "BBBB"},
{OS: "linux", Arch: "amd64", Type: "github_release", RepoOwner: "foo", RepoName: "foo", Asset: "foo_linux_amd64.tar.gz", Checksum: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
{OS: "darwin", Arch: "arm64", Type: "github_release", RepoOwner: "foo", RepoName: "foo", Asset: "foo_darwin_arm64.tar.gz", Checksum: "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"},
}}
}

Expand Down Expand Up @@ -70,15 +73,15 @@ func TestCheckChecksumFiles(t *testing.T) {
// doesn't list is nothing it says anything about.
name: "the entries agree",
status: http.StatusOK,
content: "aaaa foo_linux_amd64.tar.gz\nbbbb foo_darwin_arm64.tar.gz\ncccc foo_windows_amd64.zip\n",
content: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa foo_linux_amd64.tar.gz\nbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb foo_darwin_arm64.tar.gz\ncccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc foo_windows_amd64.zip\n",
signatures: &recordingSignatures{},
check: func(err error) bool { return err == nil },
want: "no error",
},
{
name: "an entry disagrees",
status: http.StatusOK,
content: "aaaa foo_linux_amd64.tar.gz\ndddd foo_darwin_arm64.tar.gz\n",
content: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa foo_linux_amd64.tar.gz\ndddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd foo_darwin_arm64.tar.gz\n",
signatures: &recordingSignatures{},
check: Tampered,
want: "tampering",
Expand All @@ -87,7 +90,7 @@ func TestCheckChecksumFiles(t *testing.T) {
// The file is read only once its signature holds.
name: "the signature doesn't verify",
status: http.StatusOK,
content: "aaaa foo_linux_amd64.tar.gz\n",
content: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa foo_linux_amd64.tar.gz\n",
signatures: failingSignatures{},
check: Tampered,
want: "tampering",
Expand Down Expand Up @@ -120,3 +123,82 @@ func TestCheckChecksumFiles_nothingToCheck(t *testing.T) {
t.Fatal(err)
}
}

// caddy's checksums.txt lists SHA512, which its name doesn't say. The digest's length does,
// and the asset is held to what it hashed to under that algorithm when it was downloaded
// rather than to its SHA256.
func TestCheckChecksumFiles_sha512(t *testing.T) {
t.Parallel()
files := []*generate.ChecksumFile{{Asset: "checksums.txt", Algorithm: "sha256"}}
sha512Of := func(c string) string { return strings.Repeat(c, 128) }
tests := []struct {
name string
content string
check func(error) bool
want string
}{
{
name: "the asset agrees",
content: sha512Of("e") + " foo_linux_amd64.tar.gz\n",
check: func(err error) bool { return err == nil },
want: "no error",
},
{
name: "the asset disagrees",
content: sha512Of("f") + " foo_linux_amd64.tar.gz\n",
check: Tampered,
want: "tampering",
},
{
// The darwin asset wasn't downloaded, so nothing here knows its SHA512 and the
// file says nothing checkable about it.
name: "an asset that wasn't downloaded",
content: sha512Of("f") + " foo_darwin_arm64.tar.gz\n",
check: func(err error) bool { return err == nil },
want: "no error",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
v := New(checksumServer(t, http.StatusOK, tt.content), &recordingSignatures{})
reg := checksumRegistry()
url, err := downloadURL("v1.0.0", reg.Assets[0])
if err != nil {
t.Fatal(err)
}
v.digests.record(url, map[string]string{algoSHA512: sha512Of("e")})
err = v.CheckChecksumFiles(context.Background(), discardLogger(), "foo/foo", "v1.0.0", reg, files)
if !tt.check(err) {
t.Errorf("got %v, want %s", err, tt.want)
}
})
}
}

func TestAlgorithmOf(t *testing.T) {
t.Parallel()
for n, want := range map[int]string{32: "md5", 40: "sha1", 64: "sha256", 128: "sha512", 4: "", 96: ""} {
if got := algorithmOf(strings.Repeat("a", n)); got != want {
t.Errorf("a digest of %d digits is %q, want %q", n, got, want)
}
}
}

// The digests are computed while the asset streams past, one per algorithm.
func TestHasher(t *testing.T) {
t.Parallel()
h := newHasher()
if _, err := io.WriteString(h.writer(), "abc"); err != nil {
t.Fatal(err)
}
want := map[string]string{
"md5": "900150983cd24fb0d6963f7d28e17f72",
"sha1": "a9993e364706816aba3e25717850c26c9cd0d89d",
"sha256": "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
"sha512": "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f",
}
if diff := cmp.Diff(want, h.sums()); diff != "" {
t.Error(diff)
}
}
96 changes: 96 additions & 0 deletions pkg/verify/digest.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package verify

import (
"crypto/md5" //nolint:gosec // a checksum file may list MD5, and what it lists is what is compared
"crypto/sha1" //nolint:gosec // a checksum file may list SHA1, and what it lists is what is compared
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"hash"
"io"
"sync"
)

// The algorithms a checksum file may list, as aqua names them.
const (
algoMD5 = "md5"
algoSHA1 = "sha1"
algoSHA256 = "sha256"
algoSHA512 = "sha512"
)

// algorithmOf says which algorithm a digest written in hex is from, by its length, or
// returns an empty string for a length none of them has.
//
// A checksum file's name doesn't say reliably: caddy_2.11.9_checksums.txt lists SHA512,
// where a name with no algorithm in it is taken for SHA256. The digest itself does, since
// each algorithm's is a length of its own.
func algorithmOf(digest string) string {
switch len(digest) {
case md5.Size * 2: //nolint:mnd // two hex digits a byte
return algoMD5
case sha1.Size * 2: //nolint:mnd // two hex digits a byte
return algoSHA1
case sha256.Size * 2: //nolint:mnd // two hex digits a byte
return algoSHA256
case sha512.Size * 2: //nolint:mnd // two hex digits a byte
return algoSHA512
}
return ""
}

// hasher computes every digest a checksum file may list while the asset streams past, so
// the asset is downloaded once whatever the file turns out to list.
type hasher struct {
hashes map[string]hash.Hash
}

func newHasher() *hasher {
return &hasher{hashes: map[string]hash.Hash{
algoMD5: md5.New(), //nolint:gosec // see the import
algoSHA1: sha1.New(), //nolint:gosec // see the import
algoSHA256: sha256.New(),
algoSHA512: sha512.New(),
}}
}

// writer is what the asset is copied through.
func (h *hasher) writer() io.Writer {
ws := make([]io.Writer, 0, len(h.hashes))
for _, w := range h.hashes {
ws = append(ws, w)
}
return io.MultiWriter(ws...)
}

// sums returns each digest in hex, by algorithm.
func (h *hasher) sums() map[string]string {
out := make(map[string]string, len(h.hashes))
for algo, w := range h.hashes {
out[algo] = hex.EncodeToString(w.Sum(nil))
}
return out
}

// digests holds what each downloaded asset hashes to, by URL and then by algorithm.
type digests struct {
mu sync.Mutex
sums map[string]map[string]string
}

func (d *digests) record(url string, sums map[string]string) {
d.mu.Lock()
defer d.mu.Unlock()
if d.sums == nil {
d.sums = map[string]map[string]string{}
}
d.sums[url] = sums
}

// of returns what the asset at url hashes to under algo, or an empty string when it wasn't
// downloaded.
func (d *digests) of(url, algo string) string {
d.mu.Lock()
defer d.mu.Unlock()
return d.sums[url][algo]
}
Loading
Loading