This repository has been archived by the owner on Sep 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
verify_ehc.py
2476 lines (2007 loc) · 98.7 KB
/
verify_ehc.py
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
#!/usr/bin/env python3
from typing import Tuple, Any, Dict, Optional, List, FrozenSet, Union, Type, Callable, Set
from gpiozero import LED
import json
import sys
import zlib
import re
import os
import argparse
import hashlib
import enum
import shutil
from os.path import splitext
from datetime import date, datetime, timedelta, timezone
from time import sleep
from base64 import b64decode, b64encode, urlsafe_b64decode, urlsafe_b64encode
import cbor2 # type: ignore
import cose.algorithms # type: ignore
import cose.keys.curves # type: ignore
import cose.keys.keytype # type: ignore
import requests
import http.client
import asn1crypto.cms # type: ignore
from lxml.html import fromstring as parse_html # type: ignore
from dateutil.parser import isoparse as parse_datetime
from jose import jwt, jws, jwk # type: ignore
from base45 import b45decode # type: ignore
from requests.exceptions import BaseHTTPError # type: ignore
from requests.cookies import RequestsCookieJar # type: ignore
from cose.headers import KID, Algorithm # type: ignore
from cose.keys import CoseKey
from cose.keys.curves import CoseCurve, P256, P384, P521
from cose.keys.keyops import VerifyOp # type: ignore
from cose.keys.keyparam import KpAlg, EC2KpX, EC2KpY, EC2KpCurve, KpKty, RSAKpN, RSAKpE, KpKeyOps # type: ignore
from cose.keys.keytype import KtyEC2, KtyRSA
from cose.messages import CoseMessage, Sign1Message # type: ignore
from cose.algorithms import Ps256, Es256
from cryptography import x509
from cryptography.x509 import load_der_x509_certificate, load_pem_x509_certificate, load_der_x509_crl, load_pem_x509_crl, Name, NameAttribute, Version, Extensions, Extension
from cryptography.x509.extensions import AuthorityKeyIdentifier, CRLDistributionPoints, ExtensionNotFound, ExtendedKeyUsage, SubjectKeyIdentifier
from cryptography.x509.name import _NAMEOID_TO_NAME
from cryptography.x509.oid import NameOID, ObjectIdentifier, ExtensionOID # type: ignore
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat, load_pem_public_key, load_der_public_key
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicKey, EllipticCurvePublicNumbers, ECDSA, SECP256R1, EllipticCurve
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey, RSAPublicNumbers
from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature
from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15
# based on: https://github.com/ehn-digital-green-development/ehn-sign-verify-python-trivial
# Digital Green Certificate Gateway API SPEC: https://eu-digital-green-certificates.github.io/dgc-gateway/#/Trust%20Lists/downloadTrustList
# But where is it hosted?
# Extended Key Usage OIDs:
VALID_FOR_TEST = ObjectIdentifier('1.3.6.1.4.1.1847.2021.1.1')
VALID_FOR_VACCINATION = ObjectIdentifier('1.3.6.1.4.1.1847.2021.1.2')
VALID_FOR_RECOVERY = ObjectIdentifier('1.3.6.1.4.1.1847.2021.1.3')
EXT_KEY_USAGE_NAMES: Dict[ObjectIdentifier, str] = {
VALID_FOR_TEST: 'test',
VALID_FOR_VACCINATION: 'vaccination',
VALID_FOR_RECOVERY: 'recovery',
# these are bugs in some X.509 certificates:
ObjectIdentifier('1.3.6.1.4.1.0.1847.2021.1.1'): 'test',
ObjectIdentifier('1.3.6.1.4.1.0.1847.2021.1.2'): 'vaccination',
ObjectIdentifier('1.3.6.1.4.1.0.1847.2021.1.3'): 'recovery',
}
EXT_KEY_USAGE_OIDS: Dict[str, ObjectIdentifier] = {
'test': VALID_FOR_TEST,
'vaccination': VALID_FOR_VACCINATION,
'recovery': VALID_FOR_RECOVERY,
}
FAIL_ON_ERROR = False
WARNING_AS_ERROR = False
# these would need parameters: 'blake2b', 'blake2s', 'sha512-224', 'sha512-256', 'shake256', 'shake128'
HASH_ALGORITHMS: Dict[str, Type[hashes.HashAlgorithm]] = {}
for attr_name in dir(hashes):
attr = getattr(hashes, attr_name)
if isinstance(attr, type):
if isinstance(attr, type) and issubclass(attr, hashes.HashAlgorithm) and attr is not hashes.HashAlgorithm:
HASH_ALGORITHMS[attr.name] = attr # type: ignore
EPOCH = datetime(1970, 1, 1)
CertList = Dict[bytes, x509.Certificate]
JS_CERT_PATTERN = re.compile(r"'({[^-']*-----BEGIN[^']*)'")
ESC = re.compile(r'\\x([0-9a-fA-F][0-9a-fA-F])')
CURVE_NAME_IGNORE = re.compile(r'[-_ ]')
MD_CERT_PATTERN = re.compile(r'(?P<url>https://[^()\s]+)[^-:]*(?P<cert>-----BEGIN CERTIFICATE-----[^-]*-----END CERTIFICATE-----\r?\n?)')
# https://tools.ietf.org/search/rfc4492#appendix-A
COSE_CURVES: Dict[str, Type[CoseCurve]] = {
'secp256r1': P256,
'prime256v1': P256,
'secp384r1': P384,
'secp521r1': P521,
}
NIST_CURVES: Dict[str, Type[EllipticCurve]] = {
'K-163': ec.SECT163K1,
'B-163': ec.SECT163R2,
'K-233': ec.SECT233K1,
'B-233': ec.SECT233R1,
'K-283': ec.SECT283K1,
'B-283': ec.SECT283R1,
'K-409': ec.SECT409K1,
'B-409': ec.SECT409R1,
'K-571': ec.SECT571K1,
'B-571': ec.SECT571R1,
'P-192': ec.SECP192R1,
'P-224': ec.SECP224R1,
'P-256': ec.SECP256R1,
'P-384': ec.SECP384R1,
'P-521': ec.SECP521R1,
}
SECG_TO_NIST_CURVES: Dict[str, str] = {curve.name: name for name, curve in NIST_CURVES.items()} # type: ignore
NAME_OIDS = {name: name_oid for name_oid, name in _NAMEOID_TO_NAME.items()}
NAME_OIDS_COVID_PASS_VERIFIER = dict(
postalCode = NameOID.POSTAL_CODE,
street = NameOID.STREET_ADDRESS,
organizationIdentifier = NameOID.ORGANIZATION_NAME,
serialNumber = NameOID.SERIAL_NUMBER,
)
NAME_OIDS_COVID_PASS_VERIFIER.update(NAME_OIDS)
for name in dir(cose.keys.curves):
if not name.startswith('_'):
curve = getattr(cose.keys.curves, name)
if curve is not CoseCurve and isinstance(curve, type) and issubclass(curve, CoseCurve) and curve.fullname != 'RESERVED': # type: ignore
name = CURVE_NAME_IGNORE.sub('', curve.fullname).lower() # type: ignore
COSE_CURVES[name] = curve
del name, curve
PREFIX = 'HC1:'
PREFIX_NO = 'NO1:' # Norway
CLAIM_NAMES = {
1: "Issuer",
6: "Issued At",
4: "Expires At",
-260: "Health Claims",
}
DATETIME_CLAIMS = {6, 4}
# This is an old test trust list, not current! It includes test public keys too!
OLD_CERTS_URL_AT = 'https://dgc.a-sit.at/ehn/cert/listv2'
OLD_SIGNS_URL_AT = 'https://dgc.a-sit.at/ehn/cert/sigv2'
# Trust List used by Austrian greencheck app:
CERTS_URL_AT_GREENCHECK = 'https://greencheck.gv.at/api/v2/masterdata'
CERTS_URL_AT_PROD = 'https://dgc-trust.qr.gv.at/trustlist'
SIGN_URL_AT_PROD = 'https://dgc-trust.qr.gv.at/trustlistsig'
CERTS_URL_AT_TEST = 'https://dgc-trusttest.qr.gv.at/trustlist'
SIGN_URL_AT_TEST = 'https://dgc-trusttest.qr.gv.at/trustlistsig'
# only used for root kec extraction from greencheck JavaScript:
ROOT_CERT_KEY_ID_AT = b'\xe0\x9f\xf7\x8f\x02R\x06\xb6'
# See: https://github.com/Federal-Ministry-of-Health-AT/green-pass-overview
# These root certs are copied from some presentation slides.
# TODO: Link a proper source here once it becomes available?
#
# TODO: keep up to date
# Not Before: Jun 2 13:46:21 2021 GMT
# Not After : Jul 2 13:46:21 2022 GMT
ROOT_CERT_AT_PROD = b'''\
-----BEGIN CERTIFICATE-----
MIIB1DCCAXmgAwIBAgIKAXnM+Z3eG2QgVzAKBggqhkjOPQQDAjBEMQswCQYDVQQG
EwJBVDEPMA0GA1UECgwGQk1TR1BLMQwwCgYDVQQFEwMwMDExFjAUBgNVBAMMDUFU
IERHQyBDU0NBIDEwHhcNMjEwNjAyMTM0NjIxWhcNMjIwNzAyMTM0NjIxWjBFMQsw
CQYDVQQGEwJBVDEPMA0GA1UECgwGQk1TR1BLMQ8wDQYDVQQFEwYwMDEwMDExFDAS
BgNVBAMMC0FUIERHQyBUTCAxMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEl2tm
d16CBHXwcBN0r1Uy+CmNW/b2V0BNP85y5N3JZeo/8l9ey/jIe5mol9fFcGTk9bCk
8zphVo0SreHa5aWrQKNSMFAwDgYDVR0PAQH/BAQDAgeAMB0GA1UdDgQWBBRTwp6d
cDGcPUB6IwdDja/a3ncM0TAfBgNVHSMEGDAWgBQfIqwcZRYptMGYs2Nvv90Jnbt7
ezAKBggqhkjOPQQDAgNJADBGAiEAlR0x3CRuQV/zwHTd2R9WNqZMabXv5XqwHt72
qtgnjRgCIQCZHIHbCvlgg5uL8ZJQzAxLavqF2w6uUxYVrvYDj2Cqjw==
-----END CERTIFICATE-----
'''
ROOT_CERT_AT_TEST = b'''\
-----BEGIN CERTIFICATE-----
MIIB6zCCAZGgAwIBAgIKAXmEuohlRbR2qzAKBggqhkjOPQQDAjBQMQswCQYDVQQG
EwJBVDEPMA0GA1UECgwGQk1TR1BLMQowCAYDVQQLDAFRMQwwCgYDVQQFEwMwMDEx
FjAUBgNVBAMMDUFUIERHQyBDU0NBIDEwHhcNMjEwNTE5MTMwNDQ3WhcNMjIwNjE5
MTMwNDQ3WjBRMQswCQYDVQQGEwJBVDEPMA0GA1UECgwGQk1TR1BLMQowCAYDVQQL
DAFRMQ8wDQYDVQQFEwYwMDEwMDExFDASBgNVBAMMC0FUIERHQyBUTCAxMFkwEwYH
KoZIzj0CAQYIKoZIzj0DAQcDQgAE29KpT1eIKsy5Jx3J0xpPLW+fEBF7ma9943/j
4Z+o1TytLVok9cWjsdasWCS/zcRyAh7HBL+oyMWdFBOWENCQ76NSMFAwDgYDVR0P
AQH/BAQDAgeAMB0GA1UdDgQWBBQYmsL5sXTdMCyW4UtP5BMxq+UAVzAfBgNVHSME
GDAWgBR2sKi2xkUpGC1Cr5ehwL0hniIsJzAKBggqhkjOPQQDAgNIADBFAiBse17k
F5F43q9mRGettRDLprASrxsDO9XxUUp3ObjcWQIhALfUWnserGEPiD7Pa25tg9lj
wkrqDrMdZHZ39qb+Jf/E
-----END CERTIFICATE-----
'''
# Trust List used by German Digitaler-Impfnachweis app:
CERTS_URL_DE = 'https://de.dscg.ubirch.com/trustList/DSC/'
PUBKEY_URL_DE = 'https://github.com/Digitaler-Impfnachweis/covpass-ios/raw/main/Certificates/PROD_RKI/CA/pubkey.pem'
# Netherlands public keys:
# (https://www.npkd.nl/csca-health.html)
# https://verifier-api.<acc/test/etc>.coronacheck.nl/v4/verifier/public_keys
# json containing a CMS (rfc5652) signature and a payload. Both base64 encoded.
# The payload is a json dictionary of the domestic and international keys. The
# later is an dictionary with the KID as a base64 encoded key and a subkjectPK
# and keyUsage array with the allowed use. Typical decode is:
# curl https://verifier-api.acc.coronacheck.nl/v4/verifier/public_keys |\
# jq -r .payload |\
# base64 -d |\
# jq .eu_keys
CERTS_URL_NL = 'https://verifier-api.coronacheck.nl/v4/verifier/public_keys'
ROOT_CERT_URL_NL = 'http://cert.pkioverheid.nl/EVRootCA.cer'
# Keys from a French validation app (nothing official, just a hobby project by someone):
# https://github.com/lovasoa/sanipasse/blob/master/src/assets/Digital_Green_Certificate_Signing_Keys.json
# French trust list:
# This requires the environment variable FR_TOKEN to be set to a bearer token that can be found in the TousAntiCovid Verif app.
CERTS_URL_FR = 'https://portail.tacv.myservices-ingroupe.com/api/client/configuration/synchronisation/tacv'
# Sweden (JOSE encoded):
CERTS_URL_SE = 'https://dgcg.covidbevis.se/tp/trust-list'
ROOT_CERT_URL_SE = 'https://dgcg.covidbevis.se/tp/cert'
# See: https://github.com/DIGGSweden/dgc-trust/blob/main/specifications/trust-list.md
# United Kingdom trust list:
CERTS_URL_GB = 'https://covid-status.service.nhsx.nhs.uk/pubkeys/keys.json'
CERTS_URL_COVID_PASS_VERIFIER = 'https://covid-pass-verifier.com/assets/certificates.json'
# Norwegian trust list:
CERTS_URL_NO = 'https://koronakontroll.nhn.no/v2/publickey'
# Norwegian COVID-19 certificates seem to be based on the European Health Certificate but just with an 'NO1:' prefix.
# https://harrisonsand.com/posts/covid-certificates/
# Switzerland:
# See: https://github.com/cn-uofbasel/ch-dcc-keys
ROOT_CERT_URL_CH = 'https://www.bit.admin.ch/dam/bit/en/dokumente/pki/scanning_center/swiss_governmentrootcaii.crt.download.crt/swiss_governmentrootcaii.crt'
CERTS_URL_CH = 'https://www.cc.bit.admin.ch/trust/v1/keys/list'
UPDATE_URL_CH = 'https://www.cc.bit.admin.ch/trust/v1/keys/updates?certFormat=ANDROID'
USER_AGENT = 'Mozilla/5.0 (Windows) Firefox/90.0'
# See also this thread:
# https://github.com/eu-digital-green-certificates/dgc-participating-countries/issues/10
DEFAULT_NOT_VALID_BEFORE = datetime(1970, 1, 1)
DEFAULT_NOT_VALID_AFTER = datetime(9999, 12, 31, 23, 59, 59, 999999)
class HackCertificate(x509.Certificate):
_public_key: Union[EllipticCurvePublicKey, RSAPublicKey]
_issuer: Name
_subject: Name
_extensions: Extensions
_not_valid_before: datetime
_not_valid_after: datetime
def __init__(self,
public_key: Union[EllipticCurvePublicKey, RSAPublicKey],
issuer: Optional[Name] = None,
subject: Optional[Name] = None,
not_valid_before: datetime = DEFAULT_NOT_VALID_BEFORE,
not_valid_after: datetime = DEFAULT_NOT_VALID_AFTER,
extensions: Optional[Extensions] = None,
):
self._public_key = public_key
self._issuer = issuer if issuer is not None else Name([])
self._subject = subject if subject is not None else Name([])
self._extensions = extensions if extensions is not None else Extensions([])
self._not_valid_before = not_valid_before
self._not_valid_after = not_valid_after
def fingerprint(self, algorithm: hashes.HashAlgorithm) -> bytes:
raise NotImplementedError
@property
def extensions(self) -> Extensions:
return self._extensions
@property
def signature(self) -> bytes:
return b''
@property
def tbs_certificate_bytes(self) -> bytes:
return b''
def __eq__(self, other: object) -> bool:
if not isinstance(other, HackCertificate):
return False
return self.__as_tuple() == other.__as_tuple()
def __ne__(self, other: object) -> bool:
if not isinstance(other, HackCertificate):
return True
return self.__as_tuple() != other.__as_tuple()
def __as_tuple(self) -> Tuple[Union[EllipticCurvePublicKey, RSAPublicKey], Name, Name, Extensions]:
return (self._public_key, self._issuer, self._subject, self._extensions)
def __hash__(self) -> int:
return hash(self.__as_tuple())
@property
def serial_number(self) -> int:
return 0
@property
def issuer(self) -> Name:
return self._issuer
@property
def subject(self) -> Name:
return self._subject
@property
def version(self) -> Version:
return Version.v1
@property
def signature_algorithm_oid(self) -> ObjectIdentifier:
raise NotImplementedError
@property
def signature_hash_algorithm(self):
raise NotImplementedError
@property
def not_valid_before(self) -> datetime:
return self._not_valid_before
@property
def not_valid_after(self) -> datetime:
return self._not_valid_after
def public_key(self):
return self._public_key
def public_bytes(self, encoding: Encoding):
raise NotImplementedError("cannot serialize certificate from public-key only")
#return self._public_key.public_bytes(encoding, PublicFormat.SubjectPublicKeyInfo)
def json_serial(obj: Any) -> str:
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datetime, date)):
return obj.isoformat()
raise TypeError(f"Type {type(obj)} not serializable")
def load_ehc_certs(filename: str) -> CertList:
with open(filename, 'rb') as stream:
certs_cbor = stream.read()
return load_ehc_certs_cbor(certs_cbor, filename)
def load_ehc_certs_cbor(cbor_data: bytes, source: str) -> CertList:
certs_data = cbor2.loads(cbor_data)
certs: CertList = {}
for item in certs_data['c']:
key_id = item.get('i')
try:
cert_data = item.get('c')
if cert_data:
cert = load_der_x509_certificate(cert_data)
fingerprint = cert.fingerprint(hashes.SHA256())
if key_id != fingerprint[0:8]:
raise ValueError(f'Key ID missmatch: {key_id.hex()} != {fingerprint[0:8].hex()}')
else:
pubkey_data = item['k']
pubkey = load_der_public_key(pubkey_data)
issuer_dict = item.get('is')
issuer = parse_json_relative_distinguished_name(issuer_dict) if issuer_dict is not None else Name([])
subject_dict = item.get('su')
subject = parse_json_relative_distinguished_name(subject_dict) if subject_dict is not None else Name([])
nb = item.get('nb')
not_valid_before = EPOCH + timedelta(seconds=nb) if nb is not None else DEFAULT_NOT_VALID_BEFORE
na = item.get('na')
not_valid_after = EPOCH + timedelta(seconds=na) if na is not None else DEFAULT_NOT_VALID_AFTER
if isinstance(pubkey, (EllipticCurvePublicKey, RSAPublicKey)):
cert = HackCertificate(pubkey,
not_valid_before = not_valid_before,
not_valid_after = not_valid_after,
issuer = issuer,
subject = subject,
)
else:
pubkey_type = type(pubkey)
raise NotImplementedError(f'Unsupported public key type: {pubkey_type.__module__}.{pubkey_type.__name__}')
if key_id in certs:
print_warn(f'doubled key ID in {source} trust list, only using last: {format_key_id(key_id)}')
except Exception as error:
print_err(f'decoding {source} trust list entry {format_key_id(key_id)}: {error}')
else:
certs[key_id] = cert
return certs
def load_ehc_certs_pem(pem_data: bytes, source: str) -> CertList:
certs: CertList = {}
index = 0
while index < len(pem_data):
while index < len(pem_data) and chr(pem_data[index]).isspace():
index += 1
if index >= len(pem_data):
break
if not pem_data.startswith(b'-----BEGIN CERTIFICATE-----', index):
raise ValueError(f'decoding {source}: illegal file format')
end_index = pem_data.find(b'-----END CERTIFICATE-----', index)
if end_index < 0:
raise ValueError(f'decoding {source}: illegal file format')
end_index += len(b'-----END CERTIFICATE-----')
cert = load_pem_x509_certificate(pem_data[index:end_index])
index = end_index
fingerprint = cert.fingerprint(hashes.SHA256())
key_id = fingerprint[0:8]
if key_id in certs:
print_warn(f'doubled key ID in {source} trust list, only using last: {format_key_id(key_id)}')
certs[key_id] = cert
return certs
def make_json_relative_distinguished_name(name: Name) -> Dict[str, str]:
return {_NAMEOID_TO_NAME.get(attr.oid, attr.oid.dotted_string): attr.value
for attr in reversed(list(name))}
def parse_json_relative_distinguished_name(name_dict: Dict[str, str]) -> Name:
name_attrs: List[NameAttribute] = []
for attr_type_str, attr_value in name_dict.items():
attr_type = NAME_OIDS.get(attr_type_str) or ObjectIdentifier(attr_type_str)
name_attrs.append(NameAttribute(attr_type, attr_value))
return Name(name_attrs)
def load_hack_certs_json(data: bytes, source: str) -> CertList:
certs_dict = json.loads(data)
certs: CertList = {}
for key_id_hex, cert_dict in certs_dict['trustList'].items():
not_valid_before = parse_datetime(cert_dict['notValidBefore'])
not_valid_after = parse_datetime(cert_dict['notValidAfter'])
issuer = parse_json_relative_distinguished_name(cert_dict['issuer']) if 'issuer' in cert_dict else Name([])
subject = parse_json_relative_distinguished_name(cert_dict['subject']) if 'subject' in cert_dict else Name([])
pubkey_dict = cert_dict['publicKey']
usage = cert_dict.get('usage')
exts: List[Extension] = []
if usage is not None:
usage_oids: List[ObjectIdentifier] = []
for use in usage:
oid = EXT_KEY_USAGE_OIDS[use]
usage_oids.append(oid)
exts.append(Extension(ExtensionOID.EXTENDED_KEY_USAGE, False, ExtendedKeyUsage(usage_oids)))
extensions = Extensions(exts)
key_id = urlsafe_b64decode_ignore_padding(pubkey_dict['kid'])
key_type = pubkey_dict['kty']
if key_type == 'EC':
curve_name = pubkey_dict['crv']
curve_type = NIST_CURVES.get(curve_name)
if not curve_type:
raise ValueError(f'unknown elliptic curve: {curve_name!r}')
curve = curve_type()
x_bytes = urlsafe_b64decode_ignore_padding(pubkey_dict['x'])
y_bytes = urlsafe_b64decode_ignore_padding(pubkey_dict['y'])
x = int.from_bytes(x_bytes, byteorder="big", signed=False)
y = int.from_bytes(y_bytes, byteorder="big", signed=False)
ec_pubkey = EllipticCurvePublicNumbers(x, y, curve).public_key()
cert = HackCertificate(ec_pubkey, issuer, subject, not_valid_before, not_valid_after, extensions=extensions)
if key_id in certs:
print_warn(f'doubled key ID in {source} trust list, only using last: {format_key_id(key_id)}')
certs[key_id] = cert
elif key_type == 'RSA':
e_bytes = urlsafe_b64decode_ignore_padding(pubkey_dict['e'])
n_bytes = urlsafe_b64decode_ignore_padding(pubkey_dict['n'])
e = int.from_bytes(e_bytes, byteorder="big", signed=False)
n = int.from_bytes(n_bytes, byteorder="big", signed=False)
rsa_pubkey = RSAPublicNumbers(e, n).public_key()
cert = HackCertificate(rsa_pubkey, issuer, subject, not_valid_before, not_valid_after, extensions=extensions)
if key_id in certs:
print_warn(f'doubled key ID in {source} trust list, only using last: {format_key_id(key_id)}')
certs[key_id] = cert
else:
print_err(f'decoding {source} trust list: illegal key type: {key_type!r}')
return certs
def print_err(msg: str) -> None:
if FAIL_ON_ERROR:
raise Exception(msg)
else:
# so that errors and normal output is correctly interleaved:
sys.stdout.flush()
print(f'ERROR: {msg}', file=sys.stderr)
def print_warn(msg: str) -> None:
if WARNING_AS_ERROR:
print_err(msg)
else:
# so that errors and normal output is correctly interleaved:
sys.stdout.flush()
print(f'WARNING: {msg}', file=sys.stderr)
def load_de_trust_list(data: bytes, pubkey: Optional[EllipticCurvePublicKey] = None) -> CertList:
certs: CertList = {}
sign_b64, body_json = data.split(b'\n', 1)
sign = b64decode(sign_b64)
body = json.loads(body_json)
if pubkey is not None:
r = int.from_bytes(sign[:len(sign)//2], byteorder="big", signed=False)
s = int.from_bytes(sign[len(sign)//2:], byteorder="big", signed=False)
sign_dds = encode_dss_signature(r, s)
try:
pubkey.verify(sign_dds, body_json, ECDSA(hashes.SHA256()))
except InvalidSignature:
raise ValueError(f'Invalid signature of DE trust list: {sign.hex()}')
for cert in body['certificates']:
try:
key_id_b64 = cert['kid']
key_id = b64decode(key_id_b64)
except Exception as error:
print_err(f'decoding DE trust list entry {json.dumps(cert)}: {error}')
else:
try:
country = cert['country']
cert_type = cert['certificateType']
if cert_type != 'DSC':
raise ValueError(f'unknown certificateType {cert_type!r} (country={country}, kid={key_id.hex()}')
raw_data = b64decode(cert['rawData'])
cert = load_der_x509_certificate(raw_data)
fingerprint = cert.fingerprint(hashes.SHA256())
if key_id != fingerprint[0:8]:
raise ValueError(f'Key ID missmatch: {key_id.hex()} != {fingerprint[0:8].hex()}')
if key_id in certs:
print_warn(f'doubled key ID in DE trust list, only using last: {format_key_id(key_id)}')
except Exception as error:
print_err(f'decoding DE trust list entry {format_key_id(key_id)}: {error}')
else:
certs[key_id] = cert
return certs
def download_at_greencheck_certs() -> CertList:
root_certs: Dict[bytes, x509.Certificate]
cookies: Optional[RequestsCookieJar] = None
try:
root_certs, cookies = get_at_greencheck_root_certs_and_cookies()
except (BaseHTTPError, ValueError, KeyError) as error:
print_err(f'AT trust list error (NOT VALIDATING): {error}')
root_certs = {}
response = requests.get(CERTS_URL_AT_GREENCHECK, headers={
'User-Agent': USER_AGENT,
'Accept': 'application/json',
'x-app-type': 'browser',
'x-app-version': '1.6',
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'same-origin',
'Sec-GPC': '1',
'Cache-Control': 'max-age=0',
}, cookies=cookies)
response.raise_for_status()
certs_json = json.loads(response.content)['trustList']
certs_cbor = b64decode(certs_json['trustListContent'])
certs_sig = b64decode(certs_json['trustListSignature'])
sig_msg = CoseMessage.decode(certs_sig)
if not isinstance(sig_msg, Sign1Message):
msg_type = type(sig_msg)
raise TypeError(f'AT trust list: expected signature to be a Sign1 COSE message, but is: {msg_type.__module__}.{msg_type.__name__}')
root_cert_key_id = sig_msg.phdr.get(KID) or sig_msg.uhdr[KID]
root_cert: Optional[x509.Certificate] = root_certs.get(root_cert_key_id)
if root_cert is not None:
now = datetime.utcnow()
if now < root_cert.not_valid_before:
raise ValueError(f'AT trust list root certificate not yet valid: {now.isoformat()} < {root_cert.not_valid_before.isoformat()}')
if now > root_cert.not_valid_after:
raise ValueError(f'AT trust list root certificate already expired: {now.isoformat()} > {root_cert.not_valid_after.isoformat()}')
sig_msg.key = cert_to_cose_key(root_cert) # type: ignore
if not sig_msg.verify_signature(): # type: ignore
raise ValueError(f'Invalid signature of AT trust list: {sig_msg.signature.hex()}') # type: ignore
sig = cbor2.loads(sig_msg.payload)
digest = hashlib.sha256(certs_cbor).digest()
if sig[2] != digest:
raise ValueError(f'Invalid hash of AT trust list. expected: {sig[2].hex()}, actual: {digest.hex()}')
created_at = EPOCH + timedelta(seconds=sig[5]) # I guess? Or "not valid before"?
expires_at = EPOCH + timedelta(seconds=sig[4])
if now > expires_at:
raise ValueError(f'AT trust list already expired at {expires_at.isoformat()}')
else:
print_err(f'root certificate for AT trust list not found!')
return load_ehc_certs_cbor(certs_cbor, 'AT')
def download_at_certs(test: bool = False, token: Optional[str] = None) -> CertList:
# TODO: update to handle tokens once required
#if token is None:
# token = os.getenv('AT_TOKEN')
# if token is None:
# raise KeyError(
# 'Required environment variable AT_TOKEN for AT trust list is not set. '
# 'Information about how to get a token will follow soon.')
if test:
certs_url = CERTS_URL_AT_TEST
sign_url = SIGN_URL_AT_TEST
root_cert = get_root_cert('AT-TEST')
else:
certs_url = CERTS_URL_AT_PROD
sign_url = SIGN_URL_AT_PROD
root_cert = get_root_cert('AT')
response = requests.get(certs_url, headers={'User-Agent': USER_AGENT})
#response = requests.get(certs_url, headers={
# 'User-Agent': USER_AGENT,
# 'Authorization': f'Bearer {token}',
#})
response.raise_for_status()
certs_cbor = response.content
response = requests.get(sign_url, headers={'User-Agent': USER_AGENT})
#response = requests.get(sign_url, headers={
# 'User-Agent': USER_AGENT,
# 'Authorization': f'Bearer {token}',
#})
response.raise_for_status()
certs_sig = response.content
sig_msg = CoseMessage.decode(certs_sig)
if not isinstance(sig_msg, Sign1Message):
msg_type = type(sig_msg)
raise TypeError(f'AT trust list: expected signature to be a Sign1 COSE message, but is: {msg_type.__module__}.{msg_type.__name__}')
root_cert_key_id = sig_msg.phdr.get(KID) or sig_msg.uhdr[KID]
key_id = root_cert.fingerprint(hashes.SHA256())[:8]
if key_id != root_cert_key_id:
raise ValueError(f'AT trust list root certificate key ID missmatch. {key_id.hex()} != {root_cert_key_id.hex()}')
now = datetime.utcnow()
if now < root_cert.not_valid_before:
raise ValueError(f'AT trust list root certificate not yet valid: {now.isoformat()} < {root_cert.not_valid_before.isoformat()}')
if now > root_cert.not_valid_after:
raise ValueError(f'AT trust list root certificate already expired: {now.isoformat()} > {root_cert.not_valid_after.isoformat()}')
sig_msg.key = cert_to_cose_key(root_cert) # type: ignore
if not sig_msg.verify_signature(): # type: ignore
raise ValueError(f'Invalid signature of AT trust list: {sig_msg.signature.hex()}') # type: ignore
sig = cbor2.loads(sig_msg.payload)
digest = hashlib.sha256(certs_cbor).digest()
if sig[2] != digest:
raise ValueError(f'Invalid hash of AT trust list. expected: {sig[2].hex()}, actual: {digest.hex()}')
created_at = EPOCH + timedelta(seconds=sig[5]) # I guess? Or "not valid before"?
expires_at = EPOCH + timedelta(seconds=sig[4])
if now > expires_at:
raise ValueError(f'AT trust list already expired at {expires_at.isoformat()}')
return load_ehc_certs_cbor(certs_cbor, 'AT')
def download_de_certs() -> CertList:
response = requests.get(CERTS_URL_DE, headers={'User-Agent': USER_AGENT})
response.raise_for_status()
certs_signed_json = response.content
pubkey: Optional[EllipticCurvePublicKey] = None
try:
pubkey = get_root_cert('DE').public_key() # type: ignore
except (BaseHTTPError, ValueError) as error:
print_err(f'DE trust list error (NOT VALIDATING): {error}')
return load_de_trust_list(certs_signed_json, pubkey)
def download_se_certs() -> CertList:
certs: CertList = {}
root_cert: Optional[x509.Certificate] = None
try:
root_cert = get_root_cert('SE')
except (BaseHTTPError, ValueError) as error:
print_err(f'SE trust list error (NOT VALIDATING): {error}')
response = requests.get(CERTS_URL_SE, headers={'User-Agent': USER_AGENT})
response.raise_for_status()
if root_cert is None:
token = jwt.get_unverified_claims(response.content.decode(response.encoding or 'UTF-8'))
else:
token = load_jwt(response.content, root_cert, {'verify_aud': False})
for country, country_keys in token['dsc_trust_list'].items():
for entry in country_keys['keys']:
key_id = b64decode(entry['kid'])
for key_data in entry['x5c']:
try:
cert = load_der_x509_certificate(b64decode_ignore_padding(key_data))
fingerprint = cert.fingerprint(hashes.SHA256())
if key_id != fingerprint[0:8]:
raise ValueError(f'Key ID missmatch: {key_id.hex()} != {fingerprint[0:8].hex()}')
if key_id in certs:
print_warn(f'doubled key ID in SE trust list, only using last: {format_key_id(key_id)}')
except Exception as error:
print_err(f'decoding SE trust list entry {key_id.hex()} / {b64encode(key_id).decode("ASCII")}: {error}')
else:
certs[key_id] = cert
return certs
def download_covid_pass_verifier_certs() -> CertList:
certs: CertList = {}
response = requests.get(CERTS_URL_COVID_PASS_VERIFIER, headers={'User-Agent': USER_AGENT})
response.raise_for_status()
certs_json = json.loads(response.content)
for entry in certs_json:
key_id = bytes(entry['kid'])
cert_der = bytes(entry['crt'])
if cert_der:
try:
cert = load_der_x509_certificate(cert_der)
except Exception as error:
print_err(f'decoding covid-pass-verifier.com trust list entry {format_key_id(key_id)}: {error}')
else:
fingerprint = cert.fingerprint(hashes.SHA256())
if key_id != fingerprint[0:8]:
raise ValueError(f'Key ID missmatch: {key_id.hex()} != {fingerprint[0:8].hex()}')
if key_id in certs:
print_warn(f'doubled key ID in covid-pass-verifier.com trust list, only using last: {format_key_id(key_id)}')
certs[key_id] = cert
else:
iss = entry.get('iss')
if iss:
issuer = Name([NameAttribute(NAME_OIDS_COVID_PASS_VERIFIER.get(key) or ObjectIdentifier(key), value) for key, value in iss.items()])
else:
issuer = Name([])
sub = entry.get('sub')
if sub:
subject = Name([NameAttribute(NAME_OIDS_COVID_PASS_VERIFIER.get(key) or ObjectIdentifier(key), value) for key, value in sub.items()])
else:
subject = Name([])
pub = entry['pub']
if 'x' in pub and 'y' in pub:
# EC
x_bytes = bytes(pub['x'])
y_bytes = bytes(pub['y'])
x = int.from_bytes(x_bytes, byteorder="big", signed=False)
y = int.from_bytes(y_bytes, byteorder="big", signed=False)
curve = SECP256R1()
ec_pubkey = EllipticCurvePublicNumbers(x, y, curve).public_key()
cert = HackCertificate(ec_pubkey, issuer, subject)
if key_id in certs:
print_warn(f'doubled key ID in covid-pass-verifier.com trust list, only using last: {format_key_id(key_id)}')
certs[key_id] = cert
elif 'n' in pub and 'e' in pub:
# RSA
e_bytes = bytes(pub['e'])
n_bytes = bytes(pub['n'])
e = int.from_bytes(e_bytes, byteorder="big", signed=False)
n = int.from_bytes(n_bytes, byteorder="big", signed=False)
rsa_pubkey = RSAPublicNumbers(e, n).public_key()
cert = HackCertificate(rsa_pubkey, issuer, subject)
if key_id in certs:
print_warn(f'doubled key ID in covid-pass-verifier.com trust list, only using last: {format_key_id(key_id)}')
certs[key_id] = cert
else:
print_err(f'decoding covid-pass-verifier.com trust list entry {format_key_id(key_id)}: no supported public key data found')
return certs
def download_fr_certs(token: Optional[str] = None) -> CertList:
certs: CertList = {}
if token is None:
token = os.getenv('FR_TOKEN')
if token is None:
raise KeyError(
'Required environment variable FR_TOKEN for FR trust list is not set. '
'You can get the value of the token from the TousAntiCovid Verif app. '
'See token_lite at https://gitlab.inria.fr/tousanticovid-verif/tousanticovid-verif-ios/-/blob/master/Anticovid%20Verify/resources/prod/prod.plist')
response = requests.get(CERTS_URL_FR, headers={
'User-Agent': USER_AGENT,
'Authorization': f'Bearer {token}',
})
response.raise_for_status()
certs_json = json.loads(response.content)
for key_id_b64, cert_b64 in certs_json['certificatesDCC'].items():
try:
key_id = b64decode_ignore_padding(key_id_b64)
except Exception as error:
print_err(f'decoding FR trust list entry {key_id_b64}: {error}')
else:
try:
cert_pem = b64decode(cert_b64)
# Yes, they encode it twice!
cert_der = b64decode(cert_pem)
try:
cert = load_der_x509_certificate(cert_der)
except ValueError:
cert = load_hack_certificate_from_der_public_key(cert_der)
# HackCertificate.fingerprint() is not implemented
else:
fingerprint = cert.fingerprint(hashes.SHA256())
if key_id != fingerprint[0:8]:
pubkey = cert.public_key()
attrs = cert.subject.get_attributes_for_oid(NameOID.COUNTRY_NAME)
if attrs and all(attr.value == 'UK' for attr in attrs) and isinstance(pubkey, (RSAPublicKey, EllipticCurvePublicKey)):
# replace fake FR trust list certificate by my own fake certificate
# XXX: not eintirely sure if I should do this?
issuer = [attr for attr in cert.issuer if attr.oid != NameOID.COUNTRY_NAME]
subject = [attr for attr in cert.subject if attr.oid != NameOID.COUNTRY_NAME]
issuer.append( NameAttribute(NameOID.COUNTRY_NAME, 'GB'))
subject.append(NameAttribute(NameOID.COUNTRY_NAME, 'GB'))
cert = HackCertificate(
pubkey,
issuer = Name(issuer),
subject = Name(subject),
not_valid_before = cert.not_valid_before,
not_valid_after = cert.not_valid_after,
)
else:
#print()
#print_cert(key_id, cert, print_exts=True)
raise ValueError(f'Key ID missmatch: {key_id.hex()} != {fingerprint[0:8].hex()}')
if key_id in certs:
print_warn(f'doubled key ID in FR trust list, only using last: {format_key_id(key_id)}')
except Exception as error:
print_err(f'decoding FR trust list entry {format_key_id(key_id)}: {error}')
else:
certs[key_id] = cert
return certs
def build_trust_chain(certs: List[x509.Certificate]) -> Dict[bytes, x509.Certificate]:
trustchain: Dict[bytes, x509.Certificate] = {}
for cert in certs:
subject_key_id: Extension[SubjectKeyIdentifier] = cert.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_KEY_IDENTIFIER) # type: ignore
trustchain[subject_key_id.value.digest] = cert
return trustchain
def verify_trust_chain(cert: x509.Certificate, trustchain: Dict[bytes, x509.Certificate], root_cert: x509.Certificate) -> bool:
signed_cert = cert
rsa_padding = PKCS1v15()
root_subject_key_id_ext: Extension[SubjectKeyIdentifier] = root_cert.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_KEY_IDENTIFIER) # type: ignore
root_subject_key_id = root_subject_key_id_ext.value.digest
visited: Set[bytes] = set()
while signed_cert is not root_cert:
auth_key_id_ext: Extension[AuthorityKeyIdentifier] = signed_cert.extensions.get_extension_for_oid(ExtensionOID.AUTHORITY_KEY_IDENTIFIER) # type: ignore
auth_key_id = auth_key_id_ext.value.key_identifier
if auth_key_id is None:
raise ValueError(f'a certificate in the trust chain misses an authority key identifier')
if auth_key_id in visited:
raise ValueError('loop in trust chain detected')
visited.add(auth_key_id)
issuer_cert: Optional[x509.Certificate]
if root_subject_key_id == auth_key_id:
issuer_cert = root_cert
else:
issuer_cert = trustchain.get(auth_key_id)
if issuer_cert == root_cert:
# just to be sure that there is no trickery:
issuer_cert = root_cert
if issuer_cert is None:
auth_key_id_str = ':'.join('%02X' % x for x in auth_key_id)
fingerprint = signed_cert.fingerprint(hashes.SHA256())
fingerprint_str = ':'.join('%02X' % x for x in fingerprint)
print_err(f'Could not verify signature of a certificate in the trust chain.\n'
f'fingerprint: {fingerprint_str}\n'
f'authority key ID: {auth_key_id_str}')
return False
pubkey = issuer_cert.public_key()
try:
if isinstance(pubkey, RSAPublicKey):
pubkey.verify(
signed_cert.signature,
signed_cert.tbs_certificate_bytes,
rsa_padding,
signed_cert.signature_hash_algorithm, # type: ignore
)
elif isinstance(pubkey, EllipticCurvePublicKey):
pubkey.verify(
signed_cert.signature,
signed_cert.tbs_certificate_bytes,
ECDSA(signed_cert.signature_hash_algorithm), # type: ignore
)
else:
pubkey_type = type(pubkey)
raise NotImplementedError(f'Unsupported public key type: {pubkey_type.__module__}.{pubkey_type.__name__}')
except InvalidSignature:
try:
subject_key_id_ext: Extension[SubjectKeyIdentifier] = signed_cert.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_KEY_IDENTIFIER) # type: ignore
subject_key_id = subject_key_id_ext.value.digest
except ExtensionNotFound:
subject_key_id_str = 'N/A'
except ValueError as error:
print_err(f'Parsing extended key usage: {error}')
subject_key_id_str = 'N/A'
else:
subject_key_id_str = ':'.join('%02X' % x for x in subject_key_id)