| 1 |
package internal |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"crypto" |
| 6 |
"encoding/base64" |
| 7 |
"encoding/json" |
| 8 |
"errors" |
| 9 |
"fmt" |
| 10 |
"strings" |
| 11 |
"time" |
| 12 |
|
| 13 |
digest "github.com/opencontainers/go-digest" |
| 14 |
sigstoreSignature "github.com/sigstore/sigstore/pkg/signature" |
| 15 |
"go.podman.io/image/v5/version" |
| 16 |
) |
| 17 |
|
| 18 |
const ( |
| 19 |
sigstoreSignatureType = "cosign container image signature" |
| 20 |
sigstoreHarcodedHashAlgorithm = crypto.SHA256 |
| 21 |
) |
| 22 |
|
| 23 |
// UntrustedSigstorePayload is a parsed content of a sigstore signature payload (not the full signature) |
| 24 |
type UntrustedSigstorePayload struct { |
| 25 |
untrustedDockerManifestDigest digest.Digest |
| 26 |
untrustedDockerReference string // FIXME: more precise type? |
| 27 |
untrustedCreatorID *string |
| 28 |
// This is intentionally an int64; the native JSON float64 type would allow to represent _some_ sub-second precision, |
| 29 |
// but not nearly enough (with current timestamp values, a single unit in the last place is on the order of hundreds of nanoseconds). |
| 30 |
// So, this is explicitly an int64, and we reject fractional values. If we did need more precise timestamps eventually, |
| 31 |
// we would add another field, UntrustedTimestampNS int64. |
| 32 |
untrustedTimestamp *int64 |
| 33 |
} |
| 34 |
|
| 35 |
// NewUntrustedSigstorePayload returns an UntrustedSigstorePayload object with |
| 36 |
// the specified primary contents and appropriate metadata. |
| 37 |
func NewUntrustedSigstorePayload(dockerManifestDigest digest.Digest, dockerReference string) UntrustedSigstorePayload { |
| 38 |
// Use intermediate variables for these values so that we can take their addresses. |
| 39 |
// Golang guarantees that they will have a new address on every execution. |
| 40 |
creatorID := "containers/image " + version.Version |
| 41 |
timestamp := time.Now().Unix() |
| 42 |
return UntrustedSigstorePayload{ |
| 43 |
untrustedDockerManifestDigest: dockerManifestDigest, |
| 44 |
untrustedDockerReference: dockerReference, |
| 45 |
untrustedCreatorID: &creatorID, |
| 46 |
untrustedTimestamp: ×tamp, |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
// A compile-time check that UntrustedSigstorePayload and *UntrustedSigstorePayload implements json.Marshaler |
| 51 |
var _ json.Marshaler = UntrustedSigstorePayload{} |
| 52 |
var _ json.Marshaler = (*UntrustedSigstorePayload)(nil) |
| 53 |
|
| 54 |
// MarshalJSON implements the json.Marshaler interface. |
| 55 |
func (s UntrustedSigstorePayload) MarshalJSON() ([]byte, error) { |
| 56 |
if s.untrustedDockerManifestDigest == "" || s.untrustedDockerReference == "" { |
| 57 |
return nil, errors.New("Unexpected empty signature content") |
| 58 |
} |
| 59 |
critical := map[string]any{ |
| 60 |
"type": sigstoreSignatureType, |
| 61 |
"image": map[string]string{"docker-manifest-digest": s.untrustedDockerManifestDigest.String()}, |
| 62 |
"identity": map[string]string{"docker-reference": s.untrustedDockerReference}, |
| 63 |
} |
| 64 |
optional := map[string]any{} |
| 65 |
if s.untrustedCreatorID != nil { |
| 66 |
optional["creator"] = *s.untrustedCreatorID |
| 67 |
} |
| 68 |
if s.untrustedTimestamp != nil { |
| 69 |
optional["timestamp"] = *s.untrustedTimestamp |
| 70 |
} |
| 71 |
signature := map[string]any{ |
| 72 |
"critical": critical, |
| 73 |
"optional": optional, |
| 74 |
} |
| 75 |
return json.Marshal(signature) |
| 76 |
} |
| 77 |
|
| 78 |
// Compile-time check that UntrustedSigstorePayload implements json.Unmarshaler |
| 79 |
var _ json.Unmarshaler = (*UntrustedSigstorePayload)(nil) |
| 80 |
|
| 81 |
// UnmarshalJSON implements the json.Unmarshaler interface |
| 82 |
func (s *UntrustedSigstorePayload) UnmarshalJSON(data []byte) error { |
| 83 |
return JSONFormatToInvalidSignatureError(s.strictUnmarshalJSON(data)) |
| 84 |
} |
| 85 |
|
| 86 |
// strictUnmarshalJSON is UnmarshalJSON, except that it may return the internal JSONFormatError error type. |
| 87 |
// Splitting it into a separate function allows us to do the JSONFormatError → InvalidSignatureError in a single place, the caller. |
| 88 |
func (s *UntrustedSigstorePayload) strictUnmarshalJSON(data []byte) error { |
| 89 |
var critical, optional json.RawMessage |
| 90 |
if err := ParanoidUnmarshalJSONObjectExactFields(data, map[string]any{ |
| 91 |
"critical": &critical, |
| 92 |
"optional": &optional, |
| 93 |
}); err != nil { |
| 94 |
return err |
| 95 |
} |
| 96 |
|
| 97 |
var creatorID string |
| 98 |
var timestamp float64 |
| 99 |
var gotCreatorID, gotTimestamp = false, false |
| 100 |
// /usr/bin/cosign generates "optional": null if there are no user-specified annotations. |
| 101 |
if !bytes.Equal(optional, []byte("null")) { |
| 102 |
if err := ParanoidUnmarshalJSONObject(optional, func(key string) any { |
| 103 |
switch key { |
| 104 |
case "creator": |
| 105 |
gotCreatorID = true |
| 106 |
return &creatorID |
| 107 |
case "timestamp": |
| 108 |
gotTimestamp = true |
| 109 |
return ×tamp |
| 110 |
default: |
| 111 |
var ignore any |
| 112 |
return &ignore |
| 113 |
} |
| 114 |
}); err != nil { |
| 115 |
return err |
| 116 |
} |
| 117 |
} |
| 118 |
if gotCreatorID { |
| 119 |
s.untrustedCreatorID = &creatorID |
| 120 |
} |
| 121 |
if gotTimestamp { |
| 122 |
intTimestamp := int64(timestamp) |
| 123 |
if float64(intTimestamp) != timestamp { |
| 124 |
return NewInvalidSignatureError("Field optional.timestamp is not an integer") |
| 125 |
} |
| 126 |
s.untrustedTimestamp = &intTimestamp |
| 127 |
} |
| 128 |
|
| 129 |
var t string |
| 130 |
var image, identity json.RawMessage |
| 131 |
if err := ParanoidUnmarshalJSONObjectExactFields(critical, map[string]any{ |
| 132 |
"type": &t, |
| 133 |
"image": &image, |
| 134 |
"identity": &identity, |
| 135 |
}); err != nil { |
| 136 |
return err |
| 137 |
} |
| 138 |
if t != sigstoreSignatureType { |
| 139 |
return NewInvalidSignatureError(fmt.Sprintf("Unrecognized signature type %s", t)) |
| 140 |
} |
| 141 |
|
| 142 |
var digestString string |
| 143 |
if err := ParanoidUnmarshalJSONObjectExactFields(image, map[string]any{ |
| 144 |
"docker-manifest-digest": &digestString, |
| 145 |
}); err != nil { |
| 146 |
return err |
| 147 |
} |
| 148 |
digestValue, err := digest.Parse(digestString) |
| 149 |
if err != nil { |
| 150 |
return NewInvalidSignatureError(fmt.Sprintf(`invalid docker-manifest-digest value %q: %v`, digestString, err)) |
| 151 |
} |
| 152 |
s.untrustedDockerManifestDigest = digestValue |
| 153 |
|
| 154 |
return ParanoidUnmarshalJSONObjectExactFields(identity, map[string]any{ |
| 155 |
"docker-reference": &s.untrustedDockerReference, |
| 156 |
}) |
| 157 |
} |
| 158 |
|
| 159 |
// SigstorePayloadAcceptanceRules specifies how to decide whether an untrusted payload is acceptable. |
| 160 |
// We centralize the actual parsing and data extraction in VerifySigstorePayload; this supplies |
| 161 |
// the policy. We use an object instead of supplying func parameters to verifyAndExtractSignature |
| 162 |
// because the functions have the same or similar types, so there is a risk of exchanging the functions; |
| 163 |
// named members of this struct are more explicit. |
| 164 |
type SigstorePayloadAcceptanceRules struct { |
| 165 |
ValidateSignedDockerReference func(string) error |
| 166 |
ValidateSignedDockerManifestDigest func(digest.Digest) error |
| 167 |
} |
| 168 |
|
| 169 |
// verifySigstorePayloadBlobSignature verifies unverifiedSignature of unverifiedPayload was correctly created |
| 170 |
// by any of the public keys in publicKeys. |
| 171 |
// |
| 172 |
// This is an internal implementation detail of VerifySigstorePayload and should have no other callers. |
| 173 |
// It is INSUFFICIENT alone to consider the signature acceptable. |
| 174 |
func verifySigstorePayloadBlobSignature(publicKeys []crypto.PublicKey, unverifiedPayload, unverifiedSignature []byte) error { |
| 175 |
if len(publicKeys) == 0 { |
| 176 |
return errors.New("Need at least one public key to verify the sigstore payload, but got 0") |
| 177 |
} |
| 178 |
|
| 179 |
verifiers := make([]sigstoreSignature.Verifier, 0, len(publicKeys)) |
| 180 |
for _, key := range publicKeys { |
| 181 |
// Failing to load a verifier indicates that something is really, really |
| 182 |
// invalid about the public key; prefer to fail even if the signature might be |
| 183 |
// valid with other keys, so that users fix their fallback keys before they need them. |
| 184 |
// For that reason, we even initialize all verifiers before trying to validate the signature |
| 185 |
// with any key. |
| 186 |
verifier, err := sigstoreSignature.LoadVerifier(key, sigstoreHarcodedHashAlgorithm) |
| 187 |
if err != nil { |
| 188 |
return err |
| 189 |
} |
| 190 |
verifiers = append(verifiers, verifier) |
| 191 |
} |
| 192 |
|
| 193 |
var failures []string |
| 194 |
for _, verifier := range verifiers { |
| 195 |
// github.com/sigstore/cosign/pkg/cosign.verifyOCISignature uses signatureoptions.WithContext(), |
| 196 |
// which seems to be not used by anything. So we don’t bother. |
| 197 |
err := verifier.VerifySignature(bytes.NewReader(unverifiedSignature), bytes.NewReader(unverifiedPayload)) |
| 198 |
if err == nil { |
| 199 |
return nil |
| 200 |
} |
| 201 |
|
| 202 |
failures = append(failures, err.Error()) |
| 203 |
} |
| 204 |
|
| 205 |
if len(failures) == 0 { |
| 206 |
// Coverage: We have checked there is at least one public key, any success causes an early return, |
| 207 |
// and any failure adds an entry to failures => there must be at least one error. |
| 208 |
return fmt.Errorf("Internal error: signature verification failed but no errors have been recorded") |
| 209 |
} |
| 210 |
return NewInvalidSignatureError("cryptographic signature verification failed: " + strings.Join(failures, ", ")) |
| 211 |
} |
| 212 |
|
| 213 |
// VerifySigstorePayload verifies unverifiedBase64Signature of unverifiedPayload was correctly created by any of the public keys in publicKeys, and that its principal components |
| 214 |
// match expected values, both as specified by rules, and returns it. |
| 215 |
// We return an *UntrustedSigstorePayload, although nothing actually uses it, |
| 216 |
// just to double-check against stupid typos. |
| 217 |
func VerifySigstorePayload(publicKeys []crypto.PublicKey, unverifiedPayload []byte, unverifiedBase64Signature string, rules SigstorePayloadAcceptanceRules) (*UntrustedSigstorePayload, error) { |
| 218 |
unverifiedSignature, err := base64.StdEncoding.DecodeString(unverifiedBase64Signature) |
| 219 |
if err != nil { |
| 220 |
return nil, NewInvalidSignatureError(fmt.Sprintf("base64 decoding: %v", err)) |
| 221 |
} |
| 222 |
|
| 223 |
if err := verifySigstorePayloadBlobSignature(publicKeys, unverifiedPayload, unverifiedSignature); err != nil { |
| 224 |
return nil, err |
| 225 |
} |
| 226 |
|
| 227 |
var unmatchedPayload UntrustedSigstorePayload |
| 228 |
if err := json.Unmarshal(unverifiedPayload, &unmatchedPayload); err != nil { |
| 229 |
return nil, NewInvalidSignatureError(err.Error()) |
| 230 |
} |
| 231 |
if err := rules.ValidateSignedDockerManifestDigest(unmatchedPayload.untrustedDockerManifestDigest); err != nil { |
| 232 |
return nil, err |
| 233 |
} |
| 234 |
if err := rules.ValidateSignedDockerReference(unmatchedPayload.untrustedDockerReference); err != nil { |
| 235 |
return nil, err |
| 236 |
} |
| 237 |
// SigstorePayloadAcceptanceRules have accepted this value. |
| 238 |
return &unmatchedPayload, nil |
| 239 |
} |