-
Notifications
You must be signed in to change notification settings - Fork 26
/
trusted_root.go
461 lines (412 loc) · 14 KB
/
trusted_root.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
// Copyright 2023 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 root
import (
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rsa"
"crypto/x509"
"encoding/hex"
"fmt"
"log"
"os"
"sync"
"time"
protocommon "github.com/sigstore/protobuf-specs/gen/pb-go/common/v1"
prototrustroot "github.com/sigstore/protobuf-specs/gen/pb-go/trustroot/v1"
"github.com/sigstore/sigstore-go/pkg/tuf"
"google.golang.org/protobuf/encoding/protojson"
)
const TrustedRootMediaType01 = "application/vnd.dev.sigstore.trustedroot+json;version=0.1"
type TrustedRoot struct {
BaseTrustedMaterial
trustedRoot *prototrustroot.TrustedRoot
rekorLogs map[string]*TransparencyLog
fulcioCertAuthorities []CertificateAuthority
ctLogs map[string]*TransparencyLog
timestampingAuthorities []CertificateAuthority
}
type CertificateAuthority struct {
Root *x509.Certificate
Intermediates []*x509.Certificate
Leaf *x509.Certificate
ValidityPeriodStart time.Time
ValidityPeriodEnd time.Time
URI string
}
type TransparencyLog struct {
BaseURL string
ID []byte
ValidityPeriodStart time.Time
ValidityPeriodEnd time.Time
// This is the hash algorithm used by the Merkle tree
HashFunc crypto.Hash
PublicKey crypto.PublicKey
// The hash algorithm used during signature creation
SignatureHashFunc crypto.Hash
}
func (tr *TrustedRoot) TimestampingAuthorities() []CertificateAuthority {
return tr.timestampingAuthorities
}
func (tr *TrustedRoot) FulcioCertificateAuthorities() []CertificateAuthority {
return tr.fulcioCertAuthorities
}
func (tr *TrustedRoot) RekorLogs() map[string]*TransparencyLog {
return tr.rekorLogs
}
func (tr *TrustedRoot) CTLogs() map[string]*TransparencyLog {
return tr.ctLogs
}
func (tr *TrustedRoot) MarshalJSON() ([]byte, error) {
err := tr.constructProtoTrustRoot()
if err != nil {
return nil, fmt.Errorf("failed constructing protobuf TrustRoot representation: %w", err)
}
return protojson.Marshal(tr.trustedRoot)
}
func NewTrustedRootFromProtobuf(protobufTrustedRoot *prototrustroot.TrustedRoot) (trustedRoot *TrustedRoot, err error) {
if protobufTrustedRoot.GetMediaType() != TrustedRootMediaType01 {
return nil, fmt.Errorf("unsupported TrustedRoot media type: %s", protobufTrustedRoot.GetMediaType())
}
trustedRoot = &TrustedRoot{trustedRoot: protobufTrustedRoot}
trustedRoot.rekorLogs, err = ParseTransparencyLogs(protobufTrustedRoot.GetTlogs())
if err != nil {
return nil, err
}
trustedRoot.fulcioCertAuthorities, err = ParseCertificateAuthorities(protobufTrustedRoot.GetCertificateAuthorities())
if err != nil {
return nil, err
}
trustedRoot.timestampingAuthorities, err = ParseCertificateAuthorities(protobufTrustedRoot.GetTimestampAuthorities())
if err != nil {
return nil, err
}
trustedRoot.ctLogs, err = ParseTransparencyLogs(protobufTrustedRoot.GetCtlogs())
if err != nil {
return nil, err
}
return trustedRoot, nil
}
func ParseTransparencyLogs(tlogs []*prototrustroot.TransparencyLogInstance) (transparencyLogs map[string]*TransparencyLog, err error) {
transparencyLogs = make(map[string]*TransparencyLog)
for _, tlog := range tlogs {
if tlog.GetHashAlgorithm() != protocommon.HashAlgorithm_SHA2_256 {
return nil, fmt.Errorf("unsupported tlog hash algorithm: %s", tlog.GetHashAlgorithm())
}
if tlog.GetLogId() == nil {
return nil, fmt.Errorf("tlog missing log ID")
}
if tlog.GetLogId().GetKeyId() == nil {
return nil, fmt.Errorf("tlog missing log ID key ID")
}
encodedKeyID := hex.EncodeToString(tlog.GetLogId().GetKeyId())
if tlog.GetPublicKey() == nil {
return nil, fmt.Errorf("tlog missing public key")
}
if tlog.GetPublicKey().GetRawBytes() == nil {
return nil, fmt.Errorf("tlog missing public key raw bytes")
}
var hashFunc crypto.Hash
switch tlog.GetHashAlgorithm() {
case protocommon.HashAlgorithm_SHA2_256:
hashFunc = crypto.SHA256
default:
return nil, fmt.Errorf("unsupported hash function for the tlog")
}
tlogEntry := &TransparencyLog{
BaseURL: tlog.GetBaseUrl(),
ID: tlog.GetLogId().GetKeyId(),
HashFunc: hashFunc,
SignatureHashFunc: crypto.SHA256,
}
switch tlog.GetPublicKey().GetKeyDetails() {
case protocommon.PublicKeyDetails_PKIX_ECDSA_P256_SHA_256,
protocommon.PublicKeyDetails_PKIX_ECDSA_P384_SHA_384,
protocommon.PublicKeyDetails_PKIX_ECDSA_P521_SHA_512:
key, err := x509.ParsePKIXPublicKey(tlog.GetPublicKey().GetRawBytes())
if err != nil {
return nil, err
}
var ecKey *ecdsa.PublicKey
var ok bool
if ecKey, ok = key.(*ecdsa.PublicKey); !ok {
return nil, fmt.Errorf("tlog public key is not ECDSA: %s", tlog.GetPublicKey().GetKeyDetails())
}
tlogEntry.PublicKey = ecKey
// This key format has public key in PKIX RSA format and PKCS1#1v1.5 or RSASSA-PSS signature
case protocommon.PublicKeyDetails_PKIX_RSA_PKCS1V15_2048_SHA256,
protocommon.PublicKeyDetails_PKIX_RSA_PKCS1V15_3072_SHA256,
protocommon.PublicKeyDetails_PKIX_RSA_PKCS1V15_4096_SHA256:
key, err := x509.ParsePKIXPublicKey(tlog.GetPublicKey().GetRawBytes())
if err != nil {
return nil, err
}
var rsaKey *rsa.PublicKey
var ok bool
if rsaKey, ok = key.(*rsa.PublicKey); !ok {
return nil, fmt.Errorf("tlog public key is not RSA: %s", tlog.GetPublicKey().GetKeyDetails())
}
tlogEntry.PublicKey = rsaKey
case protocommon.PublicKeyDetails_PKIX_ED25519: //nolint:staticcheck
key, err := x509.ParsePKIXPublicKey(tlog.GetPublicKey().GetRawBytes())
if err != nil {
return nil, err
}
var edKey ed25519.PublicKey
var ok bool
if edKey, ok = key.(ed25519.PublicKey); !ok {
return nil, fmt.Errorf("tlog public key is not RSA: %s", tlog.GetPublicKey().GetKeyDetails())
}
tlogEntry.PublicKey = edKey
// This key format is deprecated, but currently in use for Sigstore staging instance
case protocommon.PublicKeyDetails_PKCS1_RSA_PKCS1V5: //nolint:staticcheck
key, err := x509.ParsePKCS1PublicKey(tlog.GetPublicKey().GetRawBytes())
if err != nil {
return nil, err
}
tlogEntry.PublicKey = key
default:
return nil, fmt.Errorf("unsupported tlog public key type: %s", tlog.GetPublicKey().GetKeyDetails())
}
tlogEntry.SignatureHashFunc = getSignatureHashAlgo(tlogEntry.PublicKey)
transparencyLogs[encodedKeyID] = tlogEntry
if validFor := tlog.GetPublicKey().GetValidFor(); validFor != nil {
if validFor.GetStart() != nil {
transparencyLogs[encodedKeyID].ValidityPeriodStart = validFor.GetStart().AsTime()
} else {
return nil, fmt.Errorf("tlog missing public key validity period start time")
}
if validFor.GetEnd() != nil {
transparencyLogs[encodedKeyID].ValidityPeriodEnd = validFor.GetEnd().AsTime()
}
} else {
return nil, fmt.Errorf("tlog missing public key validity period")
}
}
return transparencyLogs, nil
}
func ParseCertificateAuthorities(certAuthorities []*prototrustroot.CertificateAuthority) (certificateAuthorities []CertificateAuthority, err error) {
certificateAuthorities = make([]CertificateAuthority, len(certAuthorities))
for i, certAuthority := range certAuthorities {
certificateAuthority, err := ParseCertificateAuthority(certAuthority)
if err != nil {
return nil, err
}
certificateAuthorities[i] = *certificateAuthority
}
return certificateAuthorities, nil
}
func ParseCertificateAuthority(certAuthority *prototrustroot.CertificateAuthority) (certificateAuthority *CertificateAuthority, err error) {
if certAuthority == nil {
return nil, fmt.Errorf("CertificateAuthority is nil")
}
certChain := certAuthority.GetCertChain()
if certChain == nil {
return nil, fmt.Errorf("CertificateAuthority missing cert chain")
}
chainLen := len(certChain.GetCertificates())
if chainLen < 1 {
return nil, fmt.Errorf("CertificateAuthority cert chain is empty")
}
certificateAuthority = &CertificateAuthority{
URI: certAuthority.Uri,
}
for i, cert := range certChain.GetCertificates() {
parsedCert, err := x509.ParseCertificate(cert.RawBytes)
if err != nil {
return nil, err
}
switch {
case i == 0 && !parsedCert.IsCA:
certificateAuthority.Leaf = parsedCert
case i < chainLen-1:
certificateAuthority.Intermediates = append(certificateAuthority.Intermediates, parsedCert)
case i == chainLen-1:
certificateAuthority.Root = parsedCert
}
}
validFor := certAuthority.GetValidFor()
if validFor != nil {
start := validFor.GetStart()
if start != nil {
certificateAuthority.ValidityPeriodStart = start.AsTime()
}
end := validFor.GetEnd()
if end != nil {
certificateAuthority.ValidityPeriodEnd = end.AsTime()
}
}
certificateAuthority.URI = certAuthority.Uri
// TODO: Should we inspect/enforce ca.Subject?
// TODO: Handle validity period (ca.ValidFor)
return certificateAuthority, nil
}
func NewTrustedRootFromPath(path string) (*TrustedRoot, error) {
trustedrootJSON, err := os.ReadFile(path)
if err != nil {
return nil, err
}
return NewTrustedRootFromJSON(trustedrootJSON)
}
// NewTrustedRootFromJSON returns the Sigstore trusted root.
func NewTrustedRootFromJSON(rootJSON []byte) (*TrustedRoot, error) {
pbTrustedRoot, err := NewTrustedRootProtobuf(rootJSON)
if err != nil {
return nil, err
}
return NewTrustedRootFromProtobuf(pbTrustedRoot)
}
// NewTrustedRootProtobuf returns the Sigstore trusted root as a protobuf.
func NewTrustedRootProtobuf(rootJSON []byte) (*prototrustroot.TrustedRoot, error) {
pbTrustedRoot := &prototrustroot.TrustedRoot{}
err := protojson.Unmarshal(rootJSON, pbTrustedRoot)
if err != nil {
return nil, err
}
return pbTrustedRoot, nil
}
// NewTrustedRoot initializes a TrustedRoot object from a mediaType string, list of Fulcio
// certificate authorities, list of timestamp authorities and maps of ctlogs and rekor
// transparency log instances.
func NewTrustedRoot(mediaType string,
certificateAuthorities []CertificateAuthority,
certificateTransparencyLogs map[string]*TransparencyLog,
timestampAuthorities []CertificateAuthority,
transparencyLogs map[string]*TransparencyLog) (*TrustedRoot, error) {
// document that we assume 1 cert chain per target and with certs already ordered from leaf to root
if mediaType != TrustedRootMediaType01 {
return nil, fmt.Errorf("unsupported TrustedRoot media type: %s", TrustedRootMediaType01)
}
tr := &TrustedRoot{
fulcioCertAuthorities: certificateAuthorities,
ctLogs: certificateTransparencyLogs,
timestampingAuthorities: timestampAuthorities,
rekorLogs: transparencyLogs,
}
return tr, nil
}
// FetchTrustedRoot fetches the Sigstore trusted root from TUF and returns it.
func FetchTrustedRoot() (*TrustedRoot, error) {
return FetchTrustedRootWithOptions(tuf.DefaultOptions())
}
// FetchTrustedRootWithOptions fetches the trusted root from TUF with the given options and returns it.
func FetchTrustedRootWithOptions(opts *tuf.Options) (*TrustedRoot, error) {
client, err := tuf.New(opts)
if err != nil {
return nil, err
}
return GetTrustedRoot(client)
}
// GetTrustedRoot returns the trusted root
func GetTrustedRoot(c *tuf.Client) (*TrustedRoot, error) {
jsonBytes, err := c.GetTarget("trusted_root.json")
if err != nil {
return nil, err
}
return NewTrustedRootFromJSON(jsonBytes)
}
func getSignatureHashAlgo(pubKey crypto.PublicKey) crypto.Hash {
var h crypto.Hash
switch pk := pubKey.(type) {
case *rsa.PublicKey:
h = crypto.SHA256
case *ecdsa.PublicKey:
switch pk.Curve {
case elliptic.P256():
h = crypto.SHA256
case elliptic.P384():
h = crypto.SHA384
case elliptic.P521():
h = crypto.SHA512
default:
h = crypto.SHA256
}
case ed25519.PublicKey:
h = crypto.SHA512
default:
h = crypto.SHA256
}
return h
}
// LiveTrustedRoot is a wrapper around TrustedRoot that periodically
// refreshes the trusted root from TUF. This is needed for long-running
// processes to ensure that the trusted root does not expire.
type LiveTrustedRoot struct {
*TrustedRoot
mu sync.RWMutex
}
// NewLiveTrustedRoot returns a LiveTrustedRoot that will periodically
// refresh the trusted root from TUF.
func NewLiveTrustedRoot(opts *tuf.Options) (*LiveTrustedRoot, error) {
client, err := tuf.New(opts)
if err != nil {
return nil, err
}
tr, err := GetTrustedRoot(client)
if err != nil {
return nil, err
}
ltr := &LiveTrustedRoot{
TrustedRoot: tr,
mu: sync.RWMutex{},
}
ticker := time.NewTicker(time.Hour * 24)
go func() {
for {
select {
case <-ticker.C:
client, err = tuf.New(opts)
if err != nil {
log.Printf("error creating TUF client: %v", err)
}
newTr, err := GetTrustedRoot(client)
if err != nil {
log.Printf("error fetching trusted root: %v", err)
continue
}
ltr.mu.Lock()
ltr.TrustedRoot = newTr
ltr.mu.Unlock()
}
}
}()
return ltr, nil
}
func (l *LiveTrustedRoot) TimestampingAuthorities() []CertificateAuthority {
l.mu.RLock()
defer l.mu.RUnlock()
return l.TrustedRoot.TimestampingAuthorities()
}
func (l *LiveTrustedRoot) FulcioCertificateAuthorities() []CertificateAuthority {
l.mu.RLock()
defer l.mu.RUnlock()
return l.TrustedRoot.FulcioCertificateAuthorities()
}
func (l *LiveTrustedRoot) RekorLogs() map[string]*TransparencyLog {
l.mu.RLock()
defer l.mu.RUnlock()
return l.TrustedRoot.RekorLogs()
}
func (l *LiveTrustedRoot) CTLogs() map[string]*TransparencyLog {
l.mu.RLock()
defer l.mu.RUnlock()
return l.TrustedRoot.CTLogs()
}
func (l *LiveTrustedRoot) PublicKeyVerifier(keyID string) (TimeConstrainedVerifier, error) {
l.mu.RLock()
defer l.mu.RUnlock()
return l.TrustedRoot.PublicKeyVerifier(keyID)
}