-
Notifications
You must be signed in to change notification settings - Fork 165
Expand file tree
/
Copy pathFidoMetadataDownloader.java
More file actions
1324 lines (1227 loc) · 56.2 KB
/
FidoMetadataDownloader.java
File metadata and controls
1324 lines (1227 loc) · 56.2 KB
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
// Copyright (c) 2015-2021, Yubico AB
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package com.yubico.fido.metadata;
import com.fasterxml.jackson.core.Base64Variants;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yubico.fido.metadata.FidoMetadataDownloaderException.Reason;
import com.yubico.internal.util.BinaryUtil;
import com.yubico.internal.util.CertificateParser;
import com.yubico.internal.util.OptionalUtil;
import com.yubico.webauthn.data.ByteArray;
import com.yubico.webauthn.data.exception.Base64UrlException;
import com.yubico.webauthn.data.exception.HexException;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.security.DigestException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Signature;
import java.security.SignatureException;
import java.security.cert.CRL;
import java.security.cert.CRLException;
import java.security.cert.CertPath;
import java.security.cert.CertPathValidator;
import java.security.cert.CertPathValidatorException;
import java.security.cert.CertStore;
import java.security.cert.CertStoreParameters;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.CollectionCertStoreParameters;
import java.security.cert.PKIXParameters;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Scanner;
import java.util.Set;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
/**
* Utility for downloading, caching and verifying Fido Metadata Service BLOBs and associated
* certificates.
*
* <p>This class is NOT THREAD SAFE since it reads and writes caches. However, it has no internal
* mutable state, so instances MAY be reused in single-threaded or externally synchronized contexts.
* See also the {@link #loadCachedBlob()} and {@link #refreshBlob()} methods.
*
* <p>Use the {@link #builder() builder} to configure settings, then use the {@link
* #loadCachedBlob()} and {@link #refreshBlob()} methods to load the metadata BLOB.
*/
@Slf4j
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public final class FidoMetadataDownloader {
@NonNull private final Set<String> expectedLegalHeaders;
private final X509Certificate trustRootCertificate;
private final URL trustRootUrl;
private final Set<ByteArray> trustRootSha256;
private final File trustRootCacheFile;
private final Supplier<Optional<ByteArray>> trustRootCacheSupplier;
private final Consumer<ByteArray> trustRootCacheConsumer;
private final String blobJwt;
private final URL blobUrl;
private final File blobCacheFile;
private final Supplier<Optional<ByteArray>> blobCacheSupplier;
private final Consumer<ByteArray> blobCacheConsumer;
private final CertStore certStore;
@NonNull private final Clock clock;
private final KeyStore httpsTrustStore;
private final boolean verifyDownloadsOnly;
/** For overriding JSON mapper settings in tests. */
private final Supplier<ObjectMapper> makeHeaderJsonMapper;
/** For overriding JSON mapper settings in tests. */
private final Supplier<ObjectMapper> makePayloadJsonMapper;
/**
* Begin configuring a {@link FidoMetadataDownloader} instance. See the {@link
* FidoMetadataDownloaderBuilder.Step1 Step1} type.
*
* @see FidoMetadataDownloaderBuilder.Step1
*/
public static FidoMetadataDownloaderBuilder.Step1 builder() {
return new FidoMetadataDownloaderBuilder.Step1();
}
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public static class FidoMetadataDownloaderBuilder {
@NonNull private final Set<String> expectedLegalHeaders;
private final X509Certificate trustRootCertificate;
private final URL trustRootUrl;
private final Set<ByteArray> trustRootSha256;
private final File trustRootCacheFile;
private final Supplier<Optional<ByteArray>> trustRootCacheSupplier;
private final Consumer<ByteArray> trustRootCacheConsumer;
private final String blobJwt;
private final URL blobUrl;
private final File blobCacheFile;
private final Supplier<Optional<ByteArray>> blobCacheSupplier;
private final Consumer<ByteArray> blobCacheConsumer;
private CertStore certStore = null;
@NonNull private Clock clock = Clock.systemUTC();
private KeyStore httpsTrustStore = null;
private boolean verifyDownloadsOnly = false;
private Supplier<ObjectMapper> makeHeaderJsonMapper =
FidoMetadataDownloader::defaultHeaderJsonMapper;
private Supplier<ObjectMapper> makePayloadJsonMapper =
FidoMetadataDownloader::defaultPayloadJsonMapper;
public FidoMetadataDownloader build() {
return new FidoMetadataDownloader(
expectedLegalHeaders,
trustRootCertificate,
trustRootUrl,
trustRootSha256,
trustRootCacheFile,
trustRootCacheSupplier,
trustRootCacheConsumer,
blobJwt,
blobUrl,
blobCacheFile,
blobCacheSupplier,
blobCacheConsumer,
certStore,
clock,
httpsTrustStore,
verifyDownloadsOnly,
makeHeaderJsonMapper,
makePayloadJsonMapper);
}
/**
* Step 1: Set the legal header to expect from the FIDO Metadata Service.
*
* <p>By using the FIDO Metadata Service, you will be subject to its terms of service. This step
* serves two purposes:
*
* <ol>
* <li>To remind you and any code reviewers that you need to read those terms of service
* before using this feature.
* <li>To help you detect if the legal header changes, so you can take appropriate action.
* </ol>
*
* <p>See {@link Step1#expectLegalHeader(String...)}.
*
* @see Step1#expectLegalHeader(String...)
*/
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public static class Step1 {
/**
* Set legal headers expected in the metadata BLOB.
*
* <p>By using the FIDO Metadata Service, you will be subject to its terms of service. This
* builder step serves two purposes:
*
* <ol>
* <li>To remind you and any code reviewers that you need to read those terms of service
* before using this feature.
* <li>To help you detect if the legal header changes, so you can take appropriate action.
* </ol>
*
* <p>If the legal header in the downloaded BLOB does not equal any of the <code>
* expectedLegalHeaders</code>, an {@link UnexpectedLegalHeader} exception will be thrown in
* the finalizing builder step.
*
* <p>Note that this library makes no guarantee that a change to the FIDO Metadata Service
* terms of service will also cause a change to the legal header in the BLOB.
*
* <p>At the time of this library release, the current legal header is <code>
* "Retrieval and use of this BLOB indicates acceptance of the appropriate agreement located at https://fidoalliance.org/metadata/metadata-legal-terms/"
* </code>.
*
* @param expectedLegalHeaders the set of BLOB legal headers you expect in the metadata BLOB
* payload.
*/
public Step2 expectLegalHeader(@NonNull String... expectedLegalHeaders) {
return new Step2(Stream.of(expectedLegalHeaders).collect(Collectors.toSet()));
}
}
/**
* Step 2: Configure how to retrieve the FIDO Metadata Service trust root certificate when
* necessary.
*
* <p>This step offers three mutually exclusive options:
*
* <ol>
* <li>Use the default download URL and certificate hash. This is the main intended use case.
* See {@link #useDefaultTrustRoot()}.
* <li>Use a custom download URL and certificate hash. This is for future-proofing in case the
* trust root certificate changes and there is no new release of this library. See {@link
* #downloadTrustRoot(URL, Set)}.
* <li>Use a pre-retrieved trust root certificate. It is up to you to perform any integrity
* checks and cache it as desired. See {@link #useTrustRoot(X509Certificate)}.
* </ol>
*/
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public static class Step2 {
@NonNull private final Set<String> expectedLegalHeaders;
/**
* Download the trust root certificate from a hard-coded URL and verify it against a
* hard-coded SHA-256 hash.
*
* <p>This is an alias of:
*
* <pre>
* downloadTrustRoot(
* new URL("https://secure.globalsign.com/cacert/root-r3.crt"),
* Collections.singleton(ByteArray.fromHex("cbb522d7b7f127ad6a0113865bdf1cd4102e7d0759af635a7cf4720dc963c53b"))
* )
* </pre>
*
* This is the current FIDO Metadata Service trust root certificate at the time of this
* library release.
*
* @see #downloadTrustRoot(URL, Set)
*/
public Step3 useDefaultTrustRoot() {
try {
return downloadTrustRoot(
new URL("https://secure.globalsign.com/cacert/root-r3.crt"),
Collections.singleton(
ByteArray.fromHex(
"cbb522d7b7f127ad6a0113865bdf1cd4102e7d0759af635a7cf4720dc963c53b")));
} catch (MalformedURLException e) {
throw new RuntimeException(
"Bad hard-coded trust root certificate URL. Please file a bug report.", e);
} catch (HexException e) {
throw new RuntimeException(
"Bad hard-coded trust root certificate hash. Please file a bug report.", e);
}
}
/**
* Download the trust root certificate from the given HTTPS <code>url</code> and verify its
* SHA-256 hash against <code>acceptedCertSha256</code>.
*
* <p>The certificate will be downloaded if it does not exist in the cache, or if the cached
* certificate is not currently valid.
*
* <p>If the cert is downloaded, it is also written to the cache {@link File} or {@link
* Consumer} configured in the {@link Step3 next step}.
*
* @param url the HTTP URL to download. It MUST use the <code>https:</code> scheme.
* @param acceptedCertSha256 a set of SHA-256 hashes to verify the downloaded certificate
* against. The downloaded certificate MUST match at least one of these hashes.
* @throws IllegalArgumentException if <code>url</code> is not a HTTPS URL.
*/
public Step3 downloadTrustRoot(@NonNull URL url, @NonNull Set<ByteArray> acceptedCertSha256) {
if (!"https".equals(url.getProtocol())) {
throw new IllegalArgumentException("Trust certificate download URL must be a HTTPS URL.");
}
return new Step3(this, null, url, acceptedCertSha256);
}
/**
* Use the given trust root certificate. It is the caller's responsibility to perform any
* integrity checks and/or caching logic.
*
* @param trustRootCertificate the certificate to use as the FIDO Metadata Service trust root.
*/
public Step4 useTrustRoot(@NonNull X509Certificate trustRootCertificate) {
return new Step4(new Step3(this, trustRootCertificate, null, null), null, null, null);
}
}
/**
* Step 3: Configure how to cache the trust root certificate.
*
* <p>This step offers two mutually exclusive options:
*
* <ol>
* <li>Cache the trust root certificate in a {@link File}. See {@link
* Step3#useTrustRootCacheFile(File)}.
* <li>Cache the trust root certificate using a {@link Supplier} to read the cache and a
* {@link Consumer} to write the cache. See {@link Step3#useTrustRootCache(Supplier,
* Consumer)}.
* </ol>
*/
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public static class Step3 {
@NonNull private final Step2 step2;
private final X509Certificate trustRootCertificate;
private final URL trustRootUrl;
private final Set<ByteArray> trustRootSha256;
/**
* Cache the trust root certificate in the file <code>cacheFile</code>.
*
* <p>If <code>cacheFile</code> exists, is a normal file, is readable, matches one of the
* SHA-256 hashes configured in the previous step, and contains a currently valid X.509
* certificate, then it will be used as the trust root for the FIDO Metadata Service blob.
*
* <p>Otherwise, the trust root certificate will be downloaded and written to this file.
*/
public Step4 useTrustRootCacheFile(@NonNull File cacheFile) {
return new Step4(this, cacheFile, null, null);
}
/**
* Cache the trust root certificate using a {@link Supplier} to read the cache, and using a
* {@link Consumer} to write the cache.
*
* <p>If <code>getCachedTrustRootCert</code> returns non-empty, the value matches one of the
* SHA-256 hashes configured in the previous step, and is a currently valid X.509 certificate,
* then it will be used as the trust root for the FIDO Metadata Service blob.
*
* <p>Otherwise, the trust root certificate will be downloaded and written to <code>
* writeCachedTrustRootCert</code>.
*
* @param getCachedTrustRootCert a {@link Supplier} that fetches the cached trust root
* certificate if it exists. MUST NOT return <code>null</code>. The returned value, if
* present, MUST be the trust root certificate in X.509 DER format.
* @param writeCachedTrustRootCert a {@link Consumer} that accepts the trust root certificate
* in X.509 DER format and writes it to the cache. Its argument will never be <code>null
* </code>.
*/
public Step4 useTrustRootCache(
@NonNull Supplier<Optional<ByteArray>> getCachedTrustRootCert,
@NonNull Consumer<ByteArray> writeCachedTrustRootCert) {
return new Step4(this, null, getCachedTrustRootCert, writeCachedTrustRootCert);
}
}
/**
* Step 4: Configure how to fetch the FIDO Metadata Service metadata BLOB.
*
* <p>This step offers three mutually exclusive options:
*
* <ol>
* <li>Use the default download URL. This is the main intended use case. See {@link
* #useDefaultBlob()}.
* <li>Use a custom download URL. This is for future-proofing in case the BLOB download URL
* changes and there is no new release of this library. See {@link #downloadBlob(URL)}.
* <li>Use a pre-retrieved BLOB. The signature will still be verified, but it is up to you to
* renew it when appropriate and perform any caching as desired. See {@link
* #useBlob(String)}.
* </ol>
*/
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public static class Step4 {
@NonNull private final Step3 step3;
private final File trustRootCacheFile;
private final Supplier<Optional<ByteArray>> trustRootCacheSupplier;
private final Consumer<ByteArray> trustRootCacheConsumer;
/**
* Download the metadata BLOB from a hard-coded URL.
*
* <p>This is an alias of <code>downloadBlob(new URL("https://mds.fidoalliance.org/"))</code>.
*
* <p>This is the current FIDO Metadata Service BLOB download URL at the time of this library
* release.
*
* @see #downloadBlob(URL)
*/
public Step5 useDefaultBlob() {
try {
return downloadBlob(new URL("https://mds.fidoalliance.org/"));
} catch (MalformedURLException e) {
throw new RuntimeException(
"Bad hard-coded trust root certificate URL. Please file a bug report.", e);
}
}
/**
* Download the metadata BLOB from the given HTTPS <code>url</code>.
*
* <p>The BLOB will be downloaded if it does not exist in the cache, or if the <code>
* nextUpdate</code> property of the cached BLOB is the current date or earlier.
*
* <p>If the BLOB is downloaded, it is also written to the cache {@link File} or {@link
* Consumer} configured in the next step.
*
* @param url the HTTP URL to download. It MUST use the <code>https:</code> scheme.
*/
public Step5 downloadBlob(@NonNull URL url) {
return new Step5(this, null, url);
}
/**
* Use the given metadata BLOB; never download it.
*
* <p>The blob signature and trust chain will still be verified, but it is the caller's
* responsibility to renew the metadata BLOB according to the <a
* href="https://fidoalliance.org/specs/mds/fido-metadata-service-v3.0-ps-20210518.html#metadata-blob-object-processing-rules">FIDO
* Metadata Service specification</a>.
*
* @param blobJwt the Metadata BLOB in JWT format as defined in <a
* href="https://fidoalliance.org/specs/mds/fido-metadata-service-v3.0-ps-20210518.html#metadata-blob">FIDO
* Metadata Service §3.1.7. Metadata BLOB</a>. The byte array MUST NOT be Base64-decoded.
* @see <a
* href="https://fidoalliance.org/specs/mds/fido-metadata-service-v3.0-ps-20210518.html#metadata-blob">FIDO
* Metadata Service §3.1.7. Metadata BLOB</a>
* @see <a
* href="https://fidoalliance.org/specs/mds/fido-metadata-service-v3.0-ps-20210518.html#metadata-blob-object-processing-rules">FIDO
* Metadata Service §3.2. Metadata BLOB object processing rules</a>
*/
public FidoMetadataDownloaderBuilder useBlob(@NonNull String blobJwt) {
return finishRequiredSteps(new Step5(this, blobJwt, null), null, null, null);
}
}
/**
* Step 5: Configure how to cache the metadata BLOB.
*
* <p>This step offers two mutually exclusive options:
*
* <ol>
* <li>Cache the metadata BLOB in a {@link File}. See {@link Step5#useBlobCacheFile(File)}.
* <li>Cache the metadata BLOB using a {@link Supplier} to read the cache and a {@link
* Consumer} to write the cache. See {@link Step5#useBlobCache(Supplier, Consumer)}.
* </ol>
*/
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public static class Step5 {
@NonNull private final Step4 step4;
private final String blobJwt;
private final URL blobUrl;
/**
* Cache metadata BLOB in the file <code>cacheFile</code>.
*
* <p>If <code>cacheFile</code> exists, is a normal file, is readable, and is not out of date,
* then it will be used as the FIDO Metadata Service BLOB.
*
* <p>Otherwise, the metadata BLOB will be downloaded and written to this file.
*
* @param cacheFile a {@link File} which may or may not exist. If it exists, it MUST contain
* the metadata BLOB in JWS compact serialization format <a
* href="https://datatracker.ietf.org/doc/html/rfc7515#section-3.1">[RFC7515]</a>.
*/
public FidoMetadataDownloaderBuilder useBlobCacheFile(@NonNull File cacheFile) {
return finishRequiredSteps(this, cacheFile, null, null);
}
/**
* Cache the metadata BLOB using a {@link Supplier} to read the cache, and using a {@link
* Consumer} to write the cache.
*
* <p>If <code>getCachedBlob</code> returns non-empty and the content is not out of date, then
* it will be used as the FIDO Metadata Service BLOB.
*
* <p>Otherwise, the metadata BLOB will be downloaded and written to <code>writeCachedBlob
* </code>.
*
* @param getCachedBlob a {@link Supplier} that fetches the cached metadata BLOB if it exists.
* MUST NOT return <code>null</code>. The returned value, if present, MUST be in JWS
* compact serialization format <a
* href="https://datatracker.ietf.org/doc/html/rfc7515#section-3.1">[RFC7515]</a>.
* @param writeCachedBlob a {@link Consumer} that accepts the metadata BLOB in JWS compact
* serialization format <a
* href="https://datatracker.ietf.org/doc/html/rfc7515#section-3.1">[RFC7515]</a> and
* writes it to the cache. Its argument will never be <code>null</code>.
*/
public FidoMetadataDownloaderBuilder useBlobCache(
@NonNull Supplier<Optional<ByteArray>> getCachedBlob,
@NonNull Consumer<ByteArray> writeCachedBlob) {
return finishRequiredSteps(this, null, getCachedBlob, writeCachedBlob);
}
}
private static FidoMetadataDownloaderBuilder finishRequiredSteps(
FidoMetadataDownloaderBuilder.Step5 step5,
File blobCacheFile,
Supplier<Optional<ByteArray>> blobCacheSupplier,
Consumer<ByteArray> blobCacheConsumer) {
return new FidoMetadataDownloaderBuilder(
step5.step4.step3.step2.expectedLegalHeaders,
step5.step4.step3.trustRootCertificate,
step5.step4.step3.trustRootUrl,
step5.step4.step3.trustRootSha256,
step5.step4.trustRootCacheFile,
step5.step4.trustRootCacheSupplier,
step5.step4.trustRootCacheConsumer,
step5.blobJwt,
step5.blobUrl,
blobCacheFile,
blobCacheSupplier,
blobCacheConsumer);
}
/**
* Use <code>clock</code> as the source of the current time for some application-level logic.
*
* <p>This is primarily intended for testing.
*
* <p>The default is {@link Clock#systemUTC()}.
*
* @param clock a {@link Clock} which the finished {@link FidoMetadataDownloader} will use to
* tell the time.
*/
public FidoMetadataDownloaderBuilder clock(@NonNull Clock clock) {
this.clock = clock;
return this;
}
/**
* Use the provided CRLs.
*
* <p>CRLs will also be downloaded from distribution points for any certificates with a
* CRLDistributionPoints extension, if the extension can be successfully interpreted. A warning
* message will be logged CRLDistributionPoints parsing fails.
*
* @throws InvalidAlgorithmParameterException if {@link CertStore#getInstance(String,
* CertStoreParameters)} does.
* @throws NoSuchAlgorithmException if a <code>"Collection"</code> type {@link CertStore}
* provider is not available.
* @see #useCrls(CertStore)
*/
public FidoMetadataDownloaderBuilder useCrls(@NonNull Collection<CRL> crls)
throws InvalidAlgorithmParameterException, NoSuchAlgorithmException {
return useCrls(CertStore.getInstance("Collection", new CollectionCertStoreParameters(crls)));
}
/**
* Use CRLs in the provided {@link CertStore}.
*
* <p>CRLs will also be downloaded from distribution points for any certificates with a
* CRLDistributionPoints extension, if the extension can be successfully interpreted. A warning
* message will be logged CRLDistributionPoints parsing fails.
*
* @see #useCrls(Collection)
*/
public FidoMetadataDownloaderBuilder useCrls(CertStore certStore) {
this.certStore = certStore;
return this;
}
/**
* Use the provided {@link X509Certificate}s as trust roots for HTTPS downloads.
*
* <p>This is primarily useful when setting {@link Step2#downloadTrustRoot(URL, Set)
* downloadTrustRoot} and/or {@link Step4#downloadBlob(URL) downloadBlob} to download from
* custom servers instead of the defaults.
*
* <p>If provided, these will be used for downloading
*
* <ul>
* <li>the trust root certificate for the BLOB signature chain, and
* <li>the metadata BLOB.
* </ul>
*
* If not set, the system default certificate store will be used.
*/
public FidoMetadataDownloaderBuilder trustHttpsCerts(@NonNull X509Certificate... certificates) {
final KeyStore trustStore;
try {
trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null);
} catch (KeyStoreException
| IOException
| NoSuchAlgorithmException
| CertificateException e) {
throw new RuntimeException(
"Failed to instantiate or initialize KeyStore. This should not be possible, please file a bug report.",
e);
}
for (X509Certificate cert : certificates) {
try {
trustStore.setCertificateEntry(UUID.randomUUID().toString(), cert);
} catch (KeyStoreException e) {
throw new RuntimeException(
"Failed to import HTTPS cert into KeyStore. This should not be possible, please file a bug report.",
e);
}
}
this.httpsTrustStore = trustStore;
return this;
}
/**
* If set to <code>true</code>, the BLOB signature will not be verified when loading the BLOB
* from cache or when explicitly set via {@link Step4#useBlob(String)}. This means that if a
* BLOB was successfully verified once and written to cache, that cached value will be
* implicitly trusted when loaded in the future.
*
* <p>If set to <code>false</code>, the BLOB signature will always be verified no matter where
* the BLOB came from. This means that a cached BLOB may become invalid if the BLOB certificate
* expires, even if the BLOB was successfully verified at the time it was downloaded.
*
* <p>The default setting is <code>false</code>.
*
* @param verifyDownloadsOnly <code>true</code> if the BLOB signature should be ignored when
* loading the BLOB from cache or when explicitly set via {@link Step4#useBlob(String)}.
*/
public FidoMetadataDownloaderBuilder verifyDownloadsOnly(final boolean verifyDownloadsOnly) {
this.verifyDownloadsOnly = verifyDownloadsOnly;
return this;
}
/** For internal testing use only. */
FidoMetadataDownloaderBuilder headerJsonMapper(
final Supplier<ObjectMapper> makeHeaderJsonMapper) {
this.makeHeaderJsonMapper = makeHeaderJsonMapper;
return this;
}
/** For internal testing use only. */
FidoMetadataDownloaderBuilder payloadJsonMapper(
final Supplier<ObjectMapper> makePayloadJsonMapper) {
this.makePayloadJsonMapper = makePayloadJsonMapper;
return this;
}
}
/**
* Load the metadata BLOB from cache, or download a fresh one if necessary.
*
* <p>This method is NOT THREAD SAFE since it reads and writes caches.
*
* <p>On each execution this will, in order:
*
* <ol>
* <li>Download the trust root certificate, if necessary: if the cache is empty, the cache fails
* to load, or the cached cert is not valid at the current time (as determined by the {@link
* FidoMetadataDownloaderBuilder#clock(Clock) clock} setting).
* <li>If downloaded, cache the trust root certificate using the configured {@link File} or
* {@link Consumer} (see {@link FidoMetadataDownloaderBuilder.Step3})
* <li>Download the metadata BLOB, if necessary: if the cache is empty, the cache fails to load,
* or the <code>"nextUpdate"</code> property in the cached BLOB is the current date (as
* determined by the {@link FidoMetadataDownloaderBuilder#clock(Clock) clock} setting) or
* earlier.
* <li>Check the <code>"no"</code> property of the downloaded BLOB, if any, and compare it with
* the <code>"no"</code> of the cached BLOB, if any. The one with a greater <code>"no"
* </code> overrides the other, even if its <code>"nextUpdate"</code> is in the past.
* <li>If a BLOB with a newer <code>"no"</code> was downloaded, verify that the value of its
* <code>"legalHeader"</code> appears in the configured {@link
* FidoMetadataDownloaderBuilder.Step1#expectLegalHeader(String...) expectLegalHeader}
* setting. If not, throw an {@link UnexpectedLegalHeader} exception containing the cached
* BLOB, if any, and the downloaded BLOB.
* <li>If a BLOB with a newer <code>"no"</code> was downloaded and had an expected <code>
* "legalHeader"</code>, cache the new BLOB using the configured {@link File} or {@link
* Consumer} (see {@link FidoMetadataDownloaderBuilder.Step5}).
* </ol>
*
* No internal mutable state is maintained between invocations of this method; each invocation
* will reload/rewrite caches, perform downloads and check the <code>"legalHeader"
* </code> as necessary. You may therefore reuse a {@link FidoMetadataDownloader} instance and,
* for example, call this method periodically to refresh the BLOB when appropriate. Each call will
* return a new {@link MetadataBLOB} instance; ones already returned will not be updated by
* subsequent calls.
*
* @return the successfully retrieved and validated metadata BLOB.
* @throws Base64UrlException if the explicitly configured or newly downloaded BLOB is not a
* well-formed JWT in compact serialization.
* @throws CertPathValidatorException if the explicitly configured or newly downloaded BLOB fails
* certificate path validation.
* @throws CertificateException if the trust root certificate was downloaded and passed the
* SHA-256 integrity check, but does not contain a currently valid X.509 DER certificate; or
* if the BLOB signing certificate chain fails to parse.
* @throws DigestException if the trust root certificate was downloaded but failed the SHA-256
* integrity check.
* @throws FidoMetadataDownloaderException if the explicitly configured or newly downloaded BLOB
* (if any) has a bad signature and there is no cached BLOB to fall back to.
* @throws IOException if any of the following fails: downloading the trust root certificate,
* downloading the BLOB, reading or writing any cache file (if any), or parsing the BLOB
* contents.
* @throws InvalidAlgorithmParameterException if certificate path validation fails.
* @throws InvalidKeyException if signature verification fails.
* @throws NoSuchAlgorithmException if signature verification fails, or if the SHA-256 algorithm
* or the <code>"Collection"</code> type {@link CertStore} is not available.
* @throws SignatureException if signature verification fails.
* @throws UnexpectedLegalHeader if the downloaded BLOB (if any) contains a <code>"legalHeader"
* </code> value not configured in {@link
* FidoMetadataDownloaderBuilder.Step1#expectLegalHeader(String...)
* expectLegalHeader(String...)} but is otherwise valid. The downloaded BLOB will not be
* written to cache in this case.
*/
public MetadataBLOB loadCachedBlob()
throws CertPathValidatorException,
InvalidAlgorithmParameterException,
Base64UrlException,
CertificateException,
IOException,
NoSuchAlgorithmException,
SignatureException,
InvalidKeyException,
UnexpectedLegalHeader,
DigestException,
FidoMetadataDownloaderException {
final X509Certificate trustRoot = retrieveTrustRootCert();
final Optional<MetadataBLOB> explicit = loadExplicitBlobOnly(trustRoot);
if (explicit.isPresent()) {
log.debug("Explicit BLOB is set - disregarding cache and download.");
return explicit.get();
}
final Optional<MetadataBLOB> cached = loadCachedBlobOnly(trustRoot);
if (cached.isPresent()) {
log.debug("Cached BLOB exists, checking expiry date...");
if (cached
.get()
.getPayload()
.getNextUpdate()
.atStartOfDay()
.atZone(clock.getZone())
.isAfter(clock.instant().atZone(clock.getZone()))) {
log.debug("Cached BLOB has not yet expired - using cached BLOB.");
return cached.get();
} else {
log.debug("Cached BLOB has expired.");
}
} else {
log.debug("Cached BLOB does not exist or is invalid.");
}
return refreshBlobInternal(trustRoot, cached).get();
}
/**
* Download and cache a fresh metadata BLOB, or read it from cache if the downloaded BLOB is not
* up to date.
*
* <p>This method is NOT THREAD SAFE since it reads and writes caches.
*
* <p>On each execution this will, in order:
*
* <ol>
* <li>Download the trust root certificate, if necessary: if the cache is empty, the cache fails
* to load, or the cached cert is not valid at the current time (as determined by the {@link
* FidoMetadataDownloaderBuilder#clock(Clock) clock} setting).
* <li>If downloaded, cache the trust root certificate using the configured {@link File} or
* {@link Consumer} (see {@link FidoMetadataDownloaderBuilder.Step3})
* <li>Download the metadata BLOB.
* <li>Check the <code>"no"</code> property of the downloaded BLOB and compare it with the
* <code>"no"</code> of the cached BLOB, if any. The one with a greater <code>"no"
* </code> overrides the other, even if its <code>"nextUpdate"</code> is in the past.
* <li>If the downloaded BLOB has a newer <code>"no"</code>, or if no BLOB was cached, verify
* that the value of the downloaded BLOB's <code>"legalHeader"</code> appears in the
* configured {@link FidoMetadataDownloaderBuilder.Step1#expectLegalHeader(String...)
* expectLegalHeader} setting. If not, throw an {@link UnexpectedLegalHeader} exception
* containing the cached BLOB, if any, and the downloaded BLOB.
* <li>If the downloaded BLOB has an expected <code>
* "legalHeader"</code>, cache it using the configured {@link File} or {@link Consumer} (see
* {@link FidoMetadataDownloaderBuilder.Step5}).
* </ol>
*
* No internal mutable state is maintained between invocations of this method; each invocation
* will reload/rewrite caches, perform downloads and check the <code>"legalHeader"
* </code> as necessary. You may therefore reuse a {@link FidoMetadataDownloader} instance and,
* for example, call this method periodically to refresh the BLOB. Each call will return a new
* {@link MetadataBLOB} instance; ones already returned will not be updated by subsequent calls.
*
* @return the successfully retrieved and validated metadata BLOB.
* @throws Base64UrlException if the explicitly configured or newly downloaded BLOB is not a
* well-formed JWT in compact serialization.
* @throws CertPathValidatorException if the explicitly configured or newly downloaded BLOB fails
* certificate path validation.
* @throws CertificateException if the trust root certificate was downloaded and passed the
* SHA-256 integrity check, but does not contain a currently valid X.509 DER certificate; or
* if the BLOB signing certificate chain fails to parse.
* @throws DigestException if the trust root certificate was downloaded but failed the SHA-256
* integrity check.
* @throws FidoMetadataDownloaderException if the explicitly configured or newly downloaded BLOB
* (if any) has a bad signature and there is no cached BLOB to fall back to.
* @throws IOException if any of the following fails: downloading the trust root certificate,
* downloading the BLOB, reading or writing any cache file (if any), or parsing the BLOB
* contents.
* @throws InvalidAlgorithmParameterException if certificate path validation fails.
* @throws InvalidKeyException if signature verification fails.
* @throws NoSuchAlgorithmException if signature verification fails, or if the SHA-256 algorithm
* or the <code>"Collection"</code> type {@link CertStore} is not available.
* @throws SignatureException if signature verification fails.
* @throws UnexpectedLegalHeader if the downloaded BLOB (if any) contains a <code>"legalHeader"
* </code> value not configured in {@link
* FidoMetadataDownloaderBuilder.Step1#expectLegalHeader(String...)
* expectLegalHeader(String...)} but is otherwise valid. The downloaded BLOB will not be
* written to cache in this case.
*/
public MetadataBLOB refreshBlob()
throws CertPathValidatorException,
InvalidAlgorithmParameterException,
Base64UrlException,
CertificateException,
IOException,
NoSuchAlgorithmException,
SignatureException,
InvalidKeyException,
UnexpectedLegalHeader,
DigestException,
FidoMetadataDownloaderException {
final X509Certificate trustRoot = retrieveTrustRootCert();
final Optional<MetadataBLOB> explicit = loadExplicitBlobOnly(trustRoot);
if (explicit.isPresent()) {
log.debug("Explicit BLOB is set - disregarding cache and download.");
return explicit.get();
}
final Optional<MetadataBLOB> cached = loadCachedBlobOnly(trustRoot);
if (cached.isPresent()) {
log.debug("Cached BLOB exists, proceeding to compare against fresh BLOB...");
} else {
log.debug("Cached BLOB does not exist or is invalid.");
}
return refreshBlobInternal(trustRoot, cached).get();
}
private Optional<MetadataBLOB> refreshBlobInternal(
@NonNull X509Certificate trustRoot, @NonNull Optional<MetadataBLOB> cached)
throws CertPathValidatorException,
InvalidAlgorithmParameterException,
Base64UrlException,
CertificateException,
IOException,
NoSuchAlgorithmException,
SignatureException,
InvalidKeyException,
UnexpectedLegalHeader,
FidoMetadataDownloaderException {
try {
log.debug("Attempting to download new BLOB...");
final ByteArray downloadedBytes = download(blobUrl);
final MetadataBLOB downloadedBlob = parseAndVerifyBlob(downloadedBytes, trustRoot);
log.debug("New BLOB downloaded.");
if (cached.isPresent()) {
log.debug("Cached BLOB exists - checking if new BLOB has a higher \"no\"...");
if (downloadedBlob.getPayload().getNo() <= cached.get().getPayload().getNo()) {
log.debug("New BLOB does not have a higher \"no\" - using cached BLOB instead.");
return cached;
}
log.debug("New BLOB has a higher \"no\" - proceeding with new BLOB.");
}
log.debug("Checking legalHeader in new BLOB...");
if (!expectedLegalHeaders.contains(downloadedBlob.getPayload().getLegalHeader())) {
throw new UnexpectedLegalHeader(cached.orElse(null), downloadedBlob);
}
log.debug("Writing new BLOB to cache...");
if (blobCacheFile != null) {
try (FileOutputStream f = new FileOutputStream(blobCacheFile)) {
f.write(downloadedBytes.getBytes());
}
}
if (blobCacheConsumer != null) {
blobCacheConsumer.accept(downloadedBytes);
}
return Optional.of(downloadedBlob);
} catch (FidoMetadataDownloaderException e) {
if (e.getReason() == Reason.BAD_SIGNATURE && cached.isPresent()) {
log.warn("New BLOB has bad signature - falling back to cached BLOB.");
return cached;
} else {
throw e;
}
} catch (Exception e) {
if (cached.isPresent()) {
log.warn("Failed to download new BLOB - falling back to cached BLOB.", e);
return cached;
} else {
throw e;
}
}
}
/**
* @throws CertificateException if the trust root certificate was downloaded and passed the
* SHA-256 integrity check, but does not contain a currently valid X.509 DER certificate.
* @throws DigestException if the trust root certificate was downloaded but failed the SHA-256
* integrity check.
* @throws IOException if the trust root certificate download failed, or if reading or writing the
* cache file (if any) failed.
* @throws NoSuchAlgorithmException if the SHA-256 algorithm is not available.
*/
private X509Certificate retrieveTrustRootCert()
throws CertificateException, DigestException, IOException, NoSuchAlgorithmException {
if (trustRootCertificate != null) {
return trustRootCertificate;
} else {
final Optional<ByteArray> cachedContents;
if (trustRootCacheFile != null) {
cachedContents = readCacheFile(trustRootCacheFile);
} else {
cachedContents = trustRootCacheSupplier.get();
}
X509Certificate cert = null;
if (cachedContents.isPresent()) {
final ByteArray verifiedCachedContents = verifyHash(cachedContents.get(), trustRootSha256);
if (verifiedCachedContents != null) {
try {
final X509Certificate cachedCert =
CertificateParser.parseDer(verifiedCachedContents.getBytes());
cachedCert.checkValidity(Date.from(clock.instant()));
cert = cachedCert;
} catch (CertificateException e) {
// Fall through
}
}
}
if (cert == null) {
final ByteArray downloaded = verifyHash(download(trustRootUrl), trustRootSha256);
if (downloaded == null) {
throw new DigestException(
"Downloaded trust root certificate matches none of the acceptable hashes.");
}
cert = CertificateParser.parseDer(downloaded.getBytes());
cert.checkValidity(Date.from(clock.instant()));
if (trustRootCacheFile != null) {
try (FileOutputStream f = new FileOutputStream(trustRootCacheFile)) {
f.write(downloaded.getBytes());
}
}
if (trustRootCacheConsumer != null) {
trustRootCacheConsumer.accept(downloaded);
}
}
return cert;
}
}
/**
* @throws Base64UrlException if the metadata BLOB is not a well-formed JWT in compact
* serialization.
* @throws CertPathValidatorException if the explicitly configured BLOB fails certificate path
* validation.
* @throws CertificateException if the BLOB signing certificate chain fails to parse.
* @throws IOException on failure to parse the BLOB contents.
* @throws InvalidAlgorithmParameterException if certificate path validation fails.
* @throws InvalidKeyException if signature verification fails.
* @throws NoSuchAlgorithmException if signature verification fails, or if the SHA-256 algorithm
* or the <code>"Collection"</code> type {@link CertStore} is not available.
* @throws SignatureException if signature verification fails.