| 1 | package cosign |
| 2 | |
| 3 | import ( |
| 4 | "crypto" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | |
| 9 | "github.com/opencontainers/go-digest" |
| 10 | oci "github.com/opencontainers/image-spec/specs-go/v1" |
| 11 | ) |
| 12 | |
| 13 | var algorithms = map[crypto.Hash]digest.Algorithm{ |
| 14 | crypto.SHA256: digest.SHA256, |
| 15 | crypto.SHA384: digest.SHA384, |
| 16 | crypto.SHA512: digest.SHA512, |
| 17 | } |
| 18 | |
| 19 | // digest a payload and return it both formatted and raw |
| 20 | func digestPayload(hash crypto.Hash, blob []byte) ([]byte, digest.Digest) { |
| 21 | alg := algorithms[hash] |
| 22 | if !alg.Available() { |
| 23 | return nil, "" |
| 24 | } |
| 25 | digester := hash.New() |
| 26 | digester.Write(blob) |
| 27 | rawDigest := digester.Sum(nil) |
| 28 | layerDigest := digest.NewDigestFromBytes(alg, rawDigest) |
| 29 | return rawDigest, layerDigest |
| 30 | } |
| 31 | |
| 32 | // legacy container media types |
| 33 | const ( |
| 34 | dockerImageType = "application/vnd.docker.distribution.manifest.v2+json" |
| 35 | dockerListType = "application/vnd.docker.distribution.manifest.list.v2+json" |
| 36 | ) |
| 37 | |
| 38 | var allowedManifestTypes = map[string]bool{ |
| 39 | oci.MediaTypeImageManifest: true, |
| 40 | oci.MediaTypeImageIndex: true, |
| 41 | dockerImageType: true, |
| 42 | dockerListType: true, |
| 43 | } |
| 44 | |
| 45 | type objectWithMediaType struct { |
| 46 | MediaType string `json:"mediaType"` |
| 47 | } |
| 48 | |
| 49 | // return the digest and mediaType of a manifest |
| 50 | func digestManifest(hash crypto.Hash, blob []byte) (digest.Digest, string, error) { |
| 51 | alg := algorithms[hash] |
| 52 | if !alg.Available() { |
| 53 | return "", "", fmt.Errorf("unsupported digest %s", hash) |
| 54 | } |
| 55 | var mt objectWithMediaType |
| 56 | if err := json.Unmarshal(blob, &mt); err != nil { |
| 57 | return "", "", fmt.Errorf("unable to determine mediaType: %w", err) |
| 58 | } |
| 59 | if mt.MediaType == "" { |
| 60 | return "", "", errors.New("unable to determine mediaType") |
| 61 | } |
| 62 | if !allowedManifestTypes[mt.MediaType] { |
| 63 | return "", "", fmt.Errorf("mediaType %q cannot be signed", mt.MediaType) |
| 64 | } |
| 65 | return alg.FromBytes(blob), mt.MediaType, nil |
| 66 | } |