Debian Codegraph @

test/cliplugin/localkms/implementation.go

raw
1 // Copyright 2024 The Sigstore Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package main implements fake signer to be used in tests
16 package main
17
18 import (
19 "bytes"
20 "context"
21 "crypto"
22 "crypto/rand"
23 "crypto/rsa"
24 "crypto/x509"
25 "encoding/pem"
26 "errors"
27 "fmt"
28 "io"
29 "os"
30 "slices"
31
32 "github.com/sigstore/sigstore/pkg/cryptoutils"
33 "github.com/sigstore/sigstore/pkg/signature"
34 )
35
36 const (
37 defaultAlgorithm = "rsa-2048"
38 )
39
40 var (
41 supportedAlgorithms = []string{defaultAlgorithm}
42 )
43
44 // LocalSignerVerifier creates and verifies digital signatures with a key saved at KeyResourceID,
45 // and implements signerverifier.SignerVerifier.
46 type LocalSignerVerifier struct {
47 keyResourceID string
48 hashFunc crypto.Hash
49 }
50
51 // DefaultAlgorithm returns the default algorithm for the signer.
52 func (i LocalSignerVerifier) DefaultAlgorithm() string {
53 return defaultAlgorithm
54 }
55
56 // SupportedAlgorithms returns the supported algorithms for the signer.
57 func (i LocalSignerVerifier) SupportedAlgorithms() []string {
58 return supportedAlgorithms
59 }
60
61 // CreateKey returns a new public key, and saves the private key to the path at KeyResourceID.
62 // Don't do this in your own real implementation!
63 func (i LocalSignerVerifier) CreateKey(ctx context.Context, algorithm string) (crypto.PublicKey, error) {
64 if err := ctx.Err(); err != nil {
65 return nil, err
66 }
67
68 if !slices.Contains(i.SupportedAlgorithms(), algorithm) {
69 return nil, fmt.Errorf("algorithm %s not supported", algorithm)
70 }
71
72 path := i.keyResourceID
73
74 if _, err := os.Stat(path); err == nil { // file exists
75 privateKey, err := loadRSAPrivateKey(path)
76 if err != nil {
77 return nil, err
78 }
79 return &privateKey.PublicKey, nil
80 } else if !errors.Is(err, os.ErrNotExist) { // any error other than ErrNotExist
81 return nil, err
82 }
83 // proceed with creating the key
84
85 privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
86 if err != nil {
87 return nil, fmt.Errorf("error generating private key: %w", err)
88 }
89
90 // write to the path
91 privateKeyPEM := &pem.Block{
92 Type: "RSA PRIVATE KEY",
93 Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
94 }
95
96 privateKeyPEMBuffer := new(bytes.Buffer)
97 if err := pem.Encode(privateKeyPEMBuffer, privateKeyPEM); err != nil {
98 return nil, fmt.Errorf("error encoding private key: %w", err)
99 }
100
101 if err := pem.Encode(privateKeyPEMBuffer, privateKeyPEM); err != nil {
102 return nil, fmt.Errorf("error encoding private key: %w", err)
103 }
104
105 if err := os.WriteFile(path, privateKeyPEMBuffer.Bytes(), 0400); err != nil {
106 return nil, fmt.Errorf("error creating private key file: %w", err)
107 }
108
109 publicKey := &privateKey.PublicKey
110 return publicKey, nil
111 }
112
113 // PublicKey returns the public key.
114 func (i LocalSignerVerifier) PublicKey(opts ...signature.PublicKeyOption) (crypto.PublicKey, error) {
115 ctx := context.Background()
116 for _, opt := range opts {
117 opt.ApplyContext(&ctx)
118 }
119 if err := ctx.Err(); err != nil {
120 return nil, err
121 }
122
123 privateKey, err := loadRSAPrivateKey(i.keyResourceID)
124 if err != nil {
125 return nil, err
126 }
127 return &privateKey.PublicKey, nil
128 }
129
130 // SignMessage signs the message with the KeyResourceID.
131 func (i LocalSignerVerifier) SignMessage(message io.Reader, opts ...signature.SignOption) ([]byte, error) {
132 ctx := context.Background()
133 for _, opt := range opts {
134 opt.ApplyContext(&ctx)
135 }
136 if err := ctx.Err(); err != nil {
137 return nil, err
138 }
139
140 privateKey, err := loadRSAPrivateKey(i.keyResourceID)
141 if err != nil {
142 return nil, err
143 }
144
145 var digest []byte
146 var signerOpts crypto.SignerOpts = i.hashFunc
147 for _, opt := range opts {
148 opt.ApplyDigest(&digest)
149 opt.ApplyCryptoSignerOpts(&signerOpts)
150 }
151
152 if len(digest) == 0 {
153 digest, err = computeDigest(&message, signerOpts.HashFunc())
154 if err != nil {
155 return nil, err
156 }
157 }
158
159 signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, signerOpts.HashFunc(), digest)
160 if err != nil {
161 return nil, fmt.Errorf("error signing data: %w", err)
162 }
163 return signature, nil
164 }
165
166 // VerifySignature verifies the signature.
167 func (i LocalSignerVerifier) VerifySignature(signature io.Reader, message io.Reader, opts ...signature.VerifyOption) error {
168 ctx := context.Background()
169 for _, opt := range opts {
170 opt.ApplyContext(&ctx)
171 }
172 if err := ctx.Err(); err != nil {
173 return err
174 }
175
176 privateKey, err := loadRSAPrivateKey(i.keyResourceID)
177 if err != nil {
178 return err
179 }
180 publicKey := privateKey.PublicKey
181
182 var digest []byte
183 var signerOpts crypto.SignerOpts = i.hashFunc
184 for _, opt := range opts {
185 opt.ApplyDigest(&digest)
186 opt.ApplyCryptoSignerOpts(&signerOpts)
187 }
188
189 if len(digest) == 0 {
190 digest, err = computeDigest(&message, signerOpts.HashFunc())
191 if err != nil {
192 return err
193 }
194 }
195
196 sig, err := io.ReadAll(signature)
197 if err != nil {
198 return fmt.Errorf("error reading signature: %w", err)
199 }
200
201 if err := rsa.VerifyPKCS1v15(&publicKey, signerOpts.HashFunc(), digest, sig); err != nil {
202 return fmt.Errorf("error verifying signature: %w", err)
203 }
204 return nil
205 }
206
207 // loadRSAPrivateKey loads the private key from the path.
208 func loadRSAPrivateKey(path string) (*rsa.PrivateKey, error) {
209 privateKeyBytes, err := os.ReadFile(path)
210 if err != nil {
211 return nil, err
212 }
213
214 priv, err := cryptoutils.UnmarshalPEMToPrivateKey(privateKeyBytes, nil)
215 if err != nil {
216 return nil, err
217 }
218
219 rsaKey, ok := priv.(*rsa.PrivateKey)
220 if !ok {
221 return nil, errors.New("only RSA keys are supported")
222 }
223 return rsaKey, nil
224 }
225
226 // computeDigest computes the message digest with the hash function.
227 func computeDigest(message *io.Reader, hashFunc crypto.Hash) ([]byte, error) {
228 hasher := hashFunc.New()
229 if _, err := io.Copy(hasher, *message); err != nil {
230 return nil, err
231 }
232 return hasher.Sum(nil), nil
233 }
234
235 // CryptoSigner need not be fully implemented by plugins.
236 func (i LocalSignerVerifier) CryptoSigner(ctx context.Context, errFunc func(error)) (crypto.Signer, crypto.SignerOpts, error) {
237 panic("CryptoSigner() not implemented")
238 }