Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add attest-blob command #2286

Merged
merged 7 commits into from
Oct 12, 2022
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
180 changes: 180 additions & 0 deletions cmd/cosign/cli/attest/attest_blob.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
// Copyright 2022 The Sigstore Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package attest

import (
"bytes"
"context"
"crypto"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"os"
"path"
"path/filepath"
"strings"
"time"

"github.com/pkg/errors"
"github.com/sigstore/cosign/cmd/cosign/cli/options"
"github.com/sigstore/cosign/cmd/cosign/cli/rekor"
"github.com/sigstore/cosign/cmd/cosign/cli/sign"
"github.com/sigstore/cosign/pkg/cosign"
"github.com/sigstore/cosign/pkg/cosign/attestation"
cbundle "github.com/sigstore/cosign/pkg/cosign/bundle"
"github.com/sigstore/cosign/pkg/types"
"github.com/sigstore/sigstore/pkg/signature"
"github.com/sigstore/sigstore/pkg/signature/dsse"
signatureoptions "github.com/sigstore/sigstore/pkg/signature/options"
)

// nolint
func AttestBlobCmd(ctx context.Context, ko options.KeyOpts, artifactPath string, artifactHash string, certPath string, certChainPath string, noUpload bool, predicatePath string, force bool, predicateType string, replace bool, timeout time.Duration, outputSignature string) error {
// A key file or token is required unless we're in experimental mode!
if options.EnableExperimental() {
if options.NOf(ko.KeyRef, ko.Sk) > 1 {
return &options.KeyParseError{}
}
} else {
if !options.OneOf(ko.KeyRef, ko.Sk) {
return &options.KeyParseError{}
}
}

var artifact []byte
var hexDigest string
var rekorBytes []byte
var err error

if artifactHash == "" {
if artifactPath == "-" {
artifact, err = io.ReadAll(os.Stdin)
} else {
fmt.Fprintln(os.Stderr, "Using payload from:", artifactPath)
artifact, err = os.ReadFile(filepath.Clean(artifactPath))
}
if err != nil {
return err
}
}

sv, err := sign.SignerFromKeyOpts(ctx, certPath, certChainPath, ko)
if err != nil {
return errors.Wrap(err, "getting signer")
}
defer sv.Close()

if timeout != 0 {
var cancelFn context.CancelFunc
ctx, cancelFn = context.WithTimeout(ctx, timeout)
defer cancelFn()
}

if artifactHash == "" {
digest, _, err := signature.ComputeDigestForSigning(bytes.NewReader(artifact), crypto.SHA256, []crypto.Hash{crypto.SHA256, crypto.SHA384})
if err != nil {
return err
}
hexDigest = strings.ToLower(hex.EncodeToString(digest))
} else {
hexDigest = artifactHash
}
wrapped := dsse.WrapSigner(sv, types.IntotoPayloadType)

fmt.Fprintln(os.Stderr, "Using payload from:", predicatePath)
predicate, err := os.Open(predicatePath)
if err != nil {
return err
}
defer predicate.Close()

base := path.Base(artifactPath)

sh, err := attestation.GenerateStatement(attestation.GenerateOpts{
Predicate: predicate,
Type: predicateType,
Digest: hexDigest,
Repo: base,
})
if err != nil {
return err
}

payload, err := json.Marshal(sh)
if err != nil {
return err
}

fmt.Println("Payload:")
fmt.Println(string(payload))

sig, err := wrapped.SignMessage(bytes.NewReader(payload), signatureoptions.WithContext(ctx))
if err != nil {
return errors.Wrap(err, "signing")
}

// Check whether we should be uploading to the transparency log
signedPayload := cosign.LocalSignedPayload{}
if options.EnableExperimental() {
rekorBytes, err := sv.Bytes(ctx)
if err != nil {
return err
}
rekorClient, err := rekor.NewClient(ko.RekorURL)
if err != nil {
return err
}
entry, err := cosign.TLogUploadInTotoAttestation(ctx, rekorClient, sig, rekorBytes)
if err != nil {
return err
}
fmt.Fprintln(os.Stderr, "tlog entry created with index:", *entry.LogIndex)
signedPayload.Bundle = cbundle.EntryToBundle(entry)
}

// if bundle is specified, just do that and ignore the rest
if ko.BundlePath != "" {
signedPayload.Base64Signature = base64.StdEncoding.EncodeToString(sig)
signedPayload.Cert = base64.StdEncoding.EncodeToString(rekorBytes)

contents, err := json.Marshal(signedPayload)
if err != nil {
return err
}
if err := os.WriteFile(ko.BundlePath, contents, 0600); err != nil {
return fmt.Errorf("create bundle file: %w", err)
}
fmt.Printf("Bundle wrote in the file %s\n", ko.BundlePath)
}

// TODO: Write the certificate to file if specified via flag
sig = []byte(base64.StdEncoding.EncodeToString(sig))
if outputSignature != "" {
if err := os.WriteFile(outputSignature, sig, 0600); err != nil {
return fmt.Errorf("create signature file: %w", err)
}
fmt.Printf("Signature written in %s\n", outputSignature)
} else {
fmt.Println(string(sig))
}

if rekorBytes != nil {
fmt.Println(string(rekorBytes))
}

return nil
}
82 changes: 82 additions & 0 deletions cmd/cosign/cli/attest_blob.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// Copyright 2022 The Sigstore Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cli

import (
"github.com/pkg/errors"
"github.com/sigstore/cosign/cmd/cosign/cli/attest"
"github.com/sigstore/cosign/cmd/cosign/cli/generate"
"github.com/sigstore/cosign/cmd/cosign/cli/options"
"github.com/spf13/cobra"
)

