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 bundle create helper command #3901

Merged
merged 3 commits into from
Nov 5, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
71 changes: 71 additions & 0 deletions cmd/cosign/cli/bundle.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
//
// Copyright 2024 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 (
"context"

"github.com/spf13/cobra"

"github.com/sigstore/cosign/v2/cmd/cosign/cli/bundle"
"github.com/sigstore/cosign/v2/cmd/cosign/cli/options"
)

func Bundle() *cobra.Command {
cmd := &cobra.Command{
Use: "bundle",
Short: "Interact with a Sigstore protobuf bundle",
Long: "Tools for interacting with a Sigstore protobuf bundle",
}

cmd.AddCommand(bundleCreate())

return cmd
}

func bundleCreate() *cobra.Command {
o := &options.BundleCreateOptions{}

cmd := &cobra.Command{
Use: "create",
Short: "Create a Sigstore protobuf bundle",
Long: "Create a Sigstore protobuf bundle by supplying signed material",
RunE: func(cmd *cobra.Command, _ []string) error {
bundleCreateCmd := &bundle.CreateCmd{
Artifact: o.Artifact,
AttestationPath: o.AttestationPath,
BundlePath: o.BundlePath,
CertificatePath: o.CertificatePath,
IgnoreTlog: o.IgnoreTlog,
KeyRef: o.KeyRef,
Out: o.Out,
RekorURL: o.RekorURL,
RFC3161TimestampPath: o.RFC3161TimestampPath,
SignaturePath: o.SignaturePath,
Sk: o.Sk,
Slot: o.Slot,
}

ctx, cancel := context.WithTimeout(cmd.Context(), ro.Timeout)
defer cancel()

return bundleCreateCmd.Exec(ctx)
},
}

o.AddFlags(cmd)
return cmd
}
214 changes: 214 additions & 0 deletions cmd/cosign/cli/bundle/bundle.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
//
// Copyright 2024 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 bundle

import (
"context"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"os"

"github.com/secure-systems-lab/go-securesystemslib/dsse"
"github.com/sigstore/rekor/pkg/generated/client"
"github.com/sigstore/sigstore/pkg/cryptoutils"
"github.com/sigstore/sigstore/pkg/signature"

"github.com/sigstore/cosign/v2/cmd/cosign/cli/options"
"github.com/sigstore/cosign/v2/cmd/cosign/cli/rekor"
"github.com/sigstore/cosign/v2/cmd/cosign/cli/verify"
"github.com/sigstore/cosign/v2/pkg/cosign"
"github.com/sigstore/cosign/v2/pkg/cosign/bundle"
"github.com/sigstore/cosign/v2/pkg/cosign/pivkey"
"github.com/sigstore/cosign/v2/pkg/cosign/pkcs11key"
sigs "github.com/sigstore/cosign/v2/pkg/signature"
)

type CreateCmd struct {
Artifact string
AttestationPath string
BundlePath string
CertificatePath string
IgnoreTlog bool
KeyRef string
Out string
RekorURL string
RFC3161TimestampPath string
SignaturePath string
Sk bool
Slot string
}

func (c *CreateCmd) Exec(ctx context.Context) (err error) {
if c.Artifact == "" {
return fmt.Errorf("must supply --artifact")
}

// We require some signature
if options.NOf(c.BundlePath, c.SignaturePath) == 0 {
return fmt.Errorf("must at least supply signature via --bundle or --signature")
}

var cert *x509.Certificate
var envelope dsse.Envelope
var rekorClient *client.Rekor
var sigBytes, signedTimestamp []byte
var sigVerifier signature.Verifier

if c.BundlePath != "" {
b, err := cosign.FetchLocalSignedPayloadFromPath(c.BundlePath)
if err != nil {
return err
}

if b.Cert != "" {
certPEM, err := base64.StdEncoding.DecodeString(b.Cert)
if err != nil {
return err
}
certs, err := cryptoutils.UnmarshalCertificatesFromPEM(certPEM)
if err != nil {
return err
}
if len(certs) == 0 {
return fmt.Errorf("no certs found in bundle")
}
cert = certs[0]
}

if b.Base64Signature != "" {
// Could be a DSSE envelope or plain signature
signature, err := base64.StdEncoding.DecodeString(b.Base64Signature)
if err != nil {
return err
}

// See if DSSE JSON unmashalling succeeds
err = json.Unmarshal(signature, &envelope)
if err != nil {
// Guess that it is a plain signature
sigBytes = signature
}
}
}

if c.SignaturePath != "" {
sigBytes, err = os.ReadFile(c.SignaturePath)
if err != nil {
return err
}
}

if c.RFC3161TimestampPath != "" {
timestampBytes, err := os.ReadFile(c.RFC3161TimestampPath)
if err != nil {
return err
}

var rfc3161Timestamp bundle.RFC3161Timestamp
err = json.Unmarshal(timestampBytes, &rfc3161Timestamp)
if err != nil {
return err
}

signedTimestamp = rfc3161Timestamp.SignedRFC3161Timestamp
}

if c.CertificatePath != "" {
certBytes, err := os.ReadFile(c.CertificatePath)
if err != nil {
return err
}

certDecoded, err := base64.StdEncoding.DecodeString(string(certBytes))
if err != nil {
return err
}

block, _ := pem.Decode(certDecoded)
if block == nil {
return fmt.Errorf("unable to decode provided certificate")
}

cert, err = x509.ParseCertificate(block.Bytes)
if err != nil {
return err
}
}

if c.AttestationPath != "" {
attestationBytes, err := os.ReadFile(c.AttestationPath)
if err != nil {
return err
}

err = json.Unmarshal(attestationBytes, &envelope)
if err != nil {
return err
}
}

if c.KeyRef != "" {
sigVerifier, err = sigs.PublicKeyFromKeyRef(ctx, c.KeyRef)
if err != nil {
return fmt.Errorf("loading public key: %w", err)
}
pkcs11Key, ok := sigVerifier.(*pkcs11key.Key)
if ok {
defer pkcs11Key.Close()
}
} else if c.Sk {
sk, err := pivkey.GetKeyWithSlot(c.Slot)
if err != nil {
return fmt.Errorf("opening piv token: %w", err)
}
defer sk.Close()
sigVerifier, err = sk.Verifier()
if err != nil {
return fmt.Errorf("loading public key from token: %w", err)
}
}

if c.RekorURL != "" {
rekorClient, err = rekor.NewClient(c.RekorURL)
if err != nil {
return err
}
}

bundle, err := verify.AssembleNewBundle(ctx, sigBytes, signedTimestamp, &envelope, c.Artifact, cert, c.IgnoreTlog, sigVerifier, nil, rekorClient)
if err != nil {
return err
}

bundleBytes, err := bundle.MarshalJSON()
if err != nil {
return err
}

if c.Out != "" {
err = os.WriteFile(c.Out, bundleBytes, 0600)
if err != nil {
return err
}
} else {
fmt.Println(string(bundleBytes))
}

return nil
}
99 changes: 99 additions & 0 deletions cmd/cosign/cli/bundle/bundle_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
//
// Copyright 2024 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 bundle
Copy link
Member

