1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
|
//
// 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 cliplugin implements the plugin functionality.
package cliplugin
import (
"bytes"
"context"
"crypto"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"os"
"github.com/sigstore/sigstore/pkg/cryptoutils"
"github.com/sigstore/sigstore/pkg/signature"
"github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/common"
"github.com/sigstore/sigstore/pkg/signature/kms/cliplugin/encoding"
"github.com/sigstore/sigstore/pkg/signature/options"
)
var (
// ErrorExecutingPlugin indicates a problem executing the plugin program.
ErrorExecutingPlugin = errors.New("error executing plugin program")
// ErrorResponseParse indicates a problem parsing the plugin response.
ErrorResponseParse = errors.New("parsing plugin response")
// ErrorPluginReturnError indicates that the plugin returned a praseable error.
ErrorPluginReturnError = errors.New("plugin returned error")
)
// PluginClient implements signerverifier.SignerVerifier with calls to our plugin program.
type PluginClient struct {
executable string
initOptions common.InitOptions
makeCmdFunc makeCmdFunc
}
// newPluginClient creates a new PluginClient.
func newPluginClient(executable string, initOptions *common.InitOptions, makeCmd makeCmdFunc) *PluginClient {
pluginClient := &PluginClient{
executable: executable,
initOptions: *initOptions,
makeCmdFunc: makeCmd,
}
return pluginClient
}
// invokePlugin invokes the plugin program and parses its response.
func (c PluginClient) invokePlugin(ctx context.Context, stdin io.Reader, methodArgs *common.MethodArgs) (*common.PluginResp, error) {
pluginArgs := &common.PluginArgs{
InitOptions: &c.initOptions,
MethodArgs: methodArgs,
}
argsEnc, err := json.Marshal(pluginArgs)
if err != nil {
return nil, err
}
cmd := c.makeCmdFunc(ctx, stdin, os.Stderr, c.executable, common.ProtocolVersion, string(argsEnc))
// We won't look at the program's non-zero exit code, but we will respect any other
// error, and cases when exec.ExitError.ExitCode() is 0 or -1:
// * (0) the program finished successfully or
// * (-1) there was some other problem not due to the program itself.
// The only debugging is to either parse the the returned error in stdout,
// or for the user to examine the sterr logs.
// See https://pkg.go.dev/os#ProcessState.ExitCode.
stdout, err := cmd.Output()
var exitError cmdExitError
if err != nil && (!errors.As(err, &exitError) || exitError.ExitCode() < 1) {
return nil, fmt.Errorf("%w: %w", ErrorExecutingPlugin, err)
}
var resp common.PluginResp
if unmarshallErr := json.Unmarshal(stdout, &resp); unmarshallErr != nil {
return nil, fmt.Errorf("%w: %w", ErrorResponseParse, unmarshallErr)
}
if resp.ErrorMessage != "" {
return nil, fmt.Errorf("%w: %s", ErrorPluginReturnError, resp.ErrorMessage)
}
return &resp, nil
}
// DefaultAlgorithm calls and returns the plugin's implementation of DefaultAlgorithm().
func (c PluginClient) DefaultAlgorithm() string {
args := &common.MethodArgs{
MethodName: common.DefaultAlgorithmMethodName,
DefaultAlgorithm: &common.DefaultAlgorithmArgs{},
}
resp, err := c.invokePlugin(context.Background(), nil, args)
if err != nil {
log.Fatal(err)
}
return resp.DefaultAlgorithm.DefaultAlgorithm
}
// SupportedAlgorithms calls and returns the plugin's implementation of SupportedAlgorithms().
func (c PluginClient) SupportedAlgorithms() []string {
args := &common.MethodArgs{
MethodName: common.SupportedAlgorithmsMethodName,
SupportedAlgorithms: &common.SupportedAlgorithmsArgs{},
}
resp, err := c.invokePlugin(context.Background(), nil, args)
if err != nil {
log.Fatal(err)
}
return resp.SupportedAlgorithms.SupportedAlgorithms
}
// CreateKey calls and returns the plugin's implementation of CreateKey().
func (c PluginClient) CreateKey(ctx context.Context, algorithm string) (crypto.PublicKey, error) {
args := &common.MethodArgs{
MethodName: common.CreateKeyMethodName,
CreateKey: &common.CreateKeyArgs{
Algorithm: algorithm,
},
}
if deadline, ok := ctx.Deadline(); ok {
args.CreateKey.CtxDeadline = &deadline
}
resp, err := c.invokePlugin(ctx, nil, args)
if err != nil {
return nil, err
}
return cryptoutils.UnmarshalPEMToPublicKey(resp.CreateKey.PublicKeyPEM)
}
// PublicKey calls and returns the plugin's implementation of PublicKey().
// If the opts contain a context, then it will be used with the Cmd.
func (c PluginClient) PublicKey(opts ...signature.PublicKeyOption) (crypto.PublicKey, error) {
args := &common.MethodArgs{
MethodName: common.PublicKeyMethodName,
PublicKey: &common.PublicKeyArgs{
PublicKeyOptions: encoding.PackPublicKeyOptions(opts),
},
}
ctx := context.Background()
for _, opt := range opts {
opt.ApplyContext(&ctx)
}
resp, err := c.invokePlugin(ctx, nil, args)
if err != nil {
return nil, err
}
return cryptoutils.UnmarshalPEMToPublicKey(resp.PublicKey.PublicKeyPEM)
}
// SignMessage calls and returns the plugin's implementation of SignMessage().
// If the opts contain a context, then it will be used with the Cmd.
func (c PluginClient) SignMessage(message io.Reader, opts ...signature.SignOption) ([]byte, error) {
args := &common.MethodArgs{
MethodName: common.SignMessageMethodName,
SignMessage: &common.SignMessageArgs{
SignOptions: encoding.PackSignOptions(opts),
},
}
ctx := context.Background()
for _, opt := range opts {
opt.ApplyContext(&ctx)
}
resp, err := c.invokePlugin(ctx, message, args)
if err != nil {
return nil, err
}
signature := resp.SignMessage.Signature
return signature, nil
}
// VerifySignature calls and returns the plugin's implementation of VerifySignature().
// If the opts contain a context, then it will be used with the Cmd.
func (c PluginClient) VerifySignature(signature, message io.Reader, opts ...signature.VerifyOption) error {
// signatures won't be larger than 1MB, so it's fine to read the entire content into memory.
signatureBytes, err := io.ReadAll(signature)
if err != nil {
return err
}
args := &common.MethodArgs{
MethodName: common.VerifySignatureMethodName,
VerifySignature: &common.VerifySignatureArgs{
Signature: signatureBytes,
VerifyOptions: encoding.PackVerifyOptions(opts),
},
}
ctx := context.Background()
for _, opt := range opts {
opt.ApplyContext(&ctx)
}
_, err = c.invokePlugin(ctx, message, args)
return err
}
// CryptoSigner is a wrapper around PluginClient.
type CryptoSigner struct {
client *PluginClient
ctx context.Context
errFunc func(error)
}
// CryptoSigner returns a wrapper around PluginClient.
func (c PluginClient) CryptoSigner(ctx context.Context, errFunc func(error)) (crypto.Signer, crypto.SignerOpts, error) {
if err := ctx.Err(); err != nil {
return nil, nil, err
}
return &CryptoSigner{
client: &c,
ctx: ctx,
errFunc: errFunc,
}, c.initOptions.HashFunc, nil
}
// Sign is a wrapper around PluginClient.SignMessage(). The first argument for a rand source is not used.
func (c CryptoSigner) Sign(_ io.Reader, digest []byte, cryptoSignerOpts crypto.SignerOpts) (sig []byte, err error) {
emptyMessage := bytes.NewReader([]byte(""))
opts := []signature.SignOption{
options.WithCryptoSignerOpts(cryptoSignerOpts.HashFunc()),
options.WithDigest(digest),
// the client's initializing ctx should not be used in calls to its methods.
}
sig, err = c.client.SignMessage(emptyMessage, opts...)
if err != nil && c.errFunc != nil {
c.errFunc(err)
}
return sig, err
}
// Public is a wrapper around PluginClient.PublicKey().
func (c CryptoSigner) Public() crypto.PublicKey {
publicKey, err := c.client.PublicKey()
if err != nil && c.errFunc != nil {
c.errFunc(err)
// we don't panic here.
}
return publicKey
}
|