-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathverifier.go
552 lines (439 loc) · 13 KB
/
verifier.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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
package httpsig
import (
"context"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/dunglas/httpsfv"
)
type Verifier interface {
Verify(msg *Message) error
}
//go:generate mockery --name KeyResolver --structname KeyResolverMock --inpackage --testonly
// KeyResolver is used to resolve a key id to a verifying key.
type KeyResolver interface {
ResolveKey(ctx context.Context, keyID string) (Key, error)
}
type payloadVerifier interface {
verifyPayload(data []byte, signature []byte) error
algorithm() SignatureAlgorithm
keyID() string
}
func newPayloadVerifier(verificationKey any, keyID string, alg SignatureAlgorithm) (payloadVerifier, error) {
switch publicKey := verificationKey.(type) {
case ed25519.PublicKey:
return newEd25519Verifier(publicKey, keyID, alg)
case *rsa.PublicKey:
return newRSAVerifier(publicKey, keyID, alg)
case *ecdsa.PublicKey:
return newECDSAVerifier(publicKey, keyID, alg)
case []byte:
return newSymmetricSigner(publicKey, keyID, alg)
default:
return nil, ErrUnsupportedKeyType
}
}
type VerifierOption func(v *verifier, e *expectations, f bool) error
// WithRequiredComponents sets the HTTP fields / derived component names to be included in signing.
func WithRequiredComponents(identifiers ...string) VerifierOption {
return func(_ *verifier, exp *expectations, _ bool) error {
var err error
exp.identifiers, err = toComponentIdentifiers(identifiers)
return err
}
}
// WithValidityTolerance sets the clock tolerance for verifying created and expires times.
func WithValidityTolerance(d time.Duration) VerifierOption {
return func(_ *verifier, e *expectations, _ bool) error {
e.tolerance = d
return nil
}
}
func WithMaxAge(d time.Duration) VerifierOption {
return func(_ *verifier, e *expectations, _ bool) error {
e.maxAge = d
return nil
}
}
func WithNonceChecker(checker NonceChecker) VerifierOption {
return func(v *verifier, _ *expectations, _ bool) error {
if checker != nil {
v.nonceChecker = checker
}
return nil
}
}
func WithRequiredTag(tag string, opts ...VerifierOption) VerifierOption {
return func(ver *verifier, _ *expectations, f bool) error {
if f {
panic("WithRequiredTag cannot be used as option for itself")
}
if _, configured := ver.tagExpectations[tag]; configured {
return fmt.Errorf("%w: requirements for tag %s are already configured", ErrParameter, tag)
}
exp := &expectations{
tolerance: -1,
maxAge: -1,
}
for _, opt := range opts {
if err := opt(ver, exp, true); err != nil {
return err
}
}
ver.tagExpectations[tag] = exp
return nil
}
}
func WithValidateAllSignatures() VerifierOption {
return func(v *verifier, _ *expectations, _ bool) error {
v.validateAllSigs = true
return nil
}
}
func WithCreatedTimestampRequired(flag bool) VerifierOption {
return func(_ *verifier, exp *expectations, _ bool) error {
exp.reqCreatedTS = &flag
return nil
}
}
func WithExpiredTimestampRequired(flag bool) VerifierOption {
return func(_ *verifier, exp *expectations, _ bool) error {
exp.reqExpiresTS = &flag
return nil
}
}
func WithSignatureNegotiation(opts ...SignatureNegotiationOption) VerifierOption {
no := &sigNegotiationOpts{opts: make([]AcceptSignatureOption, 0, len(opts))}
for _, opt := range opts {
opt(no)
}
return func(_ *verifier, exp *expectations, _ bool) error {
builder, err := NewAcceptSignature(no.opts...)
if err != nil {
return err
}
exp.asb = builder
return nil
}
}
type sigNegotiationOpts struct {
opts []AcceptSignatureOption
}
type SignatureNegotiationOption func(sno *sigNegotiationOpts)
func WithRequestedKey(key Key) SignatureNegotiationOption {
return func(sno *sigNegotiationOpts) {
sno.opts = append(sno.opts, WithExpectedKey(key))
}
}
func WithRequestedNonce(ng NonceGetter) SignatureNegotiationOption {
return func(sno *sigNegotiationOpts) {
sno.opts = append(sno.opts, WithExpectedNonce(ng))
}
}
func WithRequestedContentDigestAlgorithmPreferences(prefs ...AlgorithmPreference) SignatureNegotiationOption {
return func(sno *sigNegotiationOpts) {
sno.opts = append(sno.opts, WithContentDigestAlgorithmPreferences(prefs...))
}
}
func WithRequestedLabel(label string) SignatureNegotiationOption {
return func(sno *sigNegotiationOpts) {
sno.opts = append(sno.opts, WithExpectedLabel(label))
}
}
// NewVerifier creates a new verifier with the given options.
//
//nolint:cyclop
func NewVerifier(resolver KeyResolver, opts ...VerifierOption) (Verifier, error) {
if resolver == nil {
return nil, fmt.Errorf("%w: no key resolver provided", ErrVerifierCreation)
}
trueValue := true
ver := &verifier{
keyResolver: resolver,
tagExpectations: make(map[string]*expectations),
nonceChecker: noopNonceChecker{},
}
global := &expectations{
maxAge: 30 * time.Second, //nolint:mnd
reqExpiresTS: &trueValue,
reqCreatedTS: &trueValue,
}
for _, opt := range opts {
if err := opt(ver, global, false); err != nil {
return nil, fmt.Errorf("%w: %w", ErrVerifierCreation, err)
}
}
if !ver.validateAllSigs && len(ver.tagExpectations) == 0 {
return nil, fmt.Errorf("%w: validation of all signatures disabled, but no signature tags specified",
ErrVerifierCreation)
}
if global.asb != nil && ver.validateAllSigs {
return nil, fmt.Errorf("%w: verification and negotiation of all posible signature is not possible",
ErrVerifierCreation)
}
if global.asb != nil {
global.asb.setIdentifiers(global.identifiers)
}
for tag, exp := range ver.tagExpectations {
if exp.tolerance == -1 {
exp.tolerance = global.tolerance
}
if exp.maxAge == -1 {
exp.maxAge = global.maxAge
}
if len(global.identifiers) != 0 && len(exp.identifiers) == 0 {
exp.identifiers = global.identifiers
}
if exp.reqExpiresTS == nil {
exp.reqExpiresTS = global.reqExpiresTS
}
if exp.reqCreatedTS == nil {
exp.reqCreatedTS = global.reqCreatedTS
}
if global.asb != nil && exp.asb == nil {
// create a copy
tmp := *global.asb
exp.asb = &tmp
}
if exp.asb != nil {
exp.asb.setIdentifiers(exp.identifiers)
exp.asb.tag = tag
exp.asb.addCreatedTS = *exp.reqCreatedTS
exp.asb.addExpiresTS = *exp.reqExpiresTS
}
}
if ver.validateAllSigs {
ver.tagExpectations[""] = global
}
return ver, nil
}
type expectations struct {
tolerance time.Duration
maxAge time.Duration
identifiers []*componentIdentifier
asb *AcceptSignatureBuilder
reqCreatedTS *bool
reqExpiresTS *bool
}
//nolint:cyclop
func (e *expectations) assert(
params *signatureParameters,
msg *Message,
keyAlg SignatureAlgorithm,
nc NonceChecker,
) error {
var (
nonce string
missingComponents []string
cmv compositeMessageVerifier
mv messageVerifier
)
nonceValue, noncePresent := params.Params.Get(string(Nonce))
if noncePresent {
nonce = nonceValue.(string) //nolint: forcetypeassert
}
if err := nc.CheckNonce(msg.Context, nonce); err != nil {
return fmt.Errorf("%w: nonce validation failed: %w", ErrParameter, err)
}
if len(params.alg) != 0 && params.alg != keyAlg {
return fmt.Errorf("%w: key algorithm %s does not match signature algorithm %s",
ErrParameter, params.alg, keyAlg)
}
now := currentTime().UTC()
if params.expires.Equal(time.Time{}) {
if *e.reqExpiresTS {
return fmt.Errorf("%w: expected expires parameter not preset", ErrMissingParameter)
}
} else if now.After(params.expires.Add(e.tolerance)) {
return fmt.Errorf("%w: signature expired", ErrValidity)
}
if params.created.Equal(time.Time{}) {
if *e.reqCreatedTS {
return fmt.Errorf("%w: expected created parameter not preset", ErrMissingParameter)
}
} else {
if now.Before(params.created.Add(-1 * e.tolerance)) {
return fmt.Errorf("%w: signature not yet valid", ErrValidity)
}
if params.created.Add(e.maxAge).Before(now) {
return fmt.Errorf("%w: signature too old", ErrValidity)
}
}
for _, expIdentifier := range e.identifiers {
if !params.hasIdentifier(expIdentifier) {
res, _ := httpsfv.Marshal(expIdentifier)
missingComponents = append(missingComponents, res)
}
}
if len(missingComponents) > 0 {
return fmt.Errorf("%w: missing component identifiers: %s",
ErrMissingParameter, strings.Join(missingComponents, ", "))
}
for _, id := range params.identifiers {
if id.Value == "content-digest" {
_, fromReq := id.Params.Get("req")
cmv = append(cmv, contentDigester{fromRequest: fromReq})
}
}
if len(cmv) == 0 {
mv = noopMessageVerifier{}
} else {
mv = cmv
}
return mv.verify(msg)
}
type verifier struct {
keyResolver KeyResolver
tagExpectations map[string]*expectations
validateAllSigs bool
nonceChecker NonceChecker
}
func (v *verifier) Verify(msg *Message) error {
sigRefs, err := getSignatureReferences(msg.Header.Values(headerSignatureInput))
if err != nil {
return fmt.Errorf("%w: %w", ErrVerificationFailed, err)
}
signatureDict, err := httpsfv.UnmarshalDictionary(msg.Header.Values(headerSignature))
if err != nil {
return fmt.Errorf("%w: %w", ErrVerificationFailed, err)
}
// look if we miss any signatures for configured tags
if v.hasMissingSignatures(sigRefs) {
return fmt.Errorf("%w: %w", ErrVerificationFailed, v.negotiateSignatureParameters(msg))
}
// collect those signatures, which we can verify
applicableSignatures, err := v.applicableSignatures(sigRefs)
if err != nil {
return fmt.Errorf("%w: %w", ErrVerificationFailed, err)
}
// do the actual verification
for name, params := range applicableSignatures {
exp, exists := v.tagExpectations[params.tag]
if !exists {
exp = v.tagExpectations[""]
}
signature, err := v.extractSignature(signatureDict, name)
if err != nil {
return fmt.Errorf("%w: %w", ErrVerificationFailed, err)
}
err = v.verifySignature(msg, signature, params, exp)
if err != nil {
if errors.Is(err, ErrMissingParameter) {
return fmt.Errorf("%w: %w", ErrVerificationFailed, v.negotiateSignatureParameters(msg))
}
return fmt.Errorf("%w: %w", ErrVerificationFailed, err)
}
}
return nil
}
func (v *verifier) applicableSignatures(refs map[string]*signatureParameters) (map[string]*signatureParameters, error) {
for name, params := range refs {
if !v.isApplicable(params.tag) {
delete(refs, name)
}
}
if len(refs) == 0 {
return nil, &NoApplicableSignatureError{}
}
return refs, nil
}
func (v *verifier) negotiateSignatureParameters(msg *Message) error {
hdr := http.Header{}
for sigTag, exp := range v.tagExpectations {
if exp.asb == nil || len(sigTag) == 0 {
continue
}
err := exp.asb.Build(msg.Context, hdr)
if err != nil {
return fmt.Errorf("%w: failed to negotiate signature for tag %s: %w", ErrSignatureNegotiationError, sigTag, err)
}
}
return &NoApplicableSignatureError{headerToAdd: hdr}
}
func (v *verifier) hasMissingSignatures(sigRefs map[string]*signatureParameters) bool {
for sigTag := range v.tagExpectations {
if len(sigTag) == 0 {
// empty tag is used for expectations for all signatures
// ignoring it
continue
}
var present bool
for _, sigRef := range sigRefs {
if sigRef.tag == sigTag {
present = true
break
}
}
if !present {
return true
}
}
return false
}
func (v *verifier) verifySignature(
msg *Message,
signature []byte,
params *signatureParameters,
exp *expectations,
) error {
base, err := params.toSignatureBase(msg)
if err != nil {
return err
}
key, err := v.keyResolver.ResolveKey(msg.Context, params.keyID)
if err != nil {
return err
}
if err = exp.assert(params, msg, key.Algorithm, v.nonceChecker); err != nil {
return err
}
verifier, err := newPayloadVerifier(key.Key, key.KeyID, key.Algorithm)
if err != nil {
return err
}
return verifier.verifyPayload(base, signature)
}
func getSignatureReferences(values []string) (map[string]*signatureParameters, error) {
inputDict, err := httpsfv.UnmarshalDictionary(values)
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrMalformedData, err)
}
sigRefs := make(map[string]*signatureParameters, len(inputDict.Names()))
for _, label := range inputDict.Names() {
var sp signatureParameters
m, _ := inputDict.Get(label)
sigParams, ok := m.(httpsfv.InnerList)
if !ok {
return nil, fmt.Errorf("%w: unexpected signature parameters format", ErrMalformedData)
}
if err := sp.fromInnerList(sigParams); err != nil {
return nil, fmt.Errorf("%w: %w", ErrMalformedData, err)
}
sigRefs[label] = &sp
}
return sigRefs, nil
}
func (v *verifier) extractSignature(dict *httpsfv.Dictionary, name string) ([]byte, error) {
sigItem, ok := dict.Get(name)
if !ok {
return nil, fmt.Errorf("%w: no signature present for label %s", ErrMalformedData, name)
}
signature, ok := sigItem.(httpsfv.Item)
if !ok {
return nil, fmt.Errorf("%w: unexpected content type for label %s", ErrMalformedData, name)
}
signatureBytes, ok := signature.Value.([]byte)
if !ok {
return nil, fmt.Errorf("%w: unexpected value for label %s", ErrMalformedData, name)
}
return signatureBytes, nil
}
func (v *verifier) isApplicable(tag string) bool {
_, hasKey := v.tagExpectations[tag]
return v.validateAllSigs || hasKey
}