@loosebazooka loosebazooka Oct 25, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure where go tests should go that load data from "resources" and run tests against them. But I think we should have tests that use known signature data (including ones with certs) and generates a bundle? vs generating the data here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's an interesting idea!

Most of the existing cosign tests generate the material they work with on the fly. Some advantages of generating the material is you don't need to include known data, and you're testing with a variety of inputs. Of course, a disadvantage is that you could have a test that intermittently fails!

I think this could be something cosign considers more broadly, but might not make sense to address in this specific pull request.


import (
"context"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"os"
"path/filepath"
"testing"

sgBundle "github.com/sigstore/sigstore-go/pkg/bundle"
)

func TestCreateCmd(t *testing.T) {
ctx := context.Background()

artifact := "hello world"
digest := sha256.Sum256([]byte(artifact))

td := t.TempDir()
artifactPath := filepath.Join(td, "artifact")
err := os.WriteFile(artifactPath, []byte(artifact), 0600)
checkErr(t, err)

privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
checkErr(t, err)
sigBytes, err := privateKey.Sign(rand.Reader, digest[:], crypto.SHA256)
checkErr(t, err)

signature := base64.StdEncoding.EncodeToString(sigBytes)
sigPath := filepath.Join(td, "sig")
err = os.WriteFile(sigPath, []byte(signature), 0600)
checkErr(t, err)

publicKeyPath := filepath.Join(td, "key.pub")
pubKeyBytes, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
checkErr(t, err)
pemBlock := &pem.Block{
Type: "PUBLIC KEY",
Bytes: pubKeyBytes,
}
err = os.WriteFile(publicKeyPath, pem.EncodeToMemory(pemBlock), 0600)
checkErr(t, err)

outPath := filepath.Join(td, "bundle.sigstore.json")

bundleCreate := CreateCmd{
Artifact: artifactPath,
KeyRef: publicKeyPath,
IgnoreTlog: true,
Out: outPath,
SignaturePath: sigPath,
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could more cases be tested here? For example, for converting an old-style bundle, or for when there's a fulcio identity certificate instead of a key?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems fair; I have added another test that does both the old style bundle and when a Fulcio identity certificate is used.


err = bundleCreate.Exec(ctx)
checkErr(t, err)

b, err := sgBundle.LoadJSONFromPath(outPath)
checkErr(t, err)

if b.Bundle.VerificationMaterial == nil {
t.Fatal("bundle does not have verification material")
}

if b.Bundle.VerificationMaterial.GetPublicKey() == nil {
t.Fatal("bundle verification material does not have public key")
}

if b.Bundle.GetMessageSignature() == nil {
t.Fatal("bundle does not have message signature")
}
}

func checkErr(t *testing.T, err error) {
if err != nil {
t.Fatal(err)
}
}
1 change: 1 addition & 0 deletions cmd/cosign/cli/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ func New() *cobra.Command {
cmd.AddCommand(Attach())
cmd.AddCommand(Attest())
cmd.AddCommand(AttestBlob())
cmd.AddCommand(Bundle())
cmd.AddCommand(Clean())
cmd.AddCommand(Debug())
cmd.AddCommand(Tree())
Expand Down
Loading
Loading