func AttestBlob() *cobra.Command {
o := &options.AttestBlobOptions{}

cmd := &cobra.Command{
Use: "attest-blob",
Short: "Attest the supplied blob.",
Example: ` cosign attest-blob --key <key path>|<kms uri> [--predicate <path>] [--a key=value] [--no-upload=true|false] [--f] [--r] <BLOB uri>

# attach an attestation to a blob Google sign-in (experimental)
COSIGN_EXPERIMENTAL=1 cosign attest-blob --timeout 90s --predicate <FILE> --type <TYPE> <BLOB>

# attach an attestation to a blob with a local key pair file
cosign attest-blob --predicate <FILE> --type <TYPE> --key cosign.key <BLOB>

# attach an attestation to a blob with a key pair stored in Azure Key Vault
cosign attest-blob --predicate <FILE> --type <TYPE> --key azurekms://[VAULT_NAME][VAULT_URI]/[KEY] <BLOB>

# attach an attestation to a blob with a key pair stored in AWS KMS
cosign attest-blob --predicate <FILE> --type <TYPE> --key awskms://[ENDPOINT]/[ID/ALIAS/ARN] <BLOB>

# attach an attestation to a blob with a key pair stored in Google Cloud KMS
cosign attest-blob --predicate <FILE> --type <TYPE> --key gcpkms://projects/[PROJECT]/locations/global/keyRings/[KEYRING]/cryptoKeys/[KEY]/versions/[VERSION] <BLOB>

# attach an attestation to a blob with a key pair stored in Hashicorp Vault
cosign attest-blob --predicate <FILE> --type <TYPE> --key hashivault://[KEY] <BLOB>`,

Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
oidcClientSecret, err := o.OIDC.ClientSecret()
if err != nil {
return err
}
ko := options.KeyOpts{
KeyRef: o.Key,
PassFunc: generate.GetPass,
Sk: o.SecurityKey.Use,
Slot: o.SecurityKey.Slot,
FulcioURL: o.Fulcio.URL,
IDToken: o.Fulcio.IdentityToken,
InsecureSkipFulcioVerify: o.Fulcio.InsecureSkipFulcioVerify,
RekorURL: o.Rekor.URL,
OIDCIssuer: o.OIDC.Issuer,
OIDCClientID: o.OIDC.ClientID,
OIDCClientSecret: oidcClientSecret,
OIDCRedirectURL: o.OIDC.RedirectURL,
}
for _, artifact := range args {
if err := attest.AttestBlobCmd(cmd.Context(), ko, artifact, o.Hash, o.Cert, o.CertChain, o.NoUpload,
o.Predicate.Path, o.Force, o.Predicate.Type, o.Replace, ro.Timeout, o.OutputSignature); err != nil {
return errors.Wrapf(err, "attesting %s", artifact)
}
}
return nil
},
}
o.AddFlags(cmd)
return cmd
}
1 change: 1 addition & 0 deletions cmd/cosign/cli/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ func New() *cobra.Command {
// Add sub-commands.
cmd.AddCommand(Attach())
cmd.AddCommand(Attest())
cmd.AddCommand(AttestBlob())
cmd.AddCommand(Clean())
cmd.AddCommand(Tree())
cmd.AddCommand(Completion())
Expand Down
83 changes: 83 additions & 0 deletions cmd/cosign/cli/options/attest_blob.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// Copyright 2022 The Sigstore Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package options

import (
"time"

"github.com/spf13/cobra"
)

// AttestOptions is the top level wrapper for the attest command.
type AttestBlobOptions struct {
Key string
Cert string
CertChain string
NoUpload bool
Force bool
Recursive bool
Replace bool
Timeout time.Duration
Hash string
OutputSignature string

Rekor RekorOptions
Fulcio FulcioOptions
OIDC OIDCOptions
SecurityKey SecurityKeyOptions
Predicate PredicateLocalOptions
}

var _ Interface = (*AttestOptions)(nil)

// AddFlags implements Interface
func (o *AttestBlobOptions) AddFlags(cmd *cobra.Command) {
o.SecurityKey.AddFlags(cmd)
o.Predicate.AddFlags(cmd)
o.Fulcio.AddFlags(cmd)
o.OIDC.AddFlags(cmd)
o.Rekor.AddFlags(cmd)

cmd.Flags().StringVar(&o.Key, "key", "",
"path to the private key file, KMS URI or Kubernetes Secret")

cmd.Flags().StringVar(&o.Cert, "cert", "",
"path to the x509 certificate to include in the Signature")

cmd.Flags().StringVar(&o.OutputSignature, "output-signature", "",
"write the signature to FILE")
_ = cmd.Flags().SetAnnotation("output-signature", cobra.BashCompFilenameExt, []string{})

cmd.Flags().StringVar(&o.CertChain, "cert-chain", "",
"path to a list of CA X.509 certificates in PEM format which will be needed "+
"when building the certificate chain for the signing certificate. "+
"Must start with the parent intermediate CA certificate of the "+
"signing certificate and end with the root certificate. Included in the OCI Signature")

cmd.Flags().BoolVar(&o.NoUpload, "no-upload", false,
"do not upload the generated attestation")

cmd.Flags().BoolVarP(&o.Force, "force", "f", false,
"skip warnings and confirmations")

cmd.Flags().BoolVarP(&o.Replace, "replace", "", false,
"")

cmd.Flags().DurationVar(&o.Timeout, "timeout", time.Second*30,
"HTTP Timeout defaults to 30 seconds")

cmd.Flags().StringVar(&o.Hash, "hash", "",
"hash of blob in hexadecimal (base16). Used if you want to sign an artifact stored elsewhere and have the hash")
}
1 change: 1 addition & 0 deletions doc/cosign.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading