271 lines
9.8 KiB
Go
271 lines
9.8 KiB
Go
package attestation
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"strings"
|
|
)
|
|
|
|
// InTotoPayloadType is the DSSE payloadType of an in-toto Statement.
|
|
const InTotoPayloadType = "application/vnd.in-toto+json"
|
|
|
|
// ProvenanceExpectation is what a verified provenance must say. Every field
|
|
// is compared exactly — never as a substring of the raw cosign output.
|
|
type ProvenanceExpectation struct {
|
|
// Image the attestations were fetched for; must be digest-pinned, and a
|
|
// statement only counts when one of its subjects carries that sha256.
|
|
Image string
|
|
// BuilderID must equal predicate.runDetails.builder.id byte for byte.
|
|
BuilderID string
|
|
// SourceRepo is the repository URI without a ref or commit, e.g.
|
|
// "https://github.com/acme/app". A resolvedDependency counts when its uri,
|
|
// with an optional `git+` prefix and `.git` suffix, is that repository
|
|
// alone or that repository followed by `@<ref>`.
|
|
SourceRepo string
|
|
}
|
|
|
|
// VerifiedProvenance describes the statement that satisfied the expectation.
|
|
type VerifiedProvenance struct {
|
|
BuilderID string
|
|
SourceURI string
|
|
Subjects []string // "<name>@sha256:<hex>" for each sha256 subject
|
|
}
|
|
|
|
type envelope struct {
|
|
PayloadType string `json:"payloadType"`
|
|
Payload string `json:"payload"`
|
|
Signatures []json.RawMessage `json:"signatures"`
|
|
}
|
|
|
|
type provenancePredicate struct {
|
|
BuildDefinition struct {
|
|
ResolvedDependencies []struct {
|
|
URI string `json:"uri"`
|
|
Digest map[string]string `json:"digest"`
|
|
} `json:"resolvedDependencies"`
|
|
} `json:"buildDefinition"`
|
|
RunDetails struct {
|
|
Builder struct {
|
|
ID string `json:"id"`
|
|
} `json:"builder"`
|
|
} `json:"runDetails"`
|
|
}
|
|
|
|
// VerifyAttestationArgs is the `cosign verify-attestation` command line for a
|
|
// keyless provenance check. The signer is the trust anchor, not the builder.id
|
|
// string inside what it signed: with no identityRegex the certificate identity
|
|
// must equal builderID exactly, so a statement that names the expected builder
|
|
// only counts when that builder signed it.
|
|
//
|
|
// Both regexes are anchored to the whole value (AnchorRegex, #2435): cosign
|
|
// matches anywhere in the string, so an unanchored issuer regex also admitted
|
|
// an issuer that merely contained the expected one.
|
|
func VerifyAttestationArgs(image, builderID, identityRegex, issuerRegex string) []string {
|
|
args := []string{
|
|
"cosign", "verify-attestation",
|
|
"--type", "slsaprovenance1",
|
|
"--certificate-oidc-issuer-regexp", AnchorRegex(issuerRegex),
|
|
}
|
|
if identityRegex != "" {
|
|
args = append(args, "--certificate-identity-regexp", AnchorRegex(identityRegex))
|
|
} else {
|
|
args = append(args, "--certificate-identity", builderID)
|
|
}
|
|
return append(args, image)
|
|
}
|
|
|
|
// VerifyProvenanceOutput checks the stdout of `cosign verify-attestation
|
|
// --type slsaprovenance1`: one DSSE envelope per verified attestation (cosign
|
|
// v2 prints `sig.Payload()` of each; certificate details go to stderr).
|
|
//
|
|
// cosign has already checked the signatures and the predicate type; this
|
|
// checks what the signed statement SAYS. It succeeds when at least one
|
|
// envelope decodes to an in-toto Statement whose predicate is SLSA v1
|
|
// provenance, whose subject includes the image digest, whose builder.id equals
|
|
// the expected builder, and whose SOURCE — the first resolvedDependency, which
|
|
// is where SLSA builders and both producers in this repo put it — is the
|
|
// expected repository pinned to a commit. Later dependencies are inputs, not
|
|
// the source: a repo that vendors the expected one must not pass as it.
|
|
//
|
|
// builder.id is a string the signer wrote; it is only as trustworthy as the
|
|
// signing identity cosign checked. The caller binds the two (VerifyProvenance
|
|
// passes --certificate-identity=<builder id> unless given a regex).
|
|
//
|
|
// Fail-closed: output that is not a stream of DSSE envelopes, an envelope that
|
|
// is not an in-toto payload or does not decode, and empty output are refused
|
|
// outright rather than skipped — cosign printing something we cannot read is
|
|
// not evidence of anything. The whole stream is read before deciding, so this
|
|
// holds after a match too. Well-formed statements that simply do not match
|
|
// (another builder signing the same digest) do not count, and the error names
|
|
// what each one got wrong.
|
|
func VerifyProvenanceOutput(out []byte, want ProvenanceExpectation) (*VerifiedProvenance, error) {
|
|
digest, err := ImageDigest(want.Image)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if want.BuilderID == "" || strings.TrimSpace(want.BuilderID) != want.BuilderID {
|
|
return nil, fmt.Errorf("expected builder id %q must be non-empty with no surrounding whitespace", want.BuilderID)
|
|
}
|
|
repo := normaliseRepo(want.SourceRepo)
|
|
if repo == "" || strings.ContainsAny(want.SourceRepo, " \t\r\n") {
|
|
return nil, fmt.Errorf("expected source repo %q must be a non-empty URI without whitespace", want.SourceRepo)
|
|
}
|
|
if carriesRef(repo) {
|
|
// "…/app@refs/heads/main" as the expectation would make every ref of
|
|
// that branch name match, and reads as if the ref were checked.
|
|
return nil, fmt.Errorf("expected source repo %q must not carry a ref (drop the @<ref> suffix)", want.SourceRepo)
|
|
}
|
|
|
|
dec := json.NewDecoder(bytes.NewReader(out))
|
|
var mismatches []string
|
|
var found *VerifiedProvenance
|
|
n := 0
|
|
for {
|
|
var env envelope
|
|
if err := dec.Decode(&env); errors.Is(err, io.EOF) {
|
|
break
|
|
} else if err != nil {
|
|
return nil, fmt.Errorf("cosign output is not a stream of DSSE envelopes: %w", err)
|
|
}
|
|
n++
|
|
st, err := decodeEnvelope(env)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("attestation %d: %w", n, err)
|
|
}
|
|
vp, why := matchStatement(st, digest, want.BuilderID, repo)
|
|
if vp != nil {
|
|
if found == nil {
|
|
found = vp
|
|
}
|
|
continue
|
|
}
|
|
mismatches = append(mismatches, fmt.Sprintf("attestation %d: %s", n, why))
|
|
}
|
|
if n == 0 {
|
|
return nil, fmt.Errorf("cosign verified no provenance attestation")
|
|
}
|
|
if found != nil {
|
|
return found, nil
|
|
}
|
|
return nil, fmt.Errorf("no provenance matches builder %q, source %q and sha256 %s (%s)",
|
|
want.BuilderID, want.SourceRepo, digest, strings.Join(mismatches, "; "))
|
|
}
|
|
|
|
func decodeEnvelope(env envelope) (*statement, error) {
|
|
if env.PayloadType != InTotoPayloadType {
|
|
return nil, fmt.Errorf("DSSE payloadType %q is not %s", env.PayloadType, InTotoPayloadType)
|
|
}
|
|
if len(env.Signatures) == 0 {
|
|
return nil, fmt.Errorf("DSSE envelope carries no signature")
|
|
}
|
|
raw, err := base64.StdEncoding.DecodeString(env.Payload)
|
|
if err != nil {
|
|
// Some producers emit URL-safe base64; DSSE allows either.
|
|
if raw, err = base64.URLEncoding.DecodeString(env.Payload); err != nil {
|
|
return nil, fmt.Errorf("DSSE payload is not base64: %w", err)
|
|
}
|
|
}
|
|
var st statement
|
|
if err := json.Unmarshal(raw, &st); err != nil {
|
|
return nil, fmt.Errorf("DSSE payload is not an in-toto Statement: %w", err)
|
|
}
|
|
switch st.Type {
|
|
case "https://in-toto.io/Statement/v1", "https://in-toto.io/Statement/v0.1":
|
|
default:
|
|
return nil, fmt.Errorf("statement _type %q is not an in-toto Statement", st.Type)
|
|
}
|
|
return &st, nil
|
|
}
|
|
|
|
// matchStatement returns the verified provenance, or why the statement does
|
|
// not satisfy the expectation.
|
|
func matchStatement(st *statement, digest, builderID, repo string) (*VerifiedProvenance, string) {
|
|
if st.PredicateType != SLSAProvenanceV1 {
|
|
return nil, fmt.Sprintf("predicateType %q is not %s", st.PredicateType, SLSAProvenanceV1)
|
|
}
|
|
var subjects []string
|
|
about := false
|
|
for _, s := range st.Subject {
|
|
d := strings.ToLower(s.Digest["sha256"])
|
|
if d == "" {
|
|
continue
|
|
}
|
|
subjects = append(subjects, s.Name+"@sha256:"+d)
|
|
if d == digest {
|
|
about = true
|
|
}
|
|
}
|
|
if !about {
|
|
return nil, fmt.Sprintf("no subject with sha256 %s", digest)
|
|
}
|
|
var p provenancePredicate
|
|
if err := json.Unmarshal(st.Predicate, &p); err != nil {
|
|
return nil, fmt.Sprintf("predicate is not SLSA v1 provenance: %v", err)
|
|
}
|
|
if got := p.RunDetails.Builder.ID; got != builderID {
|
|
return nil, fmt.Sprintf("builder.id is %q", got)
|
|
}
|
|
deps := p.BuildDefinition.ResolvedDependencies
|
|
if len(deps) == 0 {
|
|
return nil, "no resolvedDependencies: the source is not recorded"
|
|
}
|
|
src := deps[0]
|
|
if !sameRepo(src.URI, repo) {
|
|
return nil, fmt.Sprintf("source (first resolvedDependency) is %q", src.URI)
|
|
}
|
|
if !pinnedToCommit(src.Digest) {
|
|
return nil, "source is not pinned to a commit (gitCommit/sha1/sha256 of 40 or 64 hex)"
|
|
}
|
|
return &VerifiedProvenance{BuilderID: builderID, SourceURI: src.URI, Subjects: subjects}, ""
|
|
}
|
|
|
|
// pinnedToCommit reports a gitCommit / sha1 / sha256 digest that is a full
|
|
// commit id. `{"gitCommit": "main"}` is a branch name, not a pin.
|
|
func pinnedToCommit(d map[string]string) bool {
|
|
for _, k := range []string{"gitCommit", "sha1", "sha256"} {
|
|
if commitID.MatchString(strings.ToLower(d[k])) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// normaliseRepo drops the `git+` transport prefix and a trailing `.git` / `/`.
|
|
func normaliseRepo(u string) string {
|
|
u = strings.TrimPrefix(strings.TrimSpace(u), "git+")
|
|
u = strings.TrimSuffix(u, "/")
|
|
return strings.TrimSuffix(u, ".git")
|
|
}
|
|
|
|
// carriesRef reports an "@" in the path of a URL ("https://h/o/r@ref"). The
|
|
// userinfo "@" of "https://u@h/o/r" and of scp-style "git@h:o/r" is allowed.
|
|
func carriesRef(repo string) bool {
|
|
i := strings.Index(repo, "://")
|
|
if i < 0 {
|
|
colon := strings.Index(repo, ":")
|
|
if colon < 0 {
|
|
return strings.Contains(repo, "@")
|
|
}
|
|
return strings.LastIndex(repo, "@") > colon
|
|
}
|
|
rest := repo[i+3:]
|
|
slash := strings.Index(rest, "/")
|
|
return slash >= 0 && strings.Contains(rest[slash:], "@")
|
|
}
|
|
|
|
// sameRepo reports whether a dependency uri names repo: exactly, or repo
|
|
// followed by "@<ref>". "…/app-evil@…" and "…/app/fork@…" do not match "…/app".
|
|
func sameRepo(uri, repo string) bool {
|
|
u := strings.TrimPrefix(strings.TrimSpace(uri), "git+")
|
|
for _, r := range []string{repo, repo + ".git"} {
|
|
if u == r || u == r+"/" || strings.HasPrefix(u, r+"@") {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|