/
entry.go
421 lines (345 loc) · 10.8 KB
/
entry.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//
// Copyright 2021 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 rekord
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/asaskevich/govalidator"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"golang.org/x/sync/errgroup"
"github.com/sigstore/rekor/pkg/generated/models"
"github.com/sigstore/rekor/pkg/log"
"github.com/sigstore/rekor/pkg/pki"
"github.com/sigstore/rekor/pkg/types"
"github.com/sigstore/rekor/pkg/types/rekord"
"github.com/sigstore/rekor/pkg/util"
)
const (
APIVERSION = "0.0.1"
)
func init() {
if err := rekord.VersionMap.SetEntryFactory(APIVERSION, NewEntry); err != nil {
log.Logger.Panic(err)
}
}
type V001Entry struct {
RekordObj models.RekordV001Schema
}
func (v V001Entry) APIVersion() string {
return APIVERSION
}
func NewEntry() types.EntryImpl {
return &V001Entry{}
}
func (v V001Entry) IndexKeys() ([]string, error) {
var result []string
af, err := pki.NewArtifactFactory(pki.Format(*v.RekordObj.Signature.Format))
if err != nil {
return nil, err
}
keyObj, err := af.NewPublicKey(bytes.NewReader(*v.RekordObj.Signature.PublicKey.Content))
if err != nil {
return nil, err
}
key, err := keyObj.CanonicalValue()
if err != nil {
log.Logger.Error(err)
} else {
keyHash := sha256.Sum256(key)
result = append(result, strings.ToLower(hex.EncodeToString(keyHash[:])))
}
result = append(result, keyObj.Subjects()...)
if v.RekordObj.Data.Hash != nil {
hashKey := strings.ToLower(fmt.Sprintf("%s:%s", *v.RekordObj.Data.Hash.Algorithm, *v.RekordObj.Data.Hash.Value))
result = append(result, hashKey)
}
return result, nil
}
func (v *V001Entry) Unmarshal(pe models.ProposedEntry) error {
rekord, ok := pe.(*models.Rekord)
if !ok {
return errors.New("cannot unmarshal non Rekord v0.0.1 type")
}
if err := types.DecodeEntry(rekord.Spec, &v.RekordObj); err != nil {
return err
}
// field validation
if err := v.RekordObj.Validate(strfmt.Default); err != nil {
return err
}
// cross field validation
return v.validate()
}
func (v *V001Entry) fetchExternalEntities(ctx context.Context) (pki.PublicKey, pki.Signature, error) {
g, ctx := errgroup.WithContext(ctx)
af, err := pki.NewArtifactFactory(pki.Format(*v.RekordObj.Signature.Format))
if err != nil {
return nil, nil, err
}
hashR, hashW := io.Pipe()
sigR, sigW := io.Pipe()
defer hashR.Close()
defer sigR.Close()
closePipesOnError := types.PipeCloser(hashR, hashW, sigR, sigW)
oldSHA := ""
if v.RekordObj.Data.Hash != nil && v.RekordObj.Data.Hash.Value != nil {
oldSHA = swag.StringValue(v.RekordObj.Data.Hash.Value)
}
g.Go(func() error {
defer hashW.Close()
defer sigW.Close()
dataReadCloser := bytes.NewReader(v.RekordObj.Data.Content)
/* #nosec G110 */
if _, err := io.Copy(io.MultiWriter(hashW, sigW), dataReadCloser); err != nil {
return closePipesOnError(err)
}
return nil
})
hashResult := make(chan string)
g.Go(func() error {
defer close(hashResult)
hasher := sha256.New()
if _, err := io.Copy(hasher, hashR); err != nil {
return closePipesOnError(err)
}
computedSHA := hex.EncodeToString(hasher.Sum(nil))
if oldSHA != "" && computedSHA != oldSHA {
return closePipesOnError(types.ValidationError(fmt.Errorf("SHA mismatch: %s != %s", computedSHA, oldSHA)))
}
select {
case <-ctx.Done():
return ctx.Err()
case hashResult <- computedSHA:
return nil
}
})
sigResult := make(chan pki.Signature)
g.Go(func() error {
defer close(sigResult)
sigReadCloser := bytes.NewReader(*v.RekordObj.Signature.Content)
signature, err := af.NewSignature(sigReadCloser)
if err != nil {
return closePipesOnError(types.ValidationError(err))
}
select {
case <-ctx.Done():
return ctx.Err()
case sigResult <- signature:
return nil
}
})
keyResult := make(chan pki.PublicKey)
g.Go(func() error {
defer close(keyResult)
keyReadCloser := bytes.NewReader(*v.RekordObj.Signature.PublicKey.Content)
key, err := af.NewPublicKey(keyReadCloser)
if err != nil {
return closePipesOnError(types.ValidationError(err))
}
select {
case <-ctx.Done():
return ctx.Err()
case keyResult <- key:
return nil
}
})
var (
keyObj pki.PublicKey
sigObj pki.Signature
)
g.Go(func() error {
keyObj, sigObj = <-keyResult, <-sigResult
if keyObj == nil || sigObj == nil {
return closePipesOnError(errors.New("failed to read signature or public key"))
}
var err error
if err = sigObj.Verify(sigR, keyObj); err != nil {
return closePipesOnError(types.ValidationError(err))
}
select {
case <-ctx.Done():
return ctx.Err()
default:
return nil
}
})
computedSHA := <-hashResult
if err := g.Wait(); err != nil {
return nil, nil, err
}
// if we get here, all goroutines succeeded without error
if oldSHA == "" {
v.RekordObj.Data.Hash = &models.RekordV001SchemaDataHash{}
v.RekordObj.Data.Hash.Algorithm = swag.String(models.RekordV001SchemaDataHashAlgorithmSha256)
v.RekordObj.Data.Hash.Value = swag.String(computedSHA)
}
return keyObj, sigObj, nil
}
func (v *V001Entry) Canonicalize(ctx context.Context) ([]byte, error) {
keyObj, sigObj, err := v.fetchExternalEntities(ctx)
if err != nil {
return nil, err
}
canonicalEntry := models.RekordV001Schema{}
// need to canonicalize signature & key content
canonicalEntry.Signature = &models.RekordV001SchemaSignature{}
// signature URL (if known) is not set deliberately
canonicalEntry.Signature.Format = v.RekordObj.Signature.Format
var sigContent []byte
sigContent, err = sigObj.CanonicalValue()
if err != nil {
return nil, err
}
canonicalEntry.Signature.Content = (*strfmt.Base64)(&sigContent)
var pubKeyContent []byte
canonicalEntry.Signature.PublicKey = &models.RekordV001SchemaSignaturePublicKey{}
pubKeyContent, err = keyObj.CanonicalValue()
if err != nil {
return nil, err
}
canonicalEntry.Signature.PublicKey.Content = (*strfmt.Base64)(&pubKeyContent)
canonicalEntry.Data = &models.RekordV001SchemaData{}
canonicalEntry.Data.Hash = v.RekordObj.Data.Hash
// data content is not set deliberately
// wrap in valid object with kind and apiVersion set
rekordObj := models.Rekord{}
rekordObj.APIVersion = swag.String(APIVERSION)
rekordObj.Spec = &canonicalEntry
v.RekordObj = canonicalEntry
bytes, err := json.Marshal(&rekordObj)
if err != nil {
return nil, err
}
return bytes, nil
}
// validate performs cross-field validation for fields in object
func (v V001Entry) validate() error {
sig := v.RekordObj.Signature
if v.RekordObj.Signature == nil {
return errors.New("missing signature")
}
if sig.Content == nil || len(*sig.Content) == 0 {
return errors.New("'content' must be specified for signature")
}
key := sig.PublicKey
if key == nil {
return errors.New("missing public key")
}
if key.Content == nil || len(*key.Content) == 0 {
return errors.New("'content' must be specified for publicKey")
}
data := v.RekordObj.Data
if data == nil {
return errors.New("missing data")
}
hash := data.Hash
if hash != nil {
if !govalidator.IsHash(swag.StringValue(hash.Value), swag.StringValue(hash.Algorithm)) {
return errors.New("invalid value for hash")
}
} else if len(data.Content) == 0 {
return errors.New("'content' must be specified for data")
}
return nil
}
func (v V001Entry) CreateFromArtifactProperties(ctx context.Context, props types.ArtifactProperties) (models.ProposedEntry, error) {
returnVal := models.Rekord{}
re := V001Entry{}
// we will need artifact, public-key, signature
re.RekordObj.Data = &models.RekordV001SchemaData{}
var err error
artifactBytes := props.ArtifactBytes
if artifactBytes == nil {
var artifactReader io.ReadCloser
if props.ArtifactPath == nil {
return nil, errors.New("path to artifact file must be specified")
}
if props.ArtifactPath.IsAbs() {
artifactReader, err = util.FileOrURLReadCloser(ctx, props.ArtifactPath.String(), nil)
if err != nil {
return nil, fmt.Errorf("error reading artifact file: %w", err)
}
} else {
artifactReader, err = os.Open(filepath.Clean(props.ArtifactPath.Path))
if err != nil {
return nil, fmt.Errorf("error opening artifact file: %w", err)
}
}
artifactBytes, err = ioutil.ReadAll(artifactReader)
if err != nil {
return nil, fmt.Errorf("error reading artifact file: %w", err)
}
}
re.RekordObj.Data.Content = strfmt.Base64(artifactBytes)
re.RekordObj.Signature = &models.RekordV001SchemaSignature{}
switch props.PKIFormat {
case "pgp":
re.RekordObj.Signature.Format = swag.String(models.RekordV001SchemaSignatureFormatPgp)
case "minisign":
re.RekordObj.Signature.Format = swag.String(models.RekordV001SchemaSignatureFormatMinisign)
case "x509":
re.RekordObj.Signature.Format = swag.String(models.RekordV001SchemaSignatureFormatX509)
case "ssh":
re.RekordObj.Signature.Format = swag.String(models.RekordV001SchemaSignatureFormatSSH)
}
sigBytes := props.SignatureBytes
if sigBytes == nil {
if props.SignaturePath == nil {
return nil, errors.New("a detached signature must be provided")
}
sigBytes, err = ioutil.ReadFile(filepath.Clean(props.SignaturePath.Path))
if err != nil {
return nil, fmt.Errorf("error reading signature file: %w", err)
}
re.RekordObj.Signature.Content = (*strfmt.Base64)(&sigBytes)
} else {
re.RekordObj.Signature.Content = (*strfmt.Base64)(&sigBytes)
}
re.RekordObj.Signature.PublicKey = &models.RekordV001SchemaSignaturePublicKey{}
publicKeyBytes := props.PublicKeyBytes
if len(publicKeyBytes) == 0 {
if len(props.PublicKeyPaths) != 1 {
return nil, errors.New("only one public key must be provided to verify detached signature")
}
keyBytes, err := ioutil.ReadFile(filepath.Clean(props.PublicKeyPaths[0].Path))
if err != nil {
return nil, fmt.Errorf("error reading public key file: %w", err)
}
publicKeyBytes = append(publicKeyBytes, keyBytes)
} else if len(publicKeyBytes) != 1 {
return nil, errors.New("only one public key byte must be provided")
}
re.RekordObj.Signature.PublicKey.Content = (*strfmt.Base64)(&publicKeyBytes[0])
if err := re.validate(); err != nil {
return nil, err
}
if _, _, err := re.fetchExternalEntities(ctx); err != nil {
return nil, fmt.Errorf("error retrieving external entities: %v", err)
}
returnVal.APIVersion = swag.String(re.APIVersion())
returnVal.Spec = re.RekordObj
return &returnVal, nil
}