-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
verify.go
354 lines (316 loc) · 9.67 KB
/
verify.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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/*
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 spire
import (
"context"
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"sort"
"strings"
"github.com/pkg/errors"
"github.com/spiffe/go-spiffe/v2/workloadapi"
"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1"
"github.com/tektoncd/pipeline/pkg/result"
"go.uber.org/zap"
)
// VerifyTaskRunResults ensures that the TaskRun results are valid and have not been tampered with
func (sc *spireControllerAPIClient) VerifyTaskRunResults(ctx context.Context, prs []result.RunResult, tr *v1beta1.TaskRun) error {
err := sc.setupClient(ctx)
if err != nil {
return err
}
resultMap := map[string]result.RunResult{}
for _, r := range prs {
if r.ResultType == result.TaskRunResultType {
resultMap[r.Key] = r
}
}
cert, err := getSVID(resultMap)
if err != nil {
return err
}
trust, err := getTrustBundle(ctx, sc.workloadAPI)
if err != nil {
return err
}
if err := verifyManifest(resultMap); err != nil {
return err
}
if err := verifyCertURI(cert, tr, sc.config.TrustDomain); err != nil {
return err
}
if err := verifyCertificateTrust(cert, trust); err != nil {
return err
}
for key := range resultMap {
if strings.HasSuffix(key, KeySignatureSuffix) {
continue
}
if key == KeySVID {
continue
}
if err := verifyResult(cert.PublicKey, key, resultMap); err != nil {
return err
}
}
return nil
}
// VerifyStatusInternalAnnotation run multuple verification steps to ensure that the spire status annotations are valid
func (sc *spireControllerAPIClient) VerifyStatusInternalAnnotation(ctx context.Context, tr *v1beta1.TaskRun, logger *zap.SugaredLogger) error {
err := sc.setupClient(ctx)
if err != nil {
return err
}
if !sc.CheckSpireVerifiedFlag(tr) {
return errors.New("annotation tekton.dev/not-verified = yes failed spire verification")
}
annotations := tr.Status.Annotations
// get trust bundle from spire server
trust, err := getTrustBundle(ctx, sc.workloadAPI)
if err != nil {
return err
}
// verify controller SVID
svid, ok := annotations[controllerSvidAnnotation]
if !ok {
return errors.New("No SVID found")
}
block, _ := pem.Decode([]byte(svid))
if block == nil {
return fmt.Errorf("invalid SVID: %w", err)
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return fmt.Errorf("invalid SVID: %w", err)
}
// verify certificate root of trust
if err := verifyCertificateTrust(cert, trust); err != nil {
return err
}
logger.Infof("Successfully verified certificate %s against SPIRE", svid)
if err := verifyAnnotation(cert.PublicKey, annotations); err != nil {
return err
}
logger.Info("Successfully verified signature")
// CheckStatusInternalAnnotation check current status hash vs annotation status hash by controller
if err := CheckStatusInternalAnnotation(tr); err != nil {
return err
}
logger.Info("Successfully verified status annotation hash matches the current taskrun status")
return nil
}
// CheckSpireVerifiedFlag checks if the verified status annotation is set which would result in spire verification failed
func (sc *spireControllerAPIClient) CheckSpireVerifiedFlag(tr *v1beta1.TaskRun) bool {
if _, ok := tr.Status.Annotations[VerifiedAnnotation]; !ok {
return true
}
return false
}
func hashTaskrunStatusInternal(tr *v1beta1.TaskRun) (string, error) {
s, err := json.Marshal(tr.Status.TaskRunStatusFields)
if err != nil {
return "", err
}
return fmt.Sprintf("%x", sha256.Sum256(s)), nil
}
// CheckStatusInternalAnnotation ensures that the internal status annotation hash and current status hash match
func CheckStatusInternalAnnotation(tr *v1beta1.TaskRun) error {
// get stored hash of status
annotations := tr.Status.Annotations
hash, ok := annotations[TaskRunStatusHashAnnotation]
if !ok {
return fmt.Errorf("no annotation status hash found for %s", TaskRunStatusHashAnnotation)
}
// get current hash of status
current, err := hashTaskrunStatusInternal(tr)
if err != nil {
return err
}
if hash != current {
return fmt.Errorf("current status hash and stored annotation hash does not match! Annotation Hash: %s, Current Status Hash: %s", hash, current)
}
return nil
}
func getSVID(resultMap map[string]result.RunResult) (*x509.Certificate, error) {
svid, ok := resultMap[KeySVID]
if !ok {
return nil, errors.New("no SVID found")
}
svidValue, err := getResultValue(svid)
if err != nil {
return nil, err
}
block, _ := pem.Decode([]byte(svidValue))
if block == nil {
return nil, fmt.Errorf("invalid SVID: %w", err)
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, fmt.Errorf("invalid SVID: %w", err)
}
return cert, nil
}
func getTrustBundle(ctx context.Context, client *workloadapi.Client) (*x509.CertPool, error) {
x509set, err := client.FetchX509Bundles(ctx)
if err != nil {
return nil, err
}
x509Bundle := x509set.Bundles()
if err != nil {
return nil, err
}
if len(x509Bundle) > 0 {
trustPool := x509.NewCertPool()
for _, bundle := range x509Bundle {
for _, c := range bundle.X509Authorities() {
trustPool.AddCert(c)
}
return trustPool, nil
}
}
return nil, errors.Wrap(err, "trust domain bundle empty")
}
func getFullPath(tr *v1beta1.TaskRun) string {
// URI:spiffe://example.org/ns/default/taskrun/cache-image-pipelinerun-r4r22-fetch-from-git
return fmt.Sprintf("/ns/%s/taskrun/%s", tr.Namespace, tr.Name)
}
func verifyCertURI(cert *x509.Certificate, tr *v1beta1.TaskRun, trustDomain string) error {
path := getFullPath(tr)
switch {
case len(cert.URIs) == 0:
return fmt.Errorf("cert uri missing for taskrun: %s", tr.Name)
case len(cert.URIs) > 1:
return fmt.Errorf("cert contains more than one URI for taskrun: %s", tr.Name)
case len(cert.URIs) == 1:
if cert.URIs[0].Host != trustDomain {
return fmt.Errorf("cert uri: %s does not match trust domain: %s", cert.URIs[0].Host, trustDomain)
}
if cert.URIs[0].Path != path {
return fmt.Errorf("cert uri: %s does not match taskrun: %s", cert.URIs[0].Path, path)
}
}
return nil
}
func verifyCertificateTrust(cert *x509.Certificate, rootCertPool *x509.CertPool) error {
verifyOptions := x509.VerifyOptions{
Roots: rootCertPool,
}
chains, err := cert.Verify(verifyOptions)
if len(chains) == 0 || err != nil {
return errors.New("cert cannot be verified by provided roots")
}
return nil
}
func verifyManifest(results map[string]result.RunResult) error {
manifest, ok := results[KeyResultManifest]
if !ok {
return errors.New("no manifest found in results")
}
manifestValue, err := getResultValue(manifest)
if err != nil {
return err
}
s := strings.Split(manifestValue, ",")
for _, key := range s {
_, found := results[key]
if key != "" && !found {
return fmt.Errorf("no result found for %s but is part of the manifest %s", key, manifestValue)
}
}
return nil
}
func verifyAnnotation(pub interface{}, annotations map[string]string) error {
signature, ok := annotations[taskRunStatusHashSigAnnotation]
if !ok {
return fmt.Errorf("no signature found for %s", taskRunStatusHashSigAnnotation)
}
hash, ok := annotations[TaskRunStatusHashAnnotation]
if !ok {
return fmt.Errorf("no annotation status hash found for %s", TaskRunStatusHashAnnotation)
}
return verifySignature(pub, signature, hash)
}
func verifyResult(pub crypto.PublicKey, key string, results map[string]result.RunResult) error {
signature, ok := results[key+KeySignatureSuffix]
if !ok {
return fmt.Errorf("no signature found for %s", key)
}
sigValue, err := getResultValue(signature)
if err != nil {
return err
}
resultValue, err := getResultValue(results[key])
if err != nil {
return err
}
return verifySignature(pub, sigValue, resultValue)
}
func verifySignature(pub crypto.PublicKey, signature string, value string) error {
b, err := base64.StdEncoding.DecodeString(signature)
if err != nil {
return fmt.Errorf("invalid signature: %w", err)
}
h := sha256.Sum256([]byte(value))
// Check val against sig
switch t := pub.(type) {
case *ecdsa.PublicKey:
if !ecdsa.VerifyASN1(t, h[:], b) {
return errors.New("invalid signature")
}
return nil
case *rsa.PublicKey:
return rsa.VerifyPKCS1v15(t, crypto.SHA256, h[:], b)
case ed25519.PublicKey:
if !ed25519.Verify(t, []byte(value), b) {
return errors.New("invalid signature")
}
return nil
default:
return fmt.Errorf("unsupported key type: %s", t)
}
}
func getResultValue(result result.RunResult) (string, error) {
aos := v1beta1.ArrayOrString{}
err := aos.UnmarshalJSON([]byte(result.Value))
valList := []string{}
if err != nil {
return "", fmt.Errorf("unmarshal error for key: %s", result.Key)
}
switch aos.Type {
case v1beta1.ParamTypeString:
return aos.StringVal, nil
case v1beta1.ParamTypeArray:
valList = append(valList, aos.ArrayVal...)
return strings.Join(valList, ","), nil
case v1beta1.ParamTypeObject:
keys := make([]string, 0, len(aos.ObjectVal))
for k := range aos.ObjectVal {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
valList = append(valList, k)
valList = append(valList, aos.ObjectVal[k])
}
return strings.Join(valList, ","), nil
}
return "", fmt.Errorf("invalid result type for key: %s", result.Key)
}