-
Notifications
You must be signed in to change notification settings - Fork 3
/
tl.go
266 lines (235 loc) · 8.4 KB
/
tl.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
package tlog
import (
"context"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"crypto/x509/pkix"
"encoding/base64"
"encoding/pem"
"fmt"
"math/big"
"strings"
"time"
"github.com/docker/attest/internal/util"
"github.com/docker/attest/pkg/signerverifier"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
"github.com/secure-systems-lab/go-securesystemslib/dsse"
"github.com/sigstore/cosign/v2/pkg/cosign"
rclient "github.com/sigstore/rekor/pkg/client"
"github.com/sigstore/rekor/pkg/generated/models"
"github.com/sigstore/rekor/pkg/types"
hashedrekord_v001 "github.com/sigstore/rekor/pkg/types/hashedrekord/v0.0.1"
)
const (
DefaultRekorURL = "https://rekor.sigstore.dev"
)
type tlCtxKeyType struct{}
var TlCtxKey tlCtxKeyType
// sets TL in context
func WithTL(ctx context.Context, tl TL) context.Context {
return context.WithValue(ctx, TlCtxKey, tl)
}
// gets TL from context, defaults to Rekor TL if not set
func GetTL(ctx context.Context) TL {
t, ok := ctx.Value(TlCtxKey).(TL)
if !ok {
t = &RekorTL{}
}
return t
}
type TlPayload struct {
Algorithm string
Hash string
Signature string
PublicKey string
}
type TL interface {
UploadLogEntry(ctx context.Context, subject string, payload, signature []byte, signer dsse.SignerVerifier) ([]byte, error)
VerifyLogEntry(ctx context.Context, entryBytes []byte) (time.Time, error)
VerifyEntryPayload(entryBytes, payload, publicKey []byte) error
UnmarshalEntry(entryBytes []byte) (any, error)
}
type MockTL struct {
UploadLogEntryFunc func(ctx context.Context, subject string, payload, signature []byte, signer dsse.SignerVerifier) ([]byte, error)
VerifyLogEntryFunc func(ctx context.Context, entryBytes []byte) (time.Time, error)
VerifyEntryPayloadFunc func(entryBytes, payload, publicKey []byte) error
UnmarshalEntryFunc func(entryBytes []byte) (any, error)
}
func (tl *MockTL) UploadLogEntry(ctx context.Context, subject string, payload, signature []byte, signer dsse.SignerVerifier) ([]byte, error) {
if tl.UploadLogEntryFunc != nil {
return tl.UploadLogEntryFunc(ctx, subject, payload, signature, signer)
}
return nil, nil
}
func (tl *MockTL) VerifyLogEntry(ctx context.Context, entryBytes []byte) (time.Time, error) {
if tl.VerifyLogEntryFunc != nil {
return tl.VerifyLogEntryFunc(ctx, entryBytes)
}
return time.Time{}, nil
}
func (tl *MockTL) VerifyEntryPayload(entryBytes, payload, publicKey []byte) error {
if tl.VerifyEntryPayloadFunc != nil {
return tl.VerifyEntryPayloadFunc(entryBytes, payload, publicKey)
}
return nil
}
func (tl *MockTL) UnmarshalEntry(entryBytes []byte) (any, error) {
if tl.UnmarshalEntryFunc != nil {
return tl.UnmarshalEntryFunc(entryBytes)
}
return nil, nil
}
type RekorTL struct{}
// UploadLogEntry submits a PK token signature to the transparency log
func (tl *RekorTL) UploadLogEntry(ctx context.Context, subject string, payload, signature []byte, signer dsse.SignerVerifier) ([]byte, error) {
// generate self-signed x509 cert
pubCert, err := CreateX509Cert(subject, signer)
if err != nil {
return nil, fmt.Errorf("Error creating x509 cert: %w", err)
}
// generate hash of payload
hasher := sha256.New()
hasher.Write(payload)
// upload entry
rekorClient, err := rclient.GetRekorClient(DefaultRekorURL)
if err != nil {
return nil, fmt.Errorf("Error creating rekor client: %w", err)
}
entry, err := cosign.TLogUpload(ctx, rekorClient, signature, hasher, pubCert)
if err != nil {
return nil, fmt.Errorf("Error uploading tlog: %w", err)
}
entryBytes, err := entry.MarshalBinary()
if err != nil {
return nil, fmt.Errorf("error marshalling TL entry: %w", err)
}
return entryBytes, nil
}
// VerifyLogEntry verifies a transparency log entry
func (tl *RekorTL) VerifyLogEntry(ctx context.Context, entryBytes []byte) (time.Time, error) {
zeroTime := time.Time{}
entry, err := tl.UnmarshalEntry(entryBytes)
if err != nil {
return zeroTime, fmt.Errorf("error failed to unmarshal TL entry: %w", err)
}
le, ok := entry.(*models.LogEntryAnon)
if !ok {
return zeroTime, fmt.Errorf("expected entry to be of type *models.LogEntryAnon, got %T", entry)
}
err = le.Validate(strfmt.Default)
if err != nil {
return zeroTime, fmt.Errorf("TL entry failed validation: %w", err)
}
// TODO: get rekor public keys from TUF (ours or theirs?), and/or embed the public key in the binary
rekorPubKeys, err := cosign.GetRekorPubs(ctx)
if err != nil {
return zeroTime, fmt.Errorf("error failed to get rekor public keys: %w", err)
}
err = cosign.VerifyTLogEntryOffline(ctx, le, rekorPubKeys)
if err != nil {
return zeroTime, fmt.Errorf("TL entry failed verification: %w", err)
}
integratedTime := time.Unix(*le.IntegratedTime, 0)
return integratedTime, nil
}
// CreateX509Cert generates a self-signed x509 cert for TL submission
func CreateX509Cert(subject string, signer dsse.SignerVerifier) ([]byte, error) {
// encode ephemeral public key
ecPub, err := x509.MarshalPKIXPublicKey(signer.Public())
if err != nil {
return nil, fmt.Errorf("error marshalling public key: %w", err)
}
template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{CommonName: subject},
RawSubjectPublicKeyInfo: ecPub,
NotBefore: time.Now(),
NotAfter: time.Now().Add(365 * 24 * time.Hour), // valid for 1 year
KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageCodeSigning},
BasicConstraintsValid: true,
DNSNames: []string{subject},
IsCA: false,
}
// dsse.SignerVerifier doesn't implement cypto.Signer exactly
csigner, ok := signer.(*signerverifier.ECDSA256_SignerVerifier)
if !ok {
return nil, fmt.Errorf("expected signer to be of type *signerverifier.ECDSA_SignerVerifier, got %T", signer)
}
// create a self-signed X.509 certificate
certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, signer.Public(), csigner.Signer)
if err != nil {
return nil, fmt.Errorf("error creating X.509 certificate: %w", err)
}
certBlock := &pem.Block{Type: "CERTIFICATE", Bytes: certDER}
return pem.EncodeToMemory(certBlock), nil
}
// VerifyEntryPayload checks that the TL entry payload matches envelope payload
func (tl *RekorTL) VerifyEntryPayload(entryBytes, payload, publicKey []byte) error {
entry, err := tl.UnmarshalEntry(entryBytes)
if err != nil {
return fmt.Errorf("error failed to unmarshal TL entry: %w", err)
}
le, ok := entry.(*models.LogEntryAnon)
if !ok {
return fmt.Errorf("expected tl entry to be of type *models.LogEntryAnon, got %T", entry)
}
tlBody, ok := le.Body.(string)
if !ok {
return fmt.Errorf("expected tl body to be of type string, got %T", entry)
}
rekord, err := extractHashedRekord(tlBody)
if err != nil {
return fmt.Errorf("error extract HashedRekord from TL entry: %w", err)
}
// compare payload hashes
payloadHash := util.SHA256Hex(payload)
if rekord.Hash != payloadHash {
return fmt.Errorf("error payload and tl entry hash mismatch")
}
// compare public keys
cert, err := base64.StdEncoding.Strict().DecodeString(rekord.PublicKey)
if err != nil {
return fmt.Errorf("failed to decode public key: %w", err)
}
p, _ := pem.Decode(cert)
result, err := x509.ParseCertificate(p.Bytes)
if err != nil {
return fmt.Errorf("failed to parse certificate: %w", err)
}
if string(result.RawSubjectPublicKeyInfo) != string(publicKey) {
return fmt.Errorf("error payload and tl entry public key mismatch")
}
return nil
}
func (tl *RekorTL) UnmarshalEntry(entry []byte) (any, error) {
le := new(models.LogEntryAnon)
err := le.UnmarshalBinary(entry)
if err != nil {
return nil, fmt.Errorf("error failed to unmarshal TL entry: %w", err)
}
return le, nil
}
func extractHashedRekord(Body string) (*TlPayload, error) {
sig := new(TlPayload)
pe, err := models.UnmarshalProposedEntry(base64.NewDecoder(base64.StdEncoding, strings.NewReader(Body)), runtime.JSONConsumer())
if err != nil {
return nil, err
}
impl, err := types.UnmarshalEntry(pe)
if err != nil {
return nil, err
}
switch entry := impl.(type) {
case *hashedrekord_v001.V001Entry:
sig.Algorithm = *entry.HashedRekordObj.Data.Hash.Algorithm
sig.Hash = *entry.HashedRekordObj.Data.Hash.Value
sig.Signature = entry.HashedRekordObj.Signature.Content.String()
sig.PublicKey = entry.HashedRekordObj.Signature.PublicKey.Content.String()
return sig, nil
default:
return nil, fmt.Errorf("failed to extract haskedrekord, unsupported type: %T", entry)
}
}