forked from sigstore/cosign
-
Notifications
You must be signed in to change notification settings - Fork 0
/
verify_test.go
250 lines (231 loc) · 7.93 KB
/
verify_test.go
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
247
248
249
250
// 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 ctl
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"os"
"reflect"
"strings"
"testing"
ct "github.com/google/certificate-transparency-go"
"github.com/google/certificate-transparency-go/testdata"
"github.com/google/certificate-transparency-go/tls"
"github.com/sigstore/sigstore/pkg/cryptoutils"
)
func TestGetPublicKey(t *testing.T) {
wd, err := os.Getwd()
if err != nil {
t.Fatalf("Failed to get cwd: %v", err)
}
tests := []struct {
file string
wantErrSub string
wantType string
}{
{file: "garbage-there-are-limits", wantErrSub: "failed to parse"},
// Testflume 2021 from here, https://letsencrypt.org/docs/ct-logs/
{file: "letsencrypt-testflume-2021", wantType: "*ecdsa.PublicKey"},
// This needs to be parsed with the pkcs1, pkix won't do.
{file: "rsa", wantType: "*rsa.PublicKey"},
// This works with pkix, from:
// https://www.gstatic.com/ct/log_list/v2/log_list_pubkey.pem
{file: "google", wantType: "*rsa.PublicKey"},
}
for _, tc := range tests {
filepath := fmt.Sprintf("%s/testdata/%s", wd, tc.file)
bytes, err := os.ReadFile(filepath)
if err != nil {
t.Fatalf("Failed to read testfile %s : %v", tc.file, err)
}
got, err := getPublicKey(bytes)
switch {
case err == nil && tc.wantErrSub != "":
t.Errorf("Wanted Error for %s but got none", tc.file)
case err != nil && tc.wantErrSub == "":
t.Errorf("Did not want error for %s but got: %v", tc.file, err)
case err != nil && tc.wantErrSub != "":
if !strings.Contains(err.Error(), tc.wantErrSub) {
t.Errorf("Unexpected error for %s: %s wanted to contain: %s", tc.file, err.Error(), tc.wantErrSub)
}
}
switch {
case got == nil && tc.wantType != "":
t.Errorf("Wanted public key for %s but got none", tc.file)
case got != nil && tc.wantType == "":
t.Errorf("Did not want error for %s but got: %v", tc.file, err)
case got != nil && tc.wantType != "":
if reflect.TypeOf(got).String() != tc.wantType {
t.Errorf("Unexpected type for %s: %+T wanted: %s", tc.file, got, tc.wantType)
}
}
}
}
func TestContainsSCT(t *testing.T) {
// test certificate without embedded SCT
contains, err := ContainsSCT([]byte(testdata.TestCertPEM))
if err != nil {
t.Fatalf("unexpected error in ContainsSCT: %v", err)
}
if contains {
t.Fatalf("certificate unexpectedly contained SCT")
}
// test certificate with embedded SCT
contains, err = ContainsSCT([]byte(testdata.TestEmbeddedCertPEM))
if err != nil {
t.Fatalf("unexpected error in ContainsSCT: %v", err)
}
if !contains {
t.Fatalf("certificate unexpectedly did not contain SCT")
}
}
// From https://github.com/google/certificate-transparency-go/blob/e76f3f637053b90c8168d29b01ca162cd235ace5/ctutil/ctutil_test.go
func TestVerifySCT(t *testing.T) {
tests := []struct {
desc string
certPEM string
chainPEM string
sct []byte
embedded bool
wantErr bool
errMsg string
}{
{
desc: "cert",
certPEM: testdata.TestCertPEM,
chainPEM: testdata.CACertPEM,
sct: testdata.TestCertProof,
},
{
desc: "invalid SCT",
certPEM: testdata.TestPreCertPEM,
chainPEM: testdata.CACertPEM,
sct: testdata.TestCertProof,
wantErr: true,
},
{
desc: "cert with embedded SCT",
certPEM: testdata.TestEmbeddedCertPEM,
chainPEM: testdata.CACertPEM,
sct: testdata.TestPreCertProof,
embedded: true,
},
{
desc: "cert with invalid embedded SCT",
certPEM: testdata.TestInvalidEmbeddedCertPEM,
chainPEM: testdata.CACertPEM,
sct: testdata.TestInvalidProof,
embedded: true,
wantErr: true,
errMsg: "failed to verify ECDSA signature",
},
}
writePubKey(t, testdata.LogPublicKeyPEM)
for _, test := range tests {
t.Run(test.desc, func(t *testing.T) {
// convert SCT to response struct if detached
var sctBytes []byte
if !test.embedded {
var sct ct.SignedCertificateTimestamp
if _, err := tls.Unmarshal(test.sct, &sct); err != nil {
t.Fatalf("error tls-unmarshalling sct: %s", err)
}
chainResp, err := toAddChainResponse(&sct)
if err != nil {
t.Fatalf("error generating chain response: %v", err)
}
sctBytes, err = json.Marshal(chainResp)
if err != nil {
t.Fatalf("error marshalling chain: %v", err)
}
}
err := VerifySCT(context.Background(), []byte(test.certPEM), []byte(test.chainPEM), sctBytes)
if gotErr := err != nil; gotErr != test.wantErr && !strings.Contains(err.Error(), test.errMsg) {
t.Errorf("VerifySCT(_,_,_, %t) = %v, want error? %t", test.embedded, err, test.wantErr)
}
})
}
}
func TestVerifySCTError(t *testing.T) {
// verify fails with mismatched verifcation key
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("unexpected error generating ECDSA key: %v", err)
}
pemKey, err := cryptoutils.MarshalPublicKeyToPEM(key.Public())
if err != nil {
t.Fatalf("unexpected error marshalling ECDSA key: %v", err)
}
writePubKey(t, string(pemKey))
err = VerifySCT(context.Background(), []byte(testdata.TestEmbeddedCertPEM), []byte(testdata.CACertPEM), []byte{})
if err == nil || !strings.Contains(err.Error(), "ctfe public key not found") {
t.Fatalf("expected error verifying SCT with mismatched key: %v", err)
}
// verify fails without either a detached SCT or embedded SCT
err = VerifySCT(context.Background(), []byte(testdata.TestCertPEM), []byte(testdata.CACertPEM), []byte{})
if err == nil || !strings.Contains(err.Error(), "no SCT found") {
t.Fatalf("expected error verifying SCT without SCT: %v", err)
}
}
func TestVerifyEmbeddedSCT(t *testing.T) {
chain, err := cryptoutils.UnmarshalCertificatesFromPEM([]byte(testdata.TestEmbeddedCertPEM + testdata.CACertPEM))
if err != nil {
t.Fatalf("error unmarshalling certificate chain: %v", err)
}
// verify fails without a certificate chain
err = VerifyEmbeddedSCT(context.Background(), chain[:1])
if err == nil || err.Error() != "certificate chain must contain at least a certificate and its issuer" {
t.Fatalf("expected error verifying SCT without chain: %v", err)
}
writePubKey(t, testdata.LogPublicKeyPEM)
err = VerifyEmbeddedSCT(context.Background(), chain)
if err != nil {
t.Fatalf("unexpected error verifying embedded SCT: %v", err)
}
}
// toAddChainResponse converts an SCT to a response struct, the expected structure for detached SCTs
func toAddChainResponse(sct *ct.SignedCertificateTimestamp) (*ct.AddChainResponse, error) {
sig, err := tls.Marshal(sct.Signature)
if err != nil {
return nil, fmt.Errorf("failed to marshal signature: %w", err)
}
addChainResp := &ct.AddChainResponse{
SCTVersion: sct.SCTVersion,
Timestamp: sct.Timestamp,
Extensions: base64.StdEncoding.EncodeToString(sct.Extensions),
ID: sct.LogID.KeyID[:],
Signature: sig,
}
return addChainResp, nil
}
// writePubKey writes the SCT verification key to disk, since there is not a TUF
// test setup
func writePubKey(t *testing.T, keyPEM string) {
t.Helper()
tmpPrivFile, err := os.CreateTemp(t.TempDir(), "cosign_verify_sct_*.key")
if err != nil {
t.Fatalf("failed to create temp key file: %v", err)
}
t.Cleanup(func() { tmpPrivFile.Close() })
if _, err := tmpPrivFile.Write([]byte(keyPEM)); err != nil {
t.Fatalf("failed to write key file: %v", err)
}
os.Setenv("SIGSTORE_CT_LOG_PUBLIC_KEY_FILE", tmpPrivFile.Name())
t.Cleanup(func() { os.Unsetenv("SIGSTORE_CT_LOG_PUBLIC_KEY_FILE") })
}