-
Notifications
You must be signed in to change notification settings - Fork 6
/
to2.go
1635 lines (1472 loc) · 59.2 KB
/
to2.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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: (C) 2024 Intel Corporation
// SPDX-License-Identifier: Apache 2.0
package fdo
import (
"bytes"
"context"
"crypto"
"crypto/ecdsa"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/hex"
"errors"
"fmt"
"hash"
"io"
"iter"
"log/slog"
"math"
"reflect"
"runtime"
"strings"
"sync"
"time"
"github.com/fido-device-onboard/go-fdo/cbor"
"github.com/fido-device-onboard/go-fdo/cbor/cdn"
"github.com/fido-device-onboard/go-fdo/cose"
"github.com/fido-device-onboard/go-fdo/kex"
"github.com/fido-device-onboard/go-fdo/plugin"
"github.com/fido-device-onboard/go-fdo/protocol"
"github.com/fido-device-onboard/go-fdo/serviceinfo"
)
// COSE claims for TO2ProveOVHdrUnprotectedHeaders
var (
to2NonceClaim = cose.Label{Int64: 256}
to2OwnerPubKeyClaim = cose.Label{Int64: 257}
)
// TO2Config contains the device credential, including secrets and keys,
// optional configuration, and service info modules.
type TO2Config struct {
// Non-secret device credential data.
Cred DeviceCredential
// HMAC-SHA256 with a device secret that does not change when ownership is
// transferred. HMAC-SHA256 support is always required by spec, so this
// field must be non-nil.
//
// This hash.Hash may optionally implement the following interface to
// return errors from Reset/Write/Sum, noting that implementations of
// hash.Hash are not supposed to return non-nil errors from Write.
//
// type FallibleHash interface {
// Err() error
// }
HmacSha256 hash.Hash
// HMAC-SHA384 with a device secret that does not change when ownership is
// transferred. HMAC-SHA384 support is optional by spec, so this field may
// be nil iff Key is RSA 2048 or EC P-256.
//
// This hash.Hash may optionally implement the following interface to
// return errors from Reset/Write/Sum, noting that implementations of
// hash.Hash are not supposed to return non-nil errors from Write.
//
// type FallibleHash interface {
// Err() error
// }
HmacSha384 hash.Hash
// An ECDSA or RSA private key that may or may not be implemented with the
// stdlib ecdsa and rsa packages.
Key crypto.Signer
// When true and an RSA key is used as a crypto.Signer argument, RSA-SSAPSS
// will be used for signing.
PSS bool
// Devmod contains all required and any number of optional messages.
//
// Alternatively to setting this field, a devmod module may be provided in
// the arguments to TransferOwnership2 where the module must provide any
// devmod messages EXCEPT nummodules and modules via its Yield method.
//
// Note: The device plugin will be yielded to exactly once and is expected
// to provide all required and desired fields and yield. It may then exit.
Devmod serviceinfo.Devmod
// Each ServiceInfo module will be reported in devmod and potentially
// activated and used. If a devmod module is included in this list, it
// overrides the Devmod field in TO2Config. The custom devmod should not
// send nummodules or modules messages, as these will always be sent upon
// module completion.
DeviceModules map[string]serviceinfo.DeviceModule
// Selects the key exchange suite to use. If unset, it defaults to ECDH384.
KeyExchange kex.Suite
// Selects the cipher suite to use for encryption. If unset, it defaults to
// A256GCM.
CipherSuite kex.CipherSuiteID
// Maximum transmission unit (MTU) to tell owner service to send with. If
// zero, the default of 1300 will be used. The value chosen can make a
// difference for performance when using service info to exchange large
// amounts of data, but choosing the best value depends on network
// configuration (e.g. jumbo packets) and transport (overhead size).
MaxServiceInfoSizeReceive uint16
// Allow for the Credential Reuse Protocol (Section 7) to be used. If not
// enabled, TO2 will fail with CredReuseErrCode (102) if reuse is
// attempted by the owner service.
AllowCredentialReuse bool
}
// TO2 runs the TO2 protocol and returns a DeviceCredential with replaced GUID,
// rendezvous info, and owner public key. It requires that a device credential,
// hmac secret, and key are all provided as configuration.
//
// A to1d signed blob is expected if rendezvous bypass is not used. This blob
// is output from TO1.
//
// It has the side effect of performing service info modules, which may include
// actions such as downloading files.
//
// If the Credential Reuse protocol is allowed and occurs, then the returned
// device credential will be nil.
func TO2(ctx context.Context, transport Transport, to1d *cose.Sign1[protocol.To1d, []byte], c TO2Config) (*DeviceCredential, error) {
ctx = contextWithErrMsg(ctx)
// Configure defaults
if c.KeyExchange == "" {
c.KeyExchange = kex.ECDH384Suite
}
if c.CipherSuite == 0 {
c.CipherSuite = kex.A256GcmCipher
}
if c.MaxServiceInfoSizeReceive == 0 {
c.MaxServiceInfoSizeReceive = serviceinfo.DefaultMTU
}
if c.DeviceModules == nil {
c.DeviceModules = make(map[string]serviceinfo.DeviceModule)
}
// Mutually attest the device and owner service
//
// Results: Replacement ownership voucher, nonces to be retransmitted in
// Done/Done2 messages
proveDeviceNonce, ownerPublicKey, originalOVH, sess, err := verifyOwner(ctx, transport, to1d, &c)
if err != nil {
errorMsg(ctx, transport, err)
return nil, err
}
defer sess.Destroy()
setupDeviceNonce, partialOVH, err := proveDevice(ctx, transport, proveDeviceNonce, ownerPublicKey, sess, &c)
if err != nil {
errorMsg(ctx, transport, err)
return nil, err
}
// Select the appropriate hash algorithm for HMAC and public key hash
alg := c.Cred.PublicKeyHash.Algorithm
var replacementOVH *VoucherHeader
if partialOVH != nil {
nextOwnerPublicKey, err := partialOVH.ManufacturerKey.Public()
if err != nil {
return nil, fmt.Errorf("error parsing manufacturer public key type from incomplete replacement ownership voucher header: %w", err)
}
alg, err = hashAlgFor(c.Key.Public(), nextOwnerPublicKey)
if err != nil {
return nil, fmt.Errorf("error selecting the appropriate hash algorithm: %w", err)
}
replacementOVH = &VoucherHeader{
Version: originalOVH.Version,
GUID: partialOVH.GUID,
RvInfo: partialOVH.RvInfo,
DeviceInfo: originalOVH.DeviceInfo,
ManufacturerKey: partialOVH.ManufacturerKey,
CertChainHash: originalOVH.CertChainHash,
}
}
// Prepare to send and receive service info, determining the transmit MTU
sendMTU, err := sendReadyServiceInfo(ctx, transport, alg, replacementOVH, sess, &c)
if err != nil {
errorMsg(ctx, transport, err)
return nil, err
}
// Start synchronously writing the initial device service info. This occurs
// in a goroutine because the pipe is unbuffered and needs to be
// concurrently read by the send/receive service info loop.
serviceInfoReader, serviceInfoWriter := serviceinfo.NewChunkOutPipe(0)
defer func() { _ = serviceInfoWriter.Close() }()
// Send devmod KVs in initial ServiceInfo
go c.Devmod.Write(ctx, c.DeviceModules, sendMTU, serviceInfoWriter)
// Loop, sending and receiving service info until done
if err := exchangeServiceInfo(ctx, transport, proveDeviceNonce, setupDeviceNonce, sendMTU, serviceInfoReader, sess, &c); err != nil {
errorMsg(ctx, transport, err)
return nil, err
}
// If using the Credential Reuse protocol the device credential is not updated
if replacementOVH == nil {
return nil, nil
}
// Hash new initial owner public key and return replacement device
// credential
replacementKeyDigest := alg.HashFunc().New()
if err := cbor.NewEncoder(replacementKeyDigest).Encode(replacementOVH.ManufacturerKey); err != nil {
err = fmt.Errorf("error computing hash of replacement owner key: %w", err)
errorMsg(ctx, transport, err)
return nil, err
}
replacementPublicKeyHash := protocol.Hash{Algorithm: alg, Value: replacementKeyDigest.Sum(nil)[:]}
return &DeviceCredential{
Version: replacementOVH.Version,
DeviceInfo: replacementOVH.DeviceInfo,
GUID: replacementOVH.GUID,
RvInfo: replacementOVH.RvInfo,
PublicKeyHash: replacementPublicKeyHash,
}, nil
}
// Stop any plugin device modules
func stopPlugins(modules *deviceModuleMap) {
pluginStopCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var pluginStopWg sync.WaitGroup
for name, mod := range modules.modules {
if !modules.active[name] {
continue
}
if p, ok := mod.(plugin.Module); ok {
pluginStopWg.Add(1)
pluginGracefulStopCtx, done := context.WithCancel(pluginStopCtx)
// Allow Graceful stop up to the original shared timeout
go func(p plugin.Module) {
defer done()
if err := p.GracefulStop(pluginGracefulStopCtx); err != nil && !errors.Is(err, context.Canceled) { //nolint:revive,staticcheck
slog.Warn("graceful stop failed", "module", name, "error", err)
}
}(p)
// Force stop after the shared timeout expires or graceful stop
// completes
go func(p plugin.Module) {
<-pluginGracefulStopCtx.Done()
_ = p.Stop()
pluginStopWg.Done()
}(p)
}
}
pluginStopWg.Wait()
}
// Verify owner by sending HelloDevice and validating the response, as well as
// all ownership voucher entries, which are retrieved iteratively with
// subsequence requests.
func verifyOwner(ctx context.Context, transport Transport, to1d *cose.Sign1[protocol.To1d, []byte], c *TO2Config) (protocol.Nonce, crypto.PublicKey, *VoucherHeader, kex.Session, error) {
proveDeviceNonce, info, sess, err := sendHelloDevice(ctx, transport, c)
if err != nil {
return protocol.Nonce{}, nil, nil, nil, err
}
if !c.KeyExchange.Valid(c.Key.Public(), info.PublicKeyToValidate) {
sess.Destroy()
return protocol.Nonce{}, nil, nil, nil, fmt.Errorf(
"key exchange %s is invalid for the device and owner attestation types",
c.KeyExchange,
)
}
if !kex.Available(c.KeyExchange, c.CipherSuite) {
sess.Destroy()
return protocol.Nonce{}, nil, nil, nil, fmt.Errorf("unsupported key exchange/cipher suite")
}
if err := verifyVoucher(ctx, transport, to1d, info, c); err != nil {
sess.Destroy()
return protocol.Nonce{}, nil, nil, nil, err
}
return proveDeviceNonce, info.PublicKeyToValidate, &info.OVH, sess, nil
}
func verifyVoucher(ctx context.Context, transport Transport, to1d *cose.Sign1[protocol.To1d, []byte], info *ovhValidationContext, c *TO2Config) error {
// Construct ownership voucher from parts received from the owner service
var entries []cose.Sign1Tag[VoucherEntryPayload, []byte]
for i := 0; i < info.NumVoucherEntries; i++ {
entry, err := sendNextOVEntry(ctx, transport, i)
if err != nil {
return err
}
entries = append(entries, *entry)
}
ov := Voucher{
Header: *cbor.NewBstr(info.OVH),
Hmac: info.OVHHmac,
Entries: entries,
}
// Verify ownership voucher header
if err := ov.VerifyHeader(c.HmacSha256, c.HmacSha384); err != nil {
captureErr(ctx, protocol.InvalidMessageErrCode, "")
return fmt.Errorf("bad ownership voucher header from TO2.ProveOVHdr: %w", err)
}
// Verify that the owner service corresponds to the most recent device
// initialization performed by checking that the voucher header has a GUID
// and/or manufacturer key corresponding to the stored device credentials.
if err := ov.VerifyManufacturerKey(c.Cred.PublicKeyHash); err != nil {
captureErr(ctx, protocol.InvalidMessageErrCode, "")
return fmt.Errorf("bad ownership voucher header from TO2.ProveOVHdr: manufacturer key: %w", err)
}
// Verify each entry in the voucher's list by performing iterative
// signature and hash (header and GUID/devInfo) checks.
if err := ov.VerifyEntries(); err != nil {
captureErr(ctx, protocol.InvalidMessageErrCode, "")
return fmt.Errorf("bad ownership voucher entries from TO2.ProveOVHdr: %w", err)
}
// Ensure that the voucher entry chain ends with given owner key.
//
// Note that this check is REQUIRED in this case, because the the owner public
// key from the ProveOVHdr message's unprotected headers is used to
// validate its COSE signature. If the public key were not to match the
// last entry of the voucher, then it would not be known that ProveOVHdr
// was signed by the intended owner service.
ownerPub := ov.Header.Val.ManufacturerKey
if len(ov.Entries) > 0 {
ownerPub = ov.Entries[len(ov.Entries)-1].Payload.Val.PublicKey
}
expectedOwnerPub, err := ownerPub.Public()
if err != nil {
return fmt.Errorf("error parsing last public key of ownership voucher: %w", err)
}
if !info.PublicKeyToValidate.(interface{ Equal(crypto.PublicKey) bool }).Equal(expectedOwnerPub) {
captureErr(ctx, protocol.InvalidMessageErrCode, "")
return fmt.Errorf("owner public key did not match last entry in ownership voucher")
}
// If no to1d blob was given, then immmediately return. This will be the
// case when RV bypass was used.
if to1d == nil {
return nil
}
// If the TO1.RVRedirect signature does not verify, the Device must assume
// that a man in the middle is monitoring its traffic, and fail TO2
// immediately with an error code message.
if ok, err := to1d.Verify(expectedOwnerPub, nil, nil); err != nil {
captureErr(ctx, protocol.InvalidMessageErrCode, "")
return fmt.Errorf("error verifying to1d signature: %w", err)
} else if !ok {
captureErr(ctx, protocol.InvalidMessageErrCode, "")
return fmt.Errorf("%w: to1d signature verification failed", ErrCryptoVerifyFailed)
}
return nil
}
type helloDeviceMsg struct {
MaxDeviceMessageSize uint16
GUID protocol.GUID
NonceTO2ProveOV protocol.Nonce
KexSuiteName kex.Suite
CipherSuite kex.CipherSuiteID
SigInfoA sigInfo
}
type ovhValidationContext struct {
OVH VoucherHeader
OVHHmac protocol.Hmac
NumVoucherEntries int
PublicKeyToValidate crypto.PublicKey
}
// HelloDevice(60) -> ProveOVHdr(61)
//
//nolint:gocyclo // This is very complex validation that is better understood linearly
func sendHelloDevice(ctx context.Context, transport Transport, c *TO2Config) (protocol.Nonce, *ovhValidationContext, kex.Session, error) {
// Generate a new nonce
var proveOVNonce protocol.Nonce
if _, err := rand.Read(proveOVNonce[:]); err != nil {
return protocol.Nonce{}, nil, nil, fmt.Errorf("error generating new nonce for TO2.HelloDevice request: %w", err)
}
// Select SigInfo using SHA384 when available
aSigInfo, err := sigInfoFor(c.Key, c.PSS)
if err != nil {
return protocol.Nonce{}, nil, nil, fmt.Errorf("error selecting aSigInfo for TO2.HelloDevice request: %w", err)
}
// Create a request structure
hello := helloDeviceMsg{
MaxDeviceMessageSize: 65535, // TODO: Make this configurable and match transport config
GUID: c.Cred.GUID,
NonceTO2ProveOV: proveOVNonce,
KexSuiteName: c.KeyExchange,
CipherSuite: c.CipherSuite,
SigInfoA: *aSigInfo,
}
// Make a request
typ, resp, err := transport.Send(ctx, protocol.TO2HelloDeviceMsgType, hello, nil)
if err != nil {
return protocol.Nonce{}, nil, nil, err
}
defer func() { _ = resp.Close() }()
// Parse response
var proveOVHdr cose.Sign1Tag[ovhProof, []byte]
switch typ {
case protocol.TO2ProveOVHdrMsgType:
captureMsgType(ctx, typ)
if err := cbor.NewDecoder(resp).Decode(&proveOVHdr); err != nil {
captureErr(ctx, protocol.MessageBodyErrCode, "")
return protocol.Nonce{}, nil, nil, fmt.Errorf("error parsing TO2.ProveOVHdr contents: %w", err)
}
defer clear(proveOVHdr.Payload.Val.KeyExchangeA)
case protocol.ErrorMsgType:
var errMsg protocol.ErrorMessage
if err := cbor.NewDecoder(resp).Decode(&errMsg); err != nil {
return protocol.Nonce{}, nil, nil, fmt.Errorf("error parsing error message contents of TO2.HelloDevice response: %w", err)
}
return protocol.Nonce{}, nil, nil, fmt.Errorf("error received from TO2.HelloDevice request: %w", errMsg)
default:
captureErr(ctx, protocol.MessageBodyErrCode, "")
return protocol.Nonce{}, nil, nil, fmt.Errorf("unexpected message type for response to TO2.HelloDevice: %d", typ)
}
// Validate the HelloDeviceHash
helloDeviceHash := proveOVHdr.Payload.Val.HelloDeviceHash.Algorithm.HashFunc().New()
if err := cbor.NewEncoder(helloDeviceHash).Encode(hello); err != nil {
return protocol.Nonce{}, nil, nil, fmt.Errorf("error hashing HelloDevice message to verify against TO2.ProveOVHdr payload's hash: %w", err)
}
if !bytes.Equal(proveOVHdr.Payload.Val.HelloDeviceHash.Value, helloDeviceHash.Sum(nil)) {
captureErr(ctx, protocol.InvalidMessageErrCode, "")
return protocol.Nonce{}, nil, nil, fmt.Errorf("hash of HelloDevice message TO2.ProveOVHdr did not match the message sent")
}
// Parse owner public key
var ownerPubKey protocol.PublicKey
if found, err := proveOVHdr.Unprotected.Parse(to2OwnerPubKeyClaim, &ownerPubKey); !found {
captureErr(ctx, protocol.InvalidMessageErrCode, "")
return protocol.Nonce{}, nil, nil, fmt.Errorf("owner pubkey unprotected header missing from TO2.ProveOVHdr response message")
} else if err != nil {
captureErr(ctx, protocol.InvalidMessageErrCode, "")
return protocol.Nonce{}, nil, nil, fmt.Errorf("owner pubkey unprotected header from TO2.ProveOVHdr could not be unmarshaled: %w", err)
}
// Validate response signature and nonce. While the payload signature
// verification is performed using the untrusted owner public key from the
// headers, this is acceptable, because the owner public key will be
// subsequently verified when the voucher entry chain is built and
// verified.
key, err := ownerPubKey.Public()
if err != nil {
captureErr(ctx, protocol.InvalidMessageErrCode, "")
return protocol.Nonce{}, nil, nil, fmt.Errorf("error parsing owner public key to verify TO2.ProveOVHdr payload signature: %w", err)
}
if ok, err := proveOVHdr.Verify(key, nil, nil); err != nil {
captureErr(ctx, protocol.InvalidMessageErrCode, "")
return protocol.Nonce{}, nil, nil, fmt.Errorf("error verifying TO2.ProveOVHdr payload signature: %w", err)
} else if !ok {
captureErr(ctx, protocol.InvalidMessageErrCode, "")
return protocol.Nonce{}, nil, nil, fmt.Errorf("%w: TO2.ProveOVHdr payload signature verification failed", ErrCryptoVerifyFailed)
}
if proveOVHdr.Payload.Val.NonceTO2ProveOV != proveOVNonce {
captureErr(ctx, protocol.InvalidMessageErrCode, "")
return protocol.Nonce{}, nil, nil, fmt.Errorf("nonce in TO2.ProveOVHdr did not match nonce sent in TO2.HelloDevice")
}
// proveOVHdr.Payload.Val.SigInfoB does not need to be validated. It is
// just a formality for ECDSA/RSA keys, left over from EPID support.
// TODO: Track proveOVHdr.Payload.Val.MaxOwnerMessageSize and later
// calculate MTU=min(MaxOwnerMessageSize, MaxOwnerServiceInfoSize) for
// better spec compliance, but honestly MaxOwnerMessageSize doesn't make
// that much sense. What can you do with it that you can't with service
// info max - fail early if TO2.ProveDevice is necessarily too large to be
// received?
// Parse nonce
var cuphNonce protocol.Nonce
if found, err := proveOVHdr.Unprotected.Parse(to2NonceClaim, &cuphNonce); !found {
captureErr(ctx, protocol.InvalidMessageErrCode, "")
return protocol.Nonce{}, nil, nil, fmt.Errorf("nonce unprotected header missing from TO2.ProveOVHdr response message")
} else if err != nil {
captureErr(ctx, protocol.InvalidMessageErrCode, "")
return protocol.Nonce{}, nil, nil, fmt.Errorf("nonce unprotected header from TO2.ProveOVHdr could not be unmarshaled: %w", err)
}
return cuphNonce,
&ovhValidationContext{
OVH: proveOVHdr.Payload.Val.OVH.Val,
OVHHmac: proveOVHdr.Payload.Val.OVHHmac,
NumVoucherEntries: int(proveOVHdr.Payload.Val.NumOVEntries),
PublicKeyToValidate: key,
},
// The key exchange parameter is zeroed and a copy used to initialize
// the key exchange session (which has its own Destroy method), because
// when using fdotest the transport does not actually marshal the
// server response. Therefore, after this function returns, proveOVHdr
// goes out of scope and its finalizer will run (at some point),
// zeroing the key exchange parameter and causing tests to be flaky.
c.KeyExchange.New(bytes.Clone(proveOVHdr.Payload.Val.KeyExchangeA), c.CipherSuite),
nil
}
type ovhProof struct {
OVH cbor.Bstr[VoucherHeader]
NumOVEntries uint8
OVHHmac protocol.Hmac
NonceTO2ProveOV protocol.Nonce
SigInfoB sigInfo
KeyExchangeA []byte
HelloDeviceHash protocol.Hash
MaxOwnerMessageSize uint16
}
// HelloDevice(60) -> ProveOVHdr(61)
//
// TODO: Handle MaxDeviceMessageSize
func (s *TO2Server) proveOVHdr(ctx context.Context, msg io.Reader) (*cose.Sign1Tag[ovhProof, []byte], error) { //nolint:gocyclo
// Parse request
var rawHello cbor.RawBytes
if err := cbor.NewDecoder(msg).Decode(&rawHello); err != nil {
return nil, fmt.Errorf("error decoding TO2.HelloDevice request: %w", err)
}
var hello helloDeviceMsg
if err := cbor.Unmarshal(rawHello, &hello); err != nil {
return nil, fmt.Errorf("error decoding TO2.HelloDevice request: %w", err)
}
// Retrieve voucher
if err := s.Session.SetGUID(ctx, hello.GUID); err != nil {
return nil, fmt.Errorf("error associating device GUID to proof session: %w", err)
}
ov, err := s.Vouchers.Voucher(ctx, hello.GUID)
if err != nil {
captureErr(ctx, protocol.ResourceNotFound, "")
return nil, fmt.Errorf("error retrieving voucher for device %x: %w", hello.GUID, err)
}
// It is legal for this tag to have a value of zero (0), but this is
// only useful in re-manufacturing situations, since the Rendezvous
// Server cannot verify (or accept) these Ownership Proxies.
numEntries := len(ov.Entries)
if numEntries > math.MaxUint8 {
return nil, fmt.Errorf("voucher for device %x has too many entries", hello.GUID)
}
// Assert that owner key matches voucher, in case the key was replaced or
// the voucher was not extended before being stored
keyType, opts, err := keyTypeFor(hello.SigInfoA.Type)
if err != nil {
return nil, fmt.Errorf("error getting key type from device sig info: %w", err)
}
ownerKey, ownerPublicKey, err := s.ownerKey(keyType, ov.Header.Val.ManufacturerKey.Encoding)
if err != nil {
return nil, err
}
expectedCUPHOwnerKey, err := ov.OwnerPublicKey()
if err != nil {
return nil, fmt.Errorf("error parsing owner public key from voucher: %w", err)
}
if !ownerKey.Public().(interface{ Equal(crypto.PublicKey) bool }).Equal(expectedCUPHOwnerKey) {
return nil, fmt.Errorf("owner key to be used for CUPHOwnerKey does not match voucher")
}
// Verify voucher using custom configuration option.
if s.VerifyVoucher != nil {
if err := s.VerifyVoucher(ctx, *ov); err != nil {
captureErr(ctx, protocol.ResourceNotFound, "")
return nil, fmt.Errorf("VerifyVoucher: %w", err)
}
} else if numEntries == 0 {
captureErr(ctx, protocol.ResourceNotFound, "")
return nil, fmt.Errorf("error retrieving voucher for device %x: %w", hello.GUID, ErrNotFound)
}
// Hash request
helloDeviceHash := protocol.Hash{Algorithm: ov.Header.Val.CertChainHash.Algorithm}
helloDeviceHasher := helloDeviceHash.Algorithm.HashFunc().New()
_, _ = helloDeviceHasher.Write(rawHello)
helloDeviceHash.Value = helloDeviceHasher.Sum(nil)
// Generate nonce for ProveDevice
var proveDeviceNonce protocol.Nonce
if _, err := rand.Read(proveDeviceNonce[:]); err != nil {
return nil, fmt.Errorf("error generating new nonce for TO2.ProveOVHdr response: %w", err)
}
if err := s.Session.SetProveDeviceNonce(ctx, proveDeviceNonce); err != nil {
return nil, fmt.Errorf("error storing nonce for later use in TO2.Done: %w", err)
}
// Begin key exchange
if !hello.KexSuiteName.Valid(hello.SigInfoA.Type, expectedCUPHOwnerKey) {
return nil, fmt.Errorf(
"key exchange %s is invalid for the device and owner attestation types",
hello.KexSuiteName,
)
}
if !kex.Available(hello.KexSuiteName, hello.CipherSuite) {
return nil, fmt.Errorf("unsupported key exchange/cipher suite")
}
sess := hello.KexSuiteName.New(nil, hello.CipherSuite)
rsaOwnerPublicKey, _ := expectedCUPHOwnerKey.(*rsa.PublicKey)
xA, err := sess.Parameter(rand.Reader, rsaOwnerPublicKey)
if err != nil {
return nil, fmt.Errorf("error generating client key exchange parameter: %w", err)
}
if err := s.Session.SetXSession(ctx, hello.KexSuiteName, sess); err != nil {
clear(xA)
return nil, fmt.Errorf("error storing key exchange session: %w", err)
}
// Send begin proof
if mfgKeyType := ov.Header.Val.ManufacturerKey.Type; keyType != mfgKeyType {
clear(xA)
return nil, fmt.Errorf("device sig info has key type %q, must be %q to match manufacturer key", keyType, mfgKeyType)
}
s1 := cose.Sign1[ovhProof, []byte]{
Header: cose.Header{
Unprotected: map[cose.Label]any{
to2NonceClaim: proveDeviceNonce,
to2OwnerPubKeyClaim: ownerPublicKey,
},
},
Payload: cbor.NewByteWrap(ovhProof{
OVH: ov.Header,
NumOVEntries: uint8(numEntries),
OVHHmac: ov.Hmac,
NonceTO2ProveOV: hello.NonceTO2ProveOV,
SigInfoB: hello.SigInfoA,
KeyExchangeA: xA,
HelloDeviceHash: helloDeviceHash,
MaxOwnerMessageSize: 65535, // TODO: Make this configurable and match handler config
}),
}
if err := s1.Sign(ownerKey, nil, nil, opts); err != nil {
clear(xA)
return nil, fmt.Errorf("error signing TO2.ProveOVHdr payload: %w", err)
}
// The lifetime of xA is until the transport has marshaled and sent the proof. Therefore, the
// best option for clearing the secret is to set a finalizer (unfortunately).
proof := s1.Tag()
runtime.SetFinalizer(proof, func(proof *cose.Sign1Tag[ovhProof, []byte]) {
clear(proof.Payload.Val.KeyExchangeA)
})
return proof, nil
}
func (s *TO2Server) ownerKey(keyType protocol.KeyType, keyEncoding protocol.KeyEncoding) (crypto.Signer, *protocol.PublicKey, error) {
key, chain, err := s.OwnerKeys.OwnerKey(keyType)
if errors.Is(err, ErrNotFound) {
return nil, nil, fmt.Errorf("owner key type %s not supported", keyType)
} else if err != nil {
return nil, nil, fmt.Errorf("error getting owner key [type=%s]: %w", keyType, err)
}
// Default to X509 key encoding if owner key does not have a certificate
// chain
if keyEncoding == protocol.X5ChainKeyEnc && len(chain) == 0 {
keyEncoding = protocol.X509KeyEnc
}
var pubkey *protocol.PublicKey
switch keyEncoding {
case protocol.X509KeyEnc, protocol.CoseKeyEnc:
switch keyType {
case protocol.Secp256r1KeyType, protocol.Secp384r1KeyType:
pubkey, err = protocol.NewPublicKey(keyType, key.Public().(*ecdsa.PublicKey), keyEncoding == protocol.CoseKeyEnc)
case protocol.Rsa2048RestrKeyType, protocol.RsaPkcsKeyType, protocol.RsaPssKeyType:
pubkey, err = protocol.NewPublicKey(keyType, key.Public().(*rsa.PublicKey), keyEncoding == protocol.CoseKeyEnc)
default:
return nil, nil, fmt.Errorf("unsupported key type: %s", keyType)
}
case protocol.X5ChainKeyEnc:
pubkey, err = protocol.NewPublicKey(keyType, chain, false)
default:
return nil, nil, fmt.Errorf("unsupported key encoding: %s", keyEncoding)
}
if err != nil {
return nil, nil, fmt.Errorf("error with owner public key: %w", err)
}
return key, pubkey, nil
}
// GetOVNextEntry(62) -> OVNextEntry(63)
func sendNextOVEntry(ctx context.Context, transport Transport, i int) (*cose.Sign1Tag[VoucherEntryPayload, []byte], error) {
// Define request structure
msg := struct {
OVEntryNum int
}{
OVEntryNum: i,
}
// Make request
typ, resp, err := transport.Send(ctx, protocol.TO2GetOVNextEntryMsgType, msg, nil)
if err != nil {
return nil, fmt.Errorf("error sending TO2.GetOVNextEntry: %w", err)
}
defer func() { _ = resp.Close() }()
// Parse response
switch typ {
case protocol.TO2OVNextEntryMsgType:
captureMsgType(ctx, typ)
var ovNextEntry ovEntry
if err := cbor.NewDecoder(resp).Decode(&ovNextEntry); err != nil {
captureErr(ctx, protocol.MessageBodyErrCode, "")
return nil, fmt.Errorf("error parsing TO2.OVNextEntry contents: %w", err)
}
if j := ovNextEntry.OVEntryNum; j != i {
return nil, fmt.Errorf("TO2.OVNextEntry message contained entry number %d, requested %d", j, i)
}
return &ovNextEntry.OVEntry, nil
case protocol.ErrorMsgType:
var errMsg protocol.ErrorMessage
if err := cbor.NewDecoder(resp).Decode(&errMsg); err != nil {
return nil, fmt.Errorf("error parsing error message contents of TO2.GetOVNextEntry response: %w", err)
}
return nil, fmt.Errorf("error received from TO2.GetOVNextEntry request: %w", errMsg)
default:
captureErr(ctx, protocol.MessageBodyErrCode, "")
return nil, fmt.Errorf("unexpected message type for response to TO2.GetOVNextEntry: %d", typ)
}
}
type ovEntry struct {
OVEntryNum int
OVEntry cose.Sign1Tag[VoucherEntryPayload, []byte]
}
// GetOVNextEntry(62) -> OVNextEntry(63)
func (s *TO2Server) ovNextEntry(ctx context.Context, msg io.Reader) (*ovEntry, error) {
// Parse request
var nextEntry struct {
OVEntryNum int
}
if err := cbor.NewDecoder(msg).Decode(&nextEntry); err != nil {
return nil, fmt.Errorf("error decoding TO2.GetOVNextEntry request: %w", err)
}
// Retrieve voucher
guid, err := s.Session.GUID(ctx)
if err != nil {
return nil, fmt.Errorf("error retrieving associated device GUID of proof session: %w", err)
}
ov, err := s.Vouchers.Voucher(ctx, guid)
if err != nil {
return nil, fmt.Errorf("error retrieving voucher for device %x: %w", guid, err)
}
// Return entry
if len(ov.Entries) < nextEntry.OVEntryNum {
return nil, fmt.Errorf("invalid ownership voucher entry index %d", nextEntry.OVEntryNum)
}
return &ovEntry{
OVEntryNum: nextEntry.OVEntryNum,
OVEntry: ov.Entries[nextEntry.OVEntryNum],
}, nil
}
// ProveDevice(64) -> SetupDevice(65)
func proveDevice(ctx context.Context, transport Transport, proveDeviceNonce protocol.Nonce, ownerPublicKey crypto.PublicKey, sess kex.Session, c *TO2Config) (protocol.Nonce, *VoucherHeader, error) {
// Generate a new nonce
var setupDeviceNonce protocol.Nonce
if _, err := rand.Read(setupDeviceNonce[:]); err != nil {
return protocol.Nonce{}, nil, fmt.Errorf("error generating new nonce for TO2.ProveDevice request: %w", err)
}
// Define request structure
rsaOwnerPublicKey, _ := ownerPublicKey.(*rsa.PublicKey)
xB, err := sess.Parameter(rand.Reader, rsaOwnerPublicKey)
if err != nil {
return protocol.Nonce{}, nil, fmt.Errorf("error generating key exchange session parameters: %w", err)
}
defer clear(xB)
token := cose.Sign1[eatoken, []byte]{
Header: cose.Header{
Unprotected: map[cose.Label]any{
eatUnprotectedNonceClaim: setupDeviceNonce,
},
},
Payload: cbor.NewByteWrap(newEAT(c.Cred.GUID, proveDeviceNonce, struct {
KeyExchangeB []byte
}{
KeyExchangeB: xB,
}, nil)),
}
opts, err := signOptsFor(c.Key, c.PSS)
if err != nil {
return protocol.Nonce{}, nil, fmt.Errorf("error determining signing options for TO2.ProveDevice: %w", err)
}
if err := token.Sign(c.Key, nil, nil, opts); err != nil {
return protocol.Nonce{}, nil, fmt.Errorf("error signing EAT payload for TO2.ProveDevice: %w", err)
}
msg := token.Tag()
// Make request
typ, resp, err := transport.Send(ctx, protocol.TO2ProveDeviceMsgType, msg, kex.DecryptOnly{Session: sess})
if err != nil {
return protocol.Nonce{}, nil, fmt.Errorf("error sending TO2.ProveDevice: %w", err)
}
defer func() { _ = resp.Close() }()
// Parse response
switch typ {
case protocol.TO2SetupDeviceMsgType:
captureMsgType(ctx, typ)
var setupDevice cose.Sign1Tag[deviceSetup, []byte]
if err := cbor.NewDecoder(resp).Decode(&setupDevice); err != nil {
captureErr(ctx, protocol.MessageBodyErrCode, "")
return protocol.Nonce{}, nil, fmt.Errorf("error parsing TO2.SetupDevice contents: %w", err)
}
if setupDevice.Payload.Val.NonceTO2SetupDv != setupDeviceNonce {
captureErr(ctx, protocol.InvalidMessageErrCode, "")
return protocol.Nonce{}, nil, fmt.Errorf("nonce in TO2.SetupDevice did not match nonce sent in TO2.ProveDevice")
}
replacementOVH := &VoucherHeader{
GUID: setupDevice.Payload.Val.GUID,
RvInfo: setupDevice.Payload.Val.RendezvousInfo,
ManufacturerKey: setupDevice.Payload.Val.Owner2Key,
}
if credReuse, err := reuseCredentials(ctx, replacementOVH, ownerPublicKey, c); err != nil || credReuse {
return setupDeviceNonce, nil, err
}
return setupDeviceNonce, replacementOVH, nil
case protocol.ErrorMsgType:
var errMsg protocol.ErrorMessage
if err := cbor.NewDecoder(resp).Decode(&errMsg); err != nil {
return protocol.Nonce{}, nil, fmt.Errorf("error parsing error message contents of TO2.ProveDevice response: %w", err)
}
return protocol.Nonce{}, nil, fmt.Errorf("error received from TO2.ProveDevice request: %w", errMsg)
default:
captureErr(ctx, protocol.MessageBodyErrCode, "")
return protocol.Nonce{}, nil, fmt.Errorf("unexpected message type for response to TO2.ProveDevice: %d", typ)
}
}
func reuseCredentials(ctx context.Context, replacementOVH *VoucherHeader, ownerPublicKey crypto.PublicKey, c *TO2Config) (bool, error) {
replacementOwnerPublicKey, err := replacementOVH.ManufacturerKey.Public()
if err != nil {
captureErr(ctx, protocol.InvalidMessageErrCode, "")
return false, fmt.Errorf("owner key in TO2.SetupDevice could not be parsed: %w", err)
}
if replacementOVH.GUID != c.Cred.GUID ||
!reflect.DeepEqual(replacementOVH.RvInfo, c.Cred.RvInfo) ||
!replacementOwnerPublicKey.(interface{ Equal(crypto.PublicKey) bool }).Equal(ownerPublicKey) {
return false, nil
}
if !c.AllowCredentialReuse {
captureErr(ctx, protocol.CredReuseErrCode, "")
return false, fmt.Errorf("credential reuse is not enabled")
}
return true, nil
}
type deviceSetup struct {
RendezvousInfo [][]protocol.RvInstruction // RendezvousInfo replacement
GUID protocol.GUID // GUID replacement
NonceTO2SetupDv protocol.Nonce // proves freshness of signature
Owner2Key protocol.PublicKey // Replacement for Owner key
}
// ProveDevice(64) -> SetupDevice(65)
//
//nolint:gocyclo // This is very complex validation that is better understood linearly
func (s *TO2Server) setupDevice(ctx context.Context, msg io.Reader) (*cose.Sign1Tag[deviceSetup, []byte], error) {
// Decode a fully-parsed and raw COSE Sign1. The latter is used for
// verifying in a more lenient way, as it doesn't require deterministic
// encoding of CBOR (even though FDO requires this).
var proof cose.Sign1Tag[cbor.RawBytes, []byte]
if err := cbor.NewDecoder(msg).Decode(&proof); err != nil {
return nil, fmt.Errorf("error decoding TO2.ProveDevice request: %w", err)
}
var eat eatoken
if err := cbor.Unmarshal([]byte(proof.Payload.Val), &eat); err != nil {
return nil, fmt.Errorf("error decoding TO2.ProveDevice request: %w", err)
}
// Parse and store SetupDevice nonce
var setupDeviceNonce protocol.Nonce
if ok, err := proof.Unprotected.Parse(eatUnprotectedNonceClaim, &setupDeviceNonce); err != nil {
return nil, fmt.Errorf("error parsing SetupDevice nonce from TO2.ProveDevice request unprotected header: %w", err)
} else if !ok {
return nil, fmt.Errorf("TO2.ProveDevice request missing SetupDevice nonce in unprotected headers")
}
if err := s.Session.SetSetupDeviceNonce(ctx, setupDeviceNonce); err != nil {
return nil, fmt.Errorf("error storing SetupDevice nonce from TO2.ProveDevice request: %w", err)
}
// Retrieve voucher
guid, err := s.Session.GUID(ctx)
if err != nil {
return nil, fmt.Errorf("error retrieving associated device GUID of proof session: %w", err)
}
ov, err := s.Vouchers.Voucher(ctx, guid)
if err != nil {
return nil, fmt.Errorf("error retrieving voucher for device %x: %w", guid, err)
}
// Verify request signature based on device certificate chain in voucher
devicePublicKey, err := ov.DevicePublicKey()
if err != nil {
return nil, fmt.Errorf("error parsing device public key from ownership voucher: %w", err)
}
if ok, err := proof.Verify(devicePublicKey, nil, nil); err != nil {
return nil, fmt.Errorf("error verifying signature of device EAT: %w", err)
} else if !ok {
return nil, fmt.Errorf("device EAT verification failed")
}
// Validate EAT contents
proveDeviceNonce, err := s.Session.ProveDeviceNonce(ctx)
if err != nil {
return nil, fmt.Errorf("error retrieving ProveDevice nonce for session: %w", err)
}
nonceClaim, ok := eat[eatNonceClaim].([]byte)
if !ok {
return nil, fmt.Errorf("missing nonce claim from EAT")
}
if !bytes.Equal(nonceClaim, proveDeviceNonce[:]) {
return nil, fmt.Errorf("nonce claim from EAT does not match ProveDevice nonce")
}
ueidClaim, ok := eat[eatUeidClaim].([]byte)
if !ok {
return nil, fmt.Errorf("missing UEID claim from EAT")
}
if !bytes.Equal(ueidClaim, append([]byte{eatRandUeid}, guid[:]...)) {
return nil, fmt.Errorf("claim of UEID in EAT does not match the device GUID")
}
fdoClaim, ok := eat[eatFdoClaim].([]any)
if !ok || len(fdoClaim) != 1 {
return nil, fmt.Errorf("missing FDO claim from EAT")
}
// Complete key exchange using EAT FDO claim
xB, ok := fdoClaim[0].([]byte)
if !ok {
return nil, fmt.Errorf("invalid EAT FDO claim: expected one item of type []byte")
}
suite, sess, err := s.Session.XSession(ctx)
if err != nil {
return nil, fmt.Errorf("error getting associated key exchange session: %w", err)
}
defer sess.Destroy()
keyType := ov.Header.Val.ManufacturerKey.Type
ownerKey, ownerPublicKey, err := s.ownerKey(keyType, ov.Header.Val.ManufacturerKey.Encoding)
if err != nil {
return nil, err
}
rsaOwnerPrivateKey, _ := ownerKey.(*rsa.PrivateKey)
if err := sess.SetParameter(xB, rsaOwnerPrivateKey); err != nil {
return nil, fmt.Errorf("error completing key exchange: %w", err)
}
if err := s.Session.SetXSession(ctx, suite, sess); err != nil {
return nil, fmt.Errorf("error updating associated key exchange session: %w", err)
}
// Get replacement GUID and rendezvous directives
var replacementGUID protocol.GUID
var replacementRvInfo [][]protocol.RvInstruction
if s.ReuseCredential != nil && s.ReuseCredential(ctx, *ov) {
replacementGUID = ov.Header.Val.GUID
replacementRvInfo = ov.Header.Val.RvInfo
} else {
if _, err := rand.Read(replacementGUID[:]); err != nil {
return nil, fmt.Errorf("error generating replacement GUID for device: %w", err)
}
if err := s.Session.SetReplacementGUID(ctx, replacementGUID); err != nil {
return nil, fmt.Errorf("error storing replacement GUID for device: %w", err)
}
if replacementRvInfo, err = s.RvInfo(ctx, *ov); err != nil {
return nil, fmt.Errorf("error determining rendezvous info for device: %w", err)
}
if err := s.Session.SetRvInfo(ctx, replacementRvInfo); err != nil {
return nil, fmt.Errorf("error storing rendezvous info for device: %w", err)
}
}