Skip to content

Commit

Permalink
[TEP-0091] Add Sign CMD and Verification at reconciler
Browse files Browse the repository at this point in the history
This commit is part of TEP-0091, before this commit we only have signing
and verification functions but not used. This commit add signing in cmd
so users can run signing with key files or KMS key to sign Task or
Pipeline. Verification is added at reconciler after remote resolution
and local resolve is done.
  • Loading branch information
Yongxuanzhang committed Sep 29, 2022
1 parent 2465c31 commit a89e323
Show file tree
Hide file tree
Showing 29 changed files with 1,830 additions and 43 deletions.
180 changes: 180 additions & 0 deletions cmd/sign/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
/*
Copyright 2022 The Tekton 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 main

import (
"context"
"crypto"
"encoding/base64"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"syscall"

sigstore "github.com/sigstore/sigstore/pkg/signature"
"github.com/sigstore/sigstore/pkg/signature/kms"
"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1"
"github.com/tektoncd/pipeline/pkg/reconciler/trustedresources"
"golang.org/x/term"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"knative.dev/pkg/webhook/resourcesemantics"
"sigs.k8s.io/yaml"
)

var (
keyFile = flag.String("kf", "", "private key file path")
kmsKey = flag.String("kms", "", "kms key path")
resourceFile = flag.String("rf", "", "YAML file path for tekton resources")
kind = flag.String("kd", "Task", "The kind of the signed object. Supported values: [Task, Pipeline]")
targetDir = flag.String("td", "", "Dir to save the signed files")
targetFile = flag.String("tf", "signed.yaml", "Filename of the signed file")
// Read is for fuzzing
read = readPasswordFn
)

func main() {
ctx := context.Background()

flag.Parse()

var signer sigstore.Signer
var err error
if *keyFile != "" {
// Load signer from key files
signer, err = sigstore.LoadSignerFromPEMFile(*keyFile, crypto.SHA256, getPass)
if err != nil {
log.Fatalf("error getting signer: %v", err)
}
}
if *kmsKey != "" {
signer, err = kms.Get(ctx, *kmsKey, crypto.SHA256)
if err != nil {
log.Fatalf("error getting signer: %v", err)
}
}

f, err := os.OpenFile(filepath.Join(*targetDir, *targetFile), os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
log.Fatalf("error opening output file: %v", err)
}
defer f.Close()

tsBuf, err := ioutil.ReadFile(*resourceFile)
if err != nil {
log.Fatalf("error reading file: %v", err)
}
var crd resourcesemantics.GenericCRD
switch *kind {
case "Task":
crd = &v1beta1.Task{}
case "Pipeline":
crd = &v1beta1.Pipeline{}
}

if err := yaml.Unmarshal(tsBuf, &crd); err != nil {
log.Fatalf("error unmarshalling Task/Pipeline: %v", err)
}

// Sign the task and write to writer
if err := Sign(ctx, crd.(metav1.Object), signer, f); err != nil {
log.Fatalf("error signing Task/Pipeline: %v", err)
}

}

// Sign the crd and output signed bytes to writer
func Sign(ctx context.Context, o metav1.Object, signer sigstore.Signer, writer io.Writer) error {
// Get annotation
a := o.GetAnnotations()
if a == nil {
a = map[string]string{}
}
// Add signature
sig, err := trustedresources.SignInterface(signer, o)
if err != nil {
return err
}
a[trustedresources.SignatureAnnotation] = base64.StdEncoding.EncodeToString(sig)
o.SetAnnotations(a)
signedBuf, err := yaml.Marshal(o)
if err != nil {
return err
}
_, err = writer.Write(signedBuf)
return err
}

func getPass(confirm bool) ([]byte, error) {
read := read(confirm)
return read()
}

func readPasswordFn(confirm bool) func() ([]byte, error) {
pw, ok := os.LookupEnv("PRIVATE_PASSWORD")
switch {
case ok:
return func() ([]byte, error) {
return []byte(pw), nil
}
case isTerminal():
return func() ([]byte, error) {
return getPassFromTerm(confirm)
}
// Handle piped in passwords.
default:
return func() ([]byte, error) {
return io.ReadAll(os.Stdin)
}
}
}

func getPassFromTerm(confirm bool) ([]byte, error) {
fmt.Fprint(os.Stderr, "Enter password for private key: ")
// Unnecessary convert of syscall.Stdin on *nix, but Windows is a uintptr
// nolint:unconvert
pw1, err := term.ReadPassword(int(syscall.Stdin))
if err != nil {
return nil, err
}
fmt.Fprintln(os.Stderr)
if !confirm {
return pw1, nil
}
fmt.Fprint(os.Stderr, "Enter password for private key again: ")
// Unnecessary convert of syscall.Stdin on *nix, but Windows is a uintptr
// nolint:unconvert
confirmpw, err := term.ReadPassword(int(syscall.Stdin))
fmt.Fprintln(os.Stderr)
if err != nil {
return nil, err
}

if string(pw1) != string(confirmpw) {
return nil, errors.New("passwords do not match")
}
return pw1, nil
}

func isTerminal() bool {
stat, _ := os.Stdin.Stat()
return (stat.Mode() & os.ModeCharDevice) != 0
}
178 changes: 178 additions & 0 deletions cmd/sign/sign_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
/*
Copyright 2022 The Tekton 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 main

import (
"bytes"
"context"
"encoding/base64"
"os"
"testing"

"github.com/sigstore/sigstore/pkg/signature"
"github.com/tektoncd/pipeline/pkg/apis/pipeline"
"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1"
"github.com/tektoncd/pipeline/pkg/reconciler/trustedresources"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/yaml"
)

const (
password = "hello"
namespace = "test"
serviceAccount = "tekton-verify-task-webhook"
)

func init() {
os.Setenv("SYSTEM_NAMESPACE", namespace)
os.Setenv("WEBHOOK_SERVICEACCOUNT_NAME", serviceAccount)
}

var (
// tasks for testing
taskSpec = &v1beta1.TaskSpec{
Steps: []v1beta1.Step{{
Image: "ubuntu",
Name: "echo",
}},
}

trTypeMeta = metav1.TypeMeta{
Kind: pipeline.TaskRunControllerName,
APIVersion: "tekton.dev/v1beta1"}

trObjectMeta = metav1.ObjectMeta{
Name: "tr",
Namespace: namespace,
Annotations: map[string]string{},
}

pipelineSpec = &v1beta1.PipelineSpec{
Tasks: []v1beta1.PipelineTask{
{
Name: "pipelinetask",
},
},
}

sa = &corev1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
Namespace: namespace,
Name: serviceAccount,
},
}
)

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

sv, _, err := signature.NewDefaultECDSASignerVerifier()
if err != nil {
t.Fatalf("failed to get signerverifier %v", err)
}

tcs := []struct {
name string
resource metav1.Object
kind string
}{{
name: "Task Sign and pass verification",
resource: getTask(),
kind: "Task",
}, {
name: "Pipeline Sign and pass verification",
resource: getPipeline(),
kind: "Pipeline",
},
}

for _, tc := range tcs {
t.Run(tc.name, func(t *testing.T) {
var writer bytes.Buffer
if err := Sign(ctx, tc.resource, sv, &writer); err != nil {
t.Fatalf("Sign() get err %v", err)
}
signed := writer.Bytes()
target, signature := unmarshalCRD(t, signed, tc.kind)
if err := trustedresources.VerifyInterface(ctx, target, sv, signature); err != nil {
t.Fatalf("VerifyTaskOCIBundle get error: %v", err)
}
})
}
}

// unmarshalCRD will get the task/pipeline from buffer extract the signature.
func unmarshalCRD(t *testing.T, buf []byte, kind string) (metav1.Object, []byte) {
var resource metav1.Object
var signature []byte

switch kind {
case "Task":
resource = &v1beta1.Task{}
if err := yaml.Unmarshal(buf, &resource); err != nil {
t.Fatalf("error unmarshalling buffer: %v", err)
}
case "Pipeline":
resource = &v1beta1.Pipeline{}
if err := yaml.Unmarshal(buf, &resource); err != nil {
t.Fatalf("error unmarshalling buffer: %v", err)
}
}
signature, err := extractSignature(resource.GetAnnotations())
if err != nil {
t.Fatalf("Failed to extract signature: %v", err)
}
return resource, signature
}

func extractSignature(annotations map[string]string) ([]byte, error) {
signature, err := base64.StdEncoding.DecodeString(annotations[trustedresources.SignatureAnnotation])
if err != nil {
return signature, err
}
delete(annotations, trustedresources.SignatureAnnotation)
return signature, nil
}

func getTask() *v1beta1.Task {
return &v1beta1.Task{
TypeMeta: metav1.TypeMeta{
APIVersion: "tekton.dev/v1beta1",
Kind: "Task",
},
ObjectMeta: metav1.ObjectMeta{
Name: "test-task",
Namespace: namespace,
},
Spec: *taskSpec,
}
}

func getPipeline() *v1beta1.Pipeline {
return &v1beta1.Pipeline{
TypeMeta: metav1.TypeMeta{
APIVersion: "tekton.dev/v1beta1",
Kind: "Pipeline",
},
ObjectMeta: metav1.ObjectMeta{
Name: "test-Pipeline",
Namespace: namespace,
},
Spec: *pipelineSpec,
}
}
4 changes: 4 additions & 0 deletions config/config-feature-flags.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,7 @@ data:
# Setting this flag to "true" enables CloudEvents for Runs, as long as a
# CloudEvents sink is configured in the config-defaults config map
send-cloudevents-for-runs: "false"
# Setting this flag to "enforce" will enforce verification of tasks/pipeline, fail to verify
# will mark the taskrun/pipelinerun as failed. "warn" will only log the err message and "skip"
# will skip the whole verification
verification-policy: "skip"
Loading

0 comments on commit a89e323

Please sign in to comment.