From 68d135903dca284b08c28308e03c7781c80763e7 Mon Sep 17 00:00:00 2001 From: peppelinux Date: Tue, 1 Dec 2026 11:47:06 +0100 Subject: [PATCH 1/4] breaking change: verify() requires trusted root/issuer by default --- .github/workflows/code-quality.yml | 4 + .github/workflows/dependency-security.yml | 4 + .github/workflows/python-app.yml | 4 + README.md | 15 +- docs/CERTIFICATE-CHAIN-VERIFICATION.md | 112 +++++++----- docs/CREATE-MSO.md | 2 +- docs/DIAGN-VALIDATE.md | 4 +- examples/it_data_model.py | 1 - pymdoccbor/__init__.py | 2 +- pymdoccbor/exceptions.py | 12 ++ pymdoccbor/mdoc/verifier.py | 76 ++++++-- pymdoccbor/mso/verifier.py | 169 ++++++++++++++++-- pymdoccbor/tests/test_01_mdoc_parser.py | 10 +- pymdoccbor/tests/test_02_mdoc_issuer.py | 14 +- pymdoccbor/tests/test_03_mdoc_issuer.py | 15 -- pymdoccbor/tests/test_05_mdoc_verifier.py | 2 +- pymdoccbor/tests/test_07_mso_verifier.py | 2 +- pymdoccbor/tests/test_08_mdoc_cbor.py | 2 +- .../tests/test_10_cert_chain_and_hashes.py | 48 +++-- pymdoccbor/tests/test_11_cbor2_compat.py | 2 +- pymdoccbor/x509.py | 1 + 21 files changed, 373 insertions(+), 128 deletions(-) diff --git a/.github/workflows/code-quality.yml b/.github/workflows/code-quality.yml index fb52b42..9b1f52a 100644 --- a/.github/workflows/code-quality.yml +++ b/.github/workflows/code-quality.yml @@ -7,6 +7,10 @@ on: pull_request: branches: ["*"] +permissions: + contents: read + actions: read + jobs: skip-check: runs-on: ubuntu-latest diff --git a/.github/workflows/dependency-security.yml b/.github/workflows/dependency-security.yml index 54c29af..e24c178 100644 --- a/.github/workflows/dependency-security.yml +++ b/.github/workflows/dependency-security.yml @@ -7,6 +7,10 @@ on: pull_request: branches: ["*"] +permissions: + contents: read + actions: read + jobs: skip-check: runs-on: ubuntu-latest diff --git a/.github/workflows/python-app.yml b/.github/workflows/python-app.yml index 987188a..09a19e5 100644 --- a/.github/workflows/python-app.yml +++ b/.github/workflows/python-app.yml @@ -9,6 +9,10 @@ on: pull_request: branches: [ "*" ] +permissions: + contents: read + actions: read + jobs: skip-check: runs-on: ubuntu-latest diff --git a/README.md b/README.md index 08835be..eccb339 100644 --- a/README.md +++ b/README.md @@ -362,7 +362,12 @@ from pymdoccbor.mdoc.verifier import MdocCbor ISSUED_MDOC="a36776657273696f6e63312e3069646f63756d656e747381a367646f6354797065756f72672e69736f2e31383031332e352e312e6d444c6c6973737565725369676e6564a26a6e616d65537061636573a1716f72672e69736f2e31383031332e352e3186d8185863a4686469676573744944006672616e646f6d58208798645b20ea200e19ffabac92624bee6aec63aceedecfb1b80077d22bfc20e971656c656d656e744964656e7469666965726b66616d696c795f6e616d656c656c656d656e7456616c756563446f65d818586ca4686469676573744944036672616e646f6d5820b23f627e8999c706df0c0a4ed98ad74af988af619b4bb078b89058553f44615d71656c656d656e744964656e7469666965726a69737375655f646174656c656c656d656e7456616c7565d903ec6a323031392d31302d3230d818586da4686469676573744944046672616e646f6d5820c7ffa307e5de921e67ba5878094787e8807ac8e7b5b3932d2ce80f00f3e9abaf71656c656d656e744964656e7469666965726b6578706972795f646174656c656c656d656e7456616c7565d903ec6a323032342d31302d3230d818586da4686469676573744944076672616e646f6d582026052a42e5880557a806c1459af3fb7eb505d3781566329d0b604b845b5f9e6871656c656d656e744964656e7469666965726f646f63756d656e745f6e756d6265726c656c656d656e7456616c756569313233343536373839d818590471a4686469676573744944086672616e646f6d5820d094dad764a2eb9deb5210e9d899643efbd1d069cc311d3295516ca0b024412d71656c656d656e744964656e74696669657268706f7274726169746c656c656d656e7456616c7565590412ffd8ffe000104a46494600010101009000900000ffdb004300130d0e110e0c13110f11151413171d301f1d1a1a1d3a2a2c2330453d4947443d43414c566d5d4c51685241435f82606871757b7c7b4a5c869085778f6d787b76ffdb0043011415151d191d381f1f38764f434f7676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676ffc00011080018006403012200021101031101ffc4001b00000301000301000000000000000000000005060401020307ffc400321000010303030205020309000000000000010203040005110612211331141551617122410781a1163542527391b2c1f1ffc4001501010100000000000000000000000000000001ffc4001a110101010003010000000000000000000000014111213161ffda000c03010002110311003f00a5bbde22da2329c7d692bc7d0d03f52cfb0ff75e7a7ef3e7709723a1d0dae146ddfbb3c039ce07ad2bd47a7e32dbb8dd1d52d6ef4b284f64a480067dfb51f87ffb95ff00eb9ff14d215de66af089ce44b7dbde9cb6890a2838eddf18078f7add62d411ef4db9b10a65d6b95a147381ea0d495b933275fe6bba75c114104a8ba410413e983dff004f5af5d34b4b4cde632d0bf1fd1592bdd91c6411f3934c2fa6af6b54975d106dcf4a65ae56e856001ebc03c7ce29dd9eef1ef10fc447dc9da76ad2aee93537a1ba7e4f70dd8eff0057c6dffb5e1a19854a83758e54528750946ec6704850cd037bceb08b6d7d2cc76d3317fc7b5cc04fb6707269c5c6e0c5b60ae549242123b0e493f602a075559e359970d98db89525456b51c951c8afa13ea8e98e3c596836783d5c63f5a61a99fdb7290875db4be88ab384bbbbbfc7183fdeaa633e8951db7da396dc48524fb1a8bd611a5aa2a2432f30ab420a7a6d3240c718cf031fa9ef4c9ad550205aa02951df4a1d6c8421b015b769db8c9229837ea2be8b1b0d39d0eba9c51484efdb8c0efd8d258daf3c449699f2edbd4584e7af9c64e3f96b9beb28d4ac40931e6478c8e76a24a825449501d867d2b1dcdebae99b9c752ae4ecd6dde4a179c1c1e460938f9149ef655e515c03919a289cb3dca278fb7bf177f4faa829dd8ce3f2ac9a7ecde490971fafd7dce15eed9b71c018c64fa514514b24e8e4f8c5c9b75c1e82579dc1233dfec08238f6add62d391acc1c5256a79e706d52d431c7a0145140b9fd149eb3a60dc5e88cbbc2da092411e9dc71f39a7766b447b344e847dcac9dcb5abba8d145061d43a6fcf1e65cf15d0e90231d3dd9cfe62995c6dcc5ca12a2c904a15f71dd27d451453e09d1a21450961cbb3ea8a956433b781f1ce33dfed54f0e2b50a2b71d84ed6db18028a28175f74fc6bda105c529a791c25c4f3c7a11f71586268f4a66b726e33de9ea6f1b52b181c760724e47b514520a5a28a283ffd9d81858ffa4686469676573744944096672616e646f6d58204599f81beaa2b20bd0ffcc9aa03a6f985befab3f6beaffa41e6354cdb2ab2ce471656c656d656e744964656e7469666965727264726976696e675f70726976696c656765736c656c656d656e7456616c756582a37576656869636c655f63617465676f72795f636f646561416a69737375655f64617465d903ec6a323031382d30382d30396b6578706972795f64617465d903ec6a323032342d31302d3230a37576656869636c655f63617465676f72795f636f646561426a69737375655f64617465d903ec6a323031372d30322d32336b6578706972795f64617465d903ec6a323032342d31302d32306a697373756572417574688443a10126a118215901d2308201ce30820174a003020102021401ec51916031e6898e8fc7864af5e6d5f86602b6300a06082a8648ce3d04030230233114301206035504030c0b75746f7069612069616361310b3009060355040613025553301e170d3230313030313030303030305a170d3231313030313030303030305a30213112301006035504030c0975746f706961206473310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004ace7ab7340e5d9648c5a72a9a6f56745c7aad436a03a43efea77b5fa7b88f0197d57d8983e1b37d3a539f4d588365e38cbbf5b94d68c547b5bc8731dcd2f146ba38187308184301e0603551d120417301581136578616d706c65406578616d706c652e636f6d301c0603551d1f041530133011a00fa00d820b6578616d706c652e636f6d301d0603551d0e0416041414e29017a6c35621ffc7a686b7b72db06cd12351300e0603551d0f0101ff04040302078030150603551d250101ff040b3009060728818c5d050102300a06082a8648ce3d0403020348003045022100bac6f93a8bacf0fc9aeac1c89a5c9293af2076942e9e972882a113640330702702207b7b73c0444371a4c94c9c888ddfe553ffde84ca492fd64dfbf02ad46a31cbc85903a2d81859039da66776657273696f6e63312e306f646967657374416c676f726974686d675348412d3235366c76616c756544696765737473a2716f72672e69736f2e31383031332e352e31ad00582075167333b47b6c2bfb86eccc1f438cf57af055371ac55e1e359e20f254adcebf01582067e539d6139ebd131aef441b445645dd831b2b375b390ca5ef6279b205ed45710258203394372ddb78053f36d5d869780e61eda313d44a392092ad8e0527a2fbfe55ae0358202e35ad3c4e514bb67b1a9db51ce74e4cb9b7146e41ac52dac9ce86b8613db555045820ea5c3304bb7c4a8dcb51c4c13b65264f845541341342093cca786e058fac2d59055820fae487f68b7a0e87a749774e56e9e1dc3a8ec7b77e490d21f0e1d3475661aa1d0658207d83e507ae77db815de4d803b88555d0511d894c897439f5774056416a1c7533075820f0549a145f1cf75cbeeffa881d4857dd438d627cf32174b1731c4c38e12ca936085820b68c8afcb2aaf7c581411d2877def155be2eb121a42bc9ba5b7312377e068f660958200b3587d1dd0c2a07a35bfb120d99a0abfb5df56865bb7fa15cc8b56a66df6e0c0a5820c98a170cf36e11abb724e98a75a5343dfa2b6ed3df2ecfbb8ef2ee55dd41c8810b5820b57dd036782f7b14c6a30faaaae6ccd5054ce88bdfa51a016ba75eda1edea9480c5820651f8736b18480fe252a03224ea087b5d10ca5485146c67c74ac4ec3112d4c3a746f72672e69736f2e31383031332e352e312e5553a4005820d80b83d25173c484c5640610ff1a31c949c1d934bf4cf7f18d5223b15dd4f21c0158204d80e1e2e4fb246d97895427ce7000bb59bb24c8cd003ecf94bf35bbd2917e340258208b331f3b685bca372e85351a25c9484ab7afcdf0d2233105511f778d98c2f544035820c343af1bd1690715439161aba73702c474abf992b20c9fb55c36a336ebe01a876d6465766963654b6579496e666fa1696465766963654b6579a40102200121582096313d6c63e24e3372742bfdb1a33ba2c897dcd68ab8c753e4fbd48dca6b7f9a2258201fb3269edd418857de1b39a4e4a44b92fa484caa722c228288f01d0c03a2c3d667646f6354797065756f72672e69736f2e31383031332e352e312e6d444c6c76616c6964697479496e666fa3667369676e6564c074323032302d31302d30315431333a33303a30325a6976616c696446726f6dc074323032302d31302d30315431333a33303a30325a6a76616c6964556e74696cc074323032312d31302d30315431333a33303a30325a5840cff12c17d4739aba806035a9cb2b34ae8a830cef4f329289f9a3ebd302dd6b99c584068257569397b92ba9aa5128554eb05d1273dafea313da4aff6b01a5fb3f6c6465766963655369676e6564a26a6e616d65537061636573d81841a06a64657669636541757468a1696465766963654d61638443a10105a0f65820200d73ded787c64652dc8ee743ea83a5260d5a3283fddc919b7b9cfb486addb26673746174757300" mdoc = MdocCbor() mdoc.loads(ISSUED_MDOC) -mdoc.verify() +# Fixture is expired and has no IACA; pin evaluation time and opt out of trust anchors for demos only. +from datetime import datetime, timezone +mdoc.verify( + allow_untrusted_issuer=True, + now=datetime(2020, 10, 1, 13, 30, 2, tzinfo=timezone.utc), +) >> True mdoc @@ -375,9 +380,11 @@ mdoc.disclosure_map >> ... dictionary containing all the disclosed attributes ... ```` +**Breaking change in 1.5.0:** `verify()` requires `trusted_root_certs` (IACA/root certificates as `Certificate`, PEM/DER bytes, or paths) unless you pass `allow_untrusted_issuer=True`. It also enforces MSO `validityInfo` and that the envelope `docType` matches the signed MSO `docType`. + ### Verify with Certificate Chain and Element Hashes -For production use, verify both the X.509 certificate chain and element hashes: +For production use, pass trusted roots. Verification also checks MSO validityInfo, docType, and element hashes by default: ````python # skip in doc examples (requires your_ca_cert.pem and device_response_bytes) @@ -385,7 +392,7 @@ from pymdoccbor.mdoc.verifier import MdocCbor from cryptography import x509 from cryptography.hazmat.backends import default_backend -# Load trusted root certificates +# Load trusted root certificates (PEM/DER bytes and file paths are also accepted) with open('your_ca_cert.pem', 'rb') as f: iaca_cert = x509.load_pem_x509_certificate(f.read(), default_backend()) @@ -409,7 +416,7 @@ BIN_ISSUED_MDOC = binascii.unhexlify(ISSUED_MDOC) mdoc = cbor2.loads(BIN_ISSUED_MDOC) msop = MsoVerifier(mdoc['documents'][0]['issuerSigned']['issuerAuth']) -msop.verify_signature() +msop.verify_signature(allow_untrusted_issuer=True) ```` API usage: diff --git a/docs/CERTIFICATE-CHAIN-VERIFICATION.md b/docs/CERTIFICATE-CHAIN-VERIFICATION.md index 31bab57..c4f96eb 100644 --- a/docs/CERTIFICATE-CHAIN-VERIFICATION.md +++ b/docs/CERTIFICATE-CHAIN-VERIFICATION.md @@ -4,16 +4,24 @@ pyMDOC-CBOR supports comprehensive mDOC verification including: -1. **X.509 Certificate Chain Verification** - Validates that mDOC documents are signed by trusted authorities -2. **Element Hash Verification** - Ensures disclosed data elements match their cryptographic hashes in the MSO +1. **X.509 Certificate Chain Verification** - Validates that mDOC documents are signed by trusted authorities (required by default since 1.5.0) +2. **MSO validityInfo and docType checks** - Enforces the MSO time window and envelope/MSO docType match +3. **Element Hash Verification** - Ensures disclosed data elements match their cryptographic hashes in the MSO ### What is Verified -**Certificate Chain:** +**Certificate Chain (required by default since 1.5.0):** - The Document Signer (DS) certificate is signed by a trusted root certificate - The DS certificate is within its validity period - The signature algorithm matches expectations +**MSO validityInfo (ISO 18013-5 §9.3 step 5):** +- `validFrom - skew <= now <= validUntil + skew` (default skew 60 seconds) +- When a DS certificate is loaded, `signed` must lie within the DS certificate validity period + +**Envelope docType (ISO 18013-5 §9.3 step 4):** +- The unsigned Document `docType` must match the signed MSO `docType` + **Element Hashes:** - Each disclosed `IssuerSignedItem` matches its SHA-256 hash in the MSO's `valueDigests` - Hashes are computed on the complete CBOR Tag 24 structure (as per ISO 18013-5 §9.1.2.4) @@ -21,22 +29,7 @@ pyMDOC-CBOR supports comprehensive mDOC verification including: ## Usage -### Basic Verification (Signature Only) - -```python -# skip in doc examples (requires device_response_bytes from previous context) -from pymdoccbor.mdoc.verifier import MdocCbor - -mdoc = MdocCbor() -mdoc.loads(device_response_bytes) - -# Verify signatures only (no certificate chain validation, but hash verification enabled) -is_valid = mdoc.verify() -``` - -**Note:** This mode verifies cryptographic signatures and element hashes, but does not validate the certificate chain. A warning will be logged about certificate chain validation. - -### Full Verification (Recommended) +### Full Verification (Required for Production) ```python # skip in doc examples (requires device_response_bytes and iaca_cert.pem) @@ -44,19 +37,36 @@ from pymdoccbor.mdoc.verifier import MdocCbor from cryptography import x509 from cryptography.hazmat.backends import default_backend -# Load trusted root certificates (IACA certificates) +# Load trusted root certificates (IACA certificates). +# Certificate objects, PEM/DER bytes, and file paths are accepted. with open('iaca_cert.pem', 'rb') as f: iaca_cert = x509.load_pem_x509_certificate(f.read(), default_backend()) trusted_certs = [iaca_cert] -# Verify with certificate chain validation AND hash verification mdoc = MdocCbor() mdoc.loads(device_response_bytes) is_valid = mdoc.verify(trusted_root_certs=trusted_certs, verify_hashes=True) if is_valid: - print("Document signature, certificate chain, and element hashes are all valid") + print("Document signature, certificate chain, validityInfo, docType, and hashes are valid") +``` + +Calling `verify()` without roots raises `TrustedRootRequired` (caught by `MdocCbor.verify`, which returns `False` and records the document as invalid). + +### Explicit Opt-Out of Issuer Trust Anchors + +Use only when the caller performs trust evaluation elsewhere: + +```python +# skip in doc examples (requires device_response_bytes from previous context) +from pymdoccbor.mdoc.verifier import MdocCbor + +mdoc = MdocCbor() +mdoc.loads(device_response_bytes) + +# Still checks COSE signature, validityInfo, docType, and hashes +is_valid = mdoc.verify(allow_untrusted_issuer=True) ``` ### Verification Options @@ -66,14 +76,14 @@ if is_valid: # Full verification (default) mdoc.verify(trusted_root_certs=trusted_certs, verify_hashes=True) -# Skip hash verification (only check signatures and certificate chain) +# Skip hash verification (only check signatures, chain, validityInfo, docType) mdoc.verify(trusted_root_certs=trusted_certs, verify_hashes=False) -# Skip certificate chain validation (only check signatures and hashes) -mdoc.verify(verify_hashes=True) +# Explicitly skip issuer trust anchors (not recommended for production) +mdoc.verify(allow_untrusted_issuer=True, verify_hashes=True) -# Only signature verification (not recommended for production) -mdoc.verify(verify_hashes=False) +# Signature + validityInfo + docType only (not recommended for production) +mdoc.verify(allow_untrusted_issuer=True, verify_hashes=False) ``` ### Accessing Verification Results @@ -366,12 +376,12 @@ except ValueError as e: ## Security Considerations -1. **Always provide trusted root certificates** in production environments +1. **Always provide trusted root certificates** in production environments (`trusted_root_certs` is required unless `allow_untrusted_issuer=True`) 2. **Always enable hash verification** (`verify_hashes=True`) in production 3. **Keep root certificates up to date** - expired roots will cause validation failures -4. **Verify certificate validity dates** - the library checks `not_valid_before_utc` and `not_valid_after_utc` +4. **Verify certificate validity dates** - the library checks DS `not_valid_before_utc` / `not_valid_after_utc` and MSO `validityInfo` 5. **Use official IACA certificates** from trusted sources (government authorities, standards bodies) -6. **Never skip validations** in production - warnings are for testing only +6. **Never set `allow_untrusted_issuer=True` in production** unless the application performs equivalent issuer authentication 7. **Check hash verification results** - a single failed hash indicates potential tampering ### Why Hash Verification Matters @@ -416,31 +426,39 @@ is_valid = mdoc.verify(trusted_root_certs=trusted_certs) ## API Reference -### `MdocCbor.verify(trusted_root_certs=None, verify_hashes=True)` +### `MdocCbor.verify(trusted_root_certs=None, verify_hashes=True, allow_untrusted_issuer=False, now=None, clock_skew_seconds=60)` Verify all documents in the mDOC. **Parameters:** -- `trusted_root_certs` (list, optional): List of `cryptography.x509.Certificate` objects representing trusted root certificates. If `None`, certificate chain validation is skipped. -- `verify_hashes` (bool, optional): If `True` (default), verify element hashes against MSO valueDigests. Set to `False` to skip hash verification. +- `trusted_root_certs` (list, optional): Trusted roots as `Certificate` objects, PEM/DER bytes, or file paths. Required unless `allow_untrusted_issuer=True`. +- `verify_hashes` (bool, optional): If `True` (default), verify element hashes against MSO valueDigests. +- `allow_untrusted_issuer` (bool, optional): If `True`, skip X.509 chain validation when no roots are supplied. Default `False` (fail closed). +- `now` (datetime, optional): Evaluation time for MSO `validityInfo`. Defaults to current UTC time. +- `clock_skew_seconds` (int, optional): Allowed skew around `validFrom` / `validUntil`. Default `60`. **Returns:** - `bool`: `True` if all documents are valid, `False` otherwise -**Raises:** -- `ValueError`: If certificate chain validation fails +**Notes:** +- Per-document failures (including missing roots, expired MSO, or docType mismatch) are recorded in `documents_invalid`. -### `MobileDocument.verify(trusted_root_certs=None, verify_hashes=True)` +### `MobileDocument.verify(trusted_root_certs=None, verify_hashes=True, allow_untrusted_issuer=False, now=None, clock_skew_seconds=60)` Verify a single document. **Parameters:** -- `trusted_root_certs` (list, optional): List of trusted root certificates -- `verify_hashes` (bool, optional): If `True` (default), verify element hashes +- Same as `MdocCbor.verify` **Returns:** - `bool`: `True` if the document is valid, `False` otherwise +**Raises:** +- `TrustedRootRequired`: If no roots are supplied and `allow_untrusted_issuer` is false +- `MsoValidityError`: If MSO `validityInfo` is outside the allowed window +- `DocTypeMismatchError`: If envelope `docType` does not match the signed MSO `docType` +- `ValueError`: If certificate chain validation fails + ### `MsoVerifier.verified_root` After calling `verify()` with `trusted_root_certs`, this attribute contains the trusted root certificate that successfully verified the DS certificate. @@ -473,18 +491,20 @@ Verify element hashes against MSO valueDigests. **Returns:** - `dict`: Verification results with keys: `valid`, `total`, `verified`, `failed` -## Backward Compatibility - -Both verification features are fully backward compatible: +## Breaking Changes in 1.5.0 **Certificate Chain Verification:** -- Existing code that calls `verify()` without `trusted_root_certs` will continue to work -- A warning message will be logged recommending to enable chain validation +- Calling `verify()` without `trusted_root_certs` now fails closed +- Callers that intentionally skip issuer trust must pass `allow_untrusted_issuer=True` +- Root inputs may be `Certificate`, PEM/DER bytes, or paths + +**Additional checks always run after a successful signature:** +- MSO `validityInfo` (`validFrom` / `validUntil`, optional `signed` vs DS cert) +- Envelope `docType` vs signed MSO `docType` **Hash Verification:** -- Enabled by default (`verify_hashes=True`) -- Can be disabled by passing `verify_hashes=False` for backward compatibility -- Does not break existing code +- Still enabled by default (`verify_hashes=True`) +- Can be disabled by passing `verify_hashes=False` ## Complete Example diff --git a/docs/CREATE-MSO.md b/docs/CREATE-MSO.md index 140ace0..4fbd56b 100644 --- a/docs/CREATE-MSO.md +++ b/docs/CREATE-MSO.md @@ -74,6 +74,6 @@ encoded = msg.encode() decoded = Sign1Message.decode(encoded) decoded.key = cose_key -decoded.verify_signature() +decoded.verify_signature(allow_untrusted_issuer=True) ```` diff --git a/docs/DIAGN-VALIDATE.md b/docs/DIAGN-VALIDATE.md index 0159751..bf74424 100644 --- a/docs/DIAGN-VALIDATE.md +++ b/docs/DIAGN-VALIDATE.md @@ -245,7 +245,7 @@ key = CoseKey.from_dict(cbor2.loads(cbor2.loads(ia[2]).value)['deviceKeyInfo'][' # OR BETTER decoded = Sign1Message.decode(cbor2.dumps(cbor2.CBORTag(18, value=ia))) # decoded.key = key -# decoded.verify_signature() +# decoded.verify_signature(allow_untrusted_issuer=True) # x509 certificate chain is here decoded.uhdr @@ -280,7 +280,7 @@ COSEKEY_HAZMAT_CRV_MAP = { key = EC2Key(crv=COSEKEY_HAZMAT_CRV_MAP[_key.curve.name], x=_key.public_numbers().x.to_bytes(32, 'big')) decoded.key = key -decoded.verify_signature() +decoded.verify_signature(allow_untrusted_issuer=True) ```` diff --git a/examples/it_data_model.py b/examples/it_data_model.py index 883b055..e15bb0b 100644 --- a/examples/it_data_model.py +++ b/examples/it_data_model.py @@ -76,6 +76,5 @@ }, ) -mdoc mdoci.dump() mdoci.dumps() \ No newline at end of file diff --git a/pymdoccbor/__init__.py b/pymdoccbor/__init__.py index 3e8d9f9..5b60188 100644 --- a/pymdoccbor/__init__.py +++ b/pymdoccbor/__init__.py @@ -1 +1 @@ -__version__ = "1.4.0" +__version__ = "1.5.0" diff --git a/pymdoccbor/exceptions.py b/pymdoccbor/exceptions.py index 115683b..336ef5d 100644 --- a/pymdoccbor/exceptions.py +++ b/pymdoccbor/exceptions.py @@ -14,3 +14,15 @@ class MsoPrivateKeyRequired(Exception): class MsoX509ChainNotFound(Exception): pass + + +class TrustedRootRequired(ValueError): + """Raised when issuer trust-anchor validation is required but no roots were supplied.""" + + +class MsoValidityError(ValueError): + """Raised when MSO validityInfo fails the time window or DS certificate checks.""" + + +class DocTypeMismatchError(ValueError): + """Raised when the unsigned envelope docType does not match the signed MSO docType.""" diff --git a/pymdoccbor/mdoc/verifier.py b/pymdoccbor/mdoc/verifier.py index bba6ed8..7ae41bc 100644 --- a/pymdoccbor/mdoc/verifier.py +++ b/pymdoccbor/mdoc/verifier.py @@ -1,14 +1,17 @@ # Aligns with https://github.com/eu-digital-identity-wallet/pyMDOC-CBOR import binascii import logging -from typing import List +from datetime import datetime +from typing import List, Sequence import cbor2 -from pymdoccbor.exceptions import InvalidMdoc +from pymdoccbor.exceptions import DocTypeMismatchError, InvalidMdoc from pymdoccbor.mdoc.exceptions import (NoDocumentTypeProvided, NoSignedDocumentProvided) from pymdoccbor.mdoc.issuersigned import IssuerSigned +from pymdoccbor.mso.verifier import DEFAULT_CLOCK_SKEW_SECONDS +from pymdoccbor.x509 import X509ChainSource logger = logging.getLogger('pymdoccbor') @@ -77,21 +80,52 @@ def dump(self) -> bytes: ) ) - def verify(self, trusted_root_certs: list = None, verify_hashes: bool = True) -> bool: + def verify( + self, + trusted_root_certs: Sequence[X509ChainSource] | None = None, + verify_hashes: bool = True, + allow_untrusted_issuer: bool = False, + now: datetime | None = None, + clock_skew_seconds: int = DEFAULT_CLOCK_SKEW_SECONDS, + ) -> bool: """ - Verify the document signature and optionally element hashes + Verify the document signature, MSO validityInfo, docType, and optionally hashes. Args: - trusted_root_certs: List of trusted root certificates for chain validation + trusted_root_certs: Trusted root certificates (Certificate, PEM/DER + bytes, or paths). Required unless allow_untrusted_issuer. verify_hashes: If True, also verify element hashes against MSO - :return: bool: True if the signature is valid, False otherwise + allow_untrusted_issuer: Skip issuer chain validation when no roots + now: Evaluation time for validityInfo (UTC) + clock_skew_seconds: Allowed skew for validityInfo checks + :return: bool: True if the document is valid, False otherwise """ - # Verify signature - self.is_valid = self.issuersigned.issuer_auth.verify_signature(trusted_root_certs) + issuer_auth = self.issuersigned.issuer_auth + + # Verify signature (and issuer trust anchors unless explicitly skipped) + self.is_valid = issuer_auth.verify_signature( + trusted_root_certs, + allow_untrusted_issuer=allow_untrusted_issuer, + ) + + if self.is_valid: + # ISO 18013-5 §9.3 step 5 — MSO validityInfo + issuer_auth.verify_validity_info( + now=now, + clock_skew_seconds=clock_skew_seconds, + ) + + # ISO 18013-5 §9.3 step 4 — envelope docType must match MSO + mso_doctype = issuer_auth.payload_as_dict.get("docType") + if mso_doctype != self.doctype: + raise DocTypeMismatchError( + f"Envelope docType {self.doctype!r} does not match " + f"MSO docType {mso_doctype!r}" + ) # Verify element hashes if requested if verify_hashes and self.is_valid: - hash_results = self.issuersigned.issuer_auth.verify_element_hashes( + hash_results = issuer_auth.verify_element_hashes( self.issuersigned.namespaces ) self.hash_verification = hash_results @@ -181,14 +215,24 @@ def _decode_claims(self, claims: list[dict]) -> dict: return decoded_claims - def verify(self, trusted_root_certs: list = None, verify_hashes: bool = True) -> bool: + def verify( + self, + trusted_root_certs: Sequence[X509ChainSource] | None = None, + verify_hashes: bool = True, + allow_untrusted_issuer: bool = False, + now: datetime | None = None, + clock_skew_seconds: int = DEFAULT_CLOCK_SKEW_SECONDS, + ) -> bool: """ Verify signatures of all documents contained in the mdoc Args: - trusted_root_certs: List of trusted root certificates (x509.Certificate objects) - for chain validation. If None, skips chain validation. + trusted_root_certs: Trusted root certificates (Certificate objects, + PEM/DER bytes, or paths). Required unless allow_untrusted_issuer. verify_hashes: If True, also verify element hashes against MSO valueDigests + allow_untrusted_issuer: Skip issuer chain validation when no roots + now: Evaluation time for validityInfo (UTC) + clock_skew_seconds: Allowed skew for validityInfo checks :return: bool: True if all signatures are valid, False otherwise """ cdict = self.data_as_cbor_dict @@ -204,7 +248,13 @@ def verify(self, trusted_root_certs: list = None, verify_hashes: bool = True) -> mso = MobileDocument(**doc) try: - if mso.verify(trusted_root_certs, verify_hashes): + if mso.verify( + trusted_root_certs, + verify_hashes, + allow_untrusted_issuer=allow_untrusted_issuer, + now=now, + clock_skew_seconds=clock_skew_seconds, + ): self.documents.append(mso) else: self.documents_invalid.append(mso) diff --git a/pymdoccbor/mso/verifier.py b/pymdoccbor/mso/verifier.py index e165d5e..54a8084 100644 --- a/pymdoccbor/mso/verifier.py +++ b/pymdoccbor/mso/verifier.py @@ -1,22 +1,58 @@ # Aligns with https://github.com/eu-digital-identity-wallet/pyMDOC-CBOR import hashlib import logging -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone from typing import Sequence, Union import cbor2 import cryptography from cryptography.exceptions import InvalidSignature +from cryptography.x509 import Certificate from pycose.keys import EC2Key from pycose.messages import Sign1Message from pymdoccbor import settings -from pymdoccbor.exceptions import (MsoX509ChainNotFound, - UnsupportedMsoDataFormat) +from pymdoccbor.exceptions import ( + MsoValidityError, + MsoX509ChainNotFound, + TrustedRootRequired, + UnsupportedMsoDataFormat, +) from pymdoccbor.tools import bytes2CoseSign1, cborlist2CoseSign1 +from pymdoccbor.x509 import X509ChainSource, load_x509_certificates_from_source logger = logging.getLogger("pymdoccbor") +DEFAULT_CLOCK_SKEW_SECONDS = 60 + + +def _as_utc(value) -> datetime: + """Normalize a datetime or CBOR date/time value to timezone-aware UTC.""" + if isinstance(value, cbor2.CBORTag): + value = value.value + if isinstance(value, str): + value = datetime.fromisoformat(value.replace("Z", "+00:00")) + if not isinstance(value, datetime): + raise MsoValidityError(f"Unsupported validityInfo timestamp type: {type(value)}") + if value.tzinfo is None: + return value.replace(tzinfo=timezone.utc) + return value.astimezone(timezone.utc) + + +def normalize_trusted_root_certs( + trusted_root_certs: Sequence[X509ChainSource] | None, +) -> list[Certificate]: + """ + Expand Certificate / PEM/DER bytes / path sources into Certificate objects. + """ + if not trusted_root_certs: + return [] + + roots: list[Certificate] = [] + for source in trusted_root_certs: + roots.extend(load_x509_certificates_from_source(source)) + return roots + class MsoVerifier: """ @@ -123,23 +159,38 @@ def raw_public_keys(self) -> list[Union[bytes, dict]]: "in this MSO." ) - def attest_public_key(self, trusted_root_certs: list = None): + def attest_public_key( + self, + trusted_root_certs: Sequence[X509ChainSource] | None = None, + allow_untrusted_issuer: bool = False, + ): """ Verify the X.509 certificate chain. Args: - trusted_root_certs: List of trusted root certificates (x509.Certificate objects) - If None, skips chain validation (backward compatible) + trusted_root_certs: Trusted root certificates (Certificate, PEM/DER + bytes, or file paths). Required unless allow_untrusted_issuer. + allow_untrusted_issuer: If True, skip chain validation when no roots + are supplied. Default False (fail closed). Returns: - The trusted root certificate that signed the DS cert, or None if validation skipped + The trusted root certificate that signed the DS cert, or None if + validation was explicitly skipped. """ - if trusted_root_certs is None: - logger.warning( - "Certificate chain validation skipped. " - "Pass trusted_root_certs parameter to verify() to enable X.509 chain validation." + roots = normalize_trusted_root_certs(trusted_root_certs) + + if not roots: + if allow_untrusted_issuer: + logger.warning( + "Certificate chain validation skipped. " + "Pass trusted_root_certs to enable X.509 chain validation." + ) + return None + raise TrustedRootRequired( + "trusted_root_certs is required for issuer authentication. " + "Pass IACA/root certificates, or set allow_untrusted_issuer=True " + "only if the caller performs trust evaluation elsewhere." ) - return None # Load DS certificate (first in chain) ds_cert = self.x509_certificates[0] if self.x509_certificates else None @@ -148,7 +199,7 @@ def attest_public_key(self, trusted_root_certs: list = None): # Verify DS cert is signed by one of the trusted roots verified_root = None - for root_cert in trusted_root_certs: + for root_cert in roots: try: # Verify signature root_cert.public_key().verify( @@ -182,12 +233,17 @@ def attest_public_key(self, trusted_root_certs: list = None): logger.info("Certificate chain and validity verified successfully") return verified_root - def load_public_key(self, trusted_root_certs: list = None) -> None: + def load_public_key( + self, + trusted_root_certs: Sequence[X509ChainSource] | None = None, + allow_untrusted_issuer: bool = False, + ) -> None: """ Load the public key from the x509 certificate Args: - trusted_root_certs: List of trusted root certificates for chain validation + trusted_root_certs: Trusted root certificates for chain validation + allow_untrusted_issuer: Skip chain validation when no roots supplied :return: None """ for i in self.raw_public_keys: @@ -195,7 +251,10 @@ def load_public_key(self, trusted_root_certs: list = None) -> None: cryptography.x509.load_der_x509_certificate(i) ) - self.verified_root = self.attest_public_key(trusted_root_certs) + self.verified_root = self.attest_public_key( + trusted_root_certs, + allow_untrusted_issuer=allow_untrusted_issuer, + ) self.public_key = self.x509_certificates[0].public_key() @@ -210,19 +269,91 @@ def load_public_key(self, trusted_root_certs: list = None) -> None: ) self.object.key = key - def verify_signature(self, trusted_root_certs: list = None) -> bool: + def verify_signature( + self, + trusted_root_certs: Sequence[X509ChainSource] | None = None, + allow_untrusted_issuer: bool = False, + ) -> bool: """" Verify the signature of the MSO Args: - trusted_root_certs: List of trusted root certificates for chain validation + trusted_root_certs: Trusted root certificates for chain validation + allow_untrusted_issuer: Skip chain validation when no roots supplied :return: bool: True if the signature is valid, False otherwise """ if not self.object.key: - self.load_public_key(trusted_root_certs) + self.load_public_key( + trusted_root_certs, + allow_untrusted_issuer=allow_untrusted_issuer, + ) return self.object.verify_signature() + def verify_validity_info( + self, + now: datetime | None = None, + clock_skew_seconds: int = DEFAULT_CLOCK_SKEW_SECONDS, + ds_cert: Certificate | None = None, + ) -> bool: + """ + Enforce MSO validityInfo against the current time (ISO 18013-5 §9.3 step 5). + + Args: + now: Evaluation time (UTC). Defaults to datetime.now(timezone.utc). + clock_skew_seconds: Allowed skew around validFrom / validUntil. + ds_cert: Optional DS certificate. When provided (or already loaded on + self.x509_certificates), also checks that validityInfo.signed lies + within the DS certificate validity period. + + Returns: + True if validityInfo is acceptable. + + Raises: + MsoValidityError: If validityInfo is missing or outside the window. + """ + mso_data = self.payload_as_dict + validity_info = mso_data.get("validityInfo") + if not isinstance(validity_info, dict): + raise MsoValidityError("MSO payload is missing validityInfo") + + try: + valid_from = _as_utc(validity_info["validFrom"]) + valid_until = _as_utc(validity_info["validUntil"]) + signed = _as_utc(validity_info["signed"]) + except KeyError as exc: + raise MsoValidityError( + f"MSO validityInfo is missing required field: {exc.args[0]}" + ) from exc + + if now is None: + now = datetime.now(timezone.utc) + else: + now = _as_utc(now) + + skew = timedelta(seconds=max(0, clock_skew_seconds)) + + if now < (valid_from - skew): + raise MsoValidityError( + f"MSO not yet valid (validFrom {valid_from}, now {now})" + ) + if now > (valid_until + skew): + raise MsoValidityError( + f"MSO expired (validUntil {valid_until}, now {now})" + ) + + cert = ds_cert or (self.x509_certificates[0] if self.x509_certificates else None) + if cert is not None: + not_before = cert.not_valid_before_utc + not_after = cert.not_valid_after_utc + if signed < (not_before - skew) or signed > (not_after + skew): + raise MsoValidityError( + f"MSO signed time {signed} is outside DS certificate validity " + f"[{not_before}, {not_after}]" + ) + + return True + def verify_element_hashes(self, namespaces: dict) -> dict: """ Verify that disclosed elements match their hashes in the MSO. diff --git a/pymdoccbor/tests/test_01_mdoc_parser.py b/pymdoccbor/tests/test_01_mdoc_parser.py index ffafd5c..102823c 100644 --- a/pymdoccbor/tests/test_01_mdoc_parser.py +++ b/pymdoccbor/tests/test_01_mdoc_parser.py @@ -1,14 +1,18 @@ +from datetime import datetime, timezone from pymdoccbor.mdoc.verifier import MdocCbor from pymdoccbor.tools import pretty_print +# Fixture MSO validityInfo is fixed at issuance time (2020-10-01 .. 2021-10-01). +_FIXTURE_NOW = datetime(2020, 10, 1, 13, 30, 2, tzinfo=timezone.utc) + ISSUED_MDOC = "a36776657273696f6e63312e3069646f63756d656e747381a367646f6354797065756f72672e69736f2e31383031332e352e312e6d444c6c6973737565725369676e6564a26a6e616d65537061636573a1716f72672e69736f2e31383031332e352e3186d8185863a4686469676573744944006672616e646f6d58208798645b20ea200e19ffabac92624bee6aec63aceedecfb1b80077d22bfc20e971656c656d656e744964656e7469666965726b66616d696c795f6e616d656c656c656d656e7456616c756563446f65d818586ca4686469676573744944036672616e646f6d5820b23f627e8999c706df0c0a4ed98ad74af988af619b4bb078b89058553f44615d71656c656d656e744964656e7469666965726a69737375655f646174656c656c656d656e7456616c7565d903ec6a323031392d31302d3230d818586da4686469676573744944046672616e646f6d5820c7ffa307e5de921e67ba5878094787e8807ac8e7b5b3932d2ce80f00f3e9abaf71656c656d656e744964656e7469666965726b6578706972795f646174656c656c656d656e7456616c7565d903ec6a323032342d31302d3230d818586da4686469676573744944076672616e646f6d582026052a42e5880557a806c1459af3fb7eb505d3781566329d0b604b845b5f9e6871656c656d656e744964656e7469666965726f646f63756d656e745f6e756d6265726c656c656d656e7456616c756569313233343536373839d818590471a4686469676573744944086672616e646f6d5820d094dad764a2eb9deb5210e9d899643efbd1d069cc311d3295516ca0b024412d71656c656d656e744964656e74696669657268706f7274726169746c656c656d656e7456616c7565590412ffd8ffe000104a46494600010101009000900000ffdb004300130d0e110e0c13110f11151413171d301f1d1a1a1d3a2a2c2330453d4947443d43414c566d5d4c51685241435f82606871757b7c7b4a5c869085778f6d787b76ffdb0043011415151d191d381f1f38764f434f7676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676767676ffc00011080018006403012200021101031101ffc4001b00000301000301000000000000000000000005060401020307ffc400321000010303030205020309000000000000010203040005110612211331141551617122410781a1163542527391b2c1f1ffc4001501010100000000000000000000000000000001ffc4001a110101010003010000000000000000000000014111213161ffda000c03010002110311003f00a5bbde22da2329c7d692bc7d0d03f52cfb0ff75e7a7ef3e7709723a1d0dae146ddfbb3c039ce07ad2bd47a7e32dbb8dd1d52d6ef4b284f64a480067dfb51f87ffb95ff00eb9ff14d215de66af089ce44b7dbde9cb6890a2838eddf18078f7add62d411ef4db9b10a65d6b95a147381ea0d495b933275fe6bba75c114104a8ba410413e983dff004f5af5d34b4b4cde632d0bf1fd1592bdd91c6411f3934c2fa6af6b54975d106dcf4a65ae56e856001ebc03c7ce29dd9eef1ef10fc447dc9da76ad2aee93537a1ba7e4f70dd8eff0057c6dffb5e1a19854a83758e54528750946ec6704850cd037bceb08b6d7d2cc76d3317fc7b5cc04fb6707269c5c6e0c5b60ae549242123b0e493f602a075559e359970d98db89525456b51c951c8afa13ea8e98e3c596836783d5c63f5a61a99fdb7290875db4be88ab384bbbbbfc7183fdeaa633e8951db7da396dc48524fb1a8bd611a5aa2a2432f30ab420a7a6d3240c718cf031fa9ef4c9ad550205aa02951df4a1d6c8421b015b769db8c9229837ea2be8b1b0d39d0eba9c51484efdb8c0efd8d258daf3c449699f2edbd4584e7af9c64e3f96b9beb28d4ac40931e6478c8e76a24a825449501d867d2b1dcdebae99b9c752ae4ecd6dde4a179c1c1e460938f9149ef655e515c03919a289cb3dca278fb7bf177f4faa829dd8ce3f2ac9a7ecde490971fafd7dce15eed9b71c018c64fa514514b24e8e4f8c5c9b75c1e82579dc1233dfec08238f6add62d391acc1c5256a79e706d52d431c7a0145140b9fd149eb3a60dc5e88cbbc2da092411e9dc71f39a7766b447b344e847dcac9dcb5abba8d145061d43a6fcf1e65cf15d0e90231d3dd9cfe62995c6dcc5ca12a2c904a15f71dd27d451453e09d1a21450961cbb3ea8a956433b781f1ce33dfed54f0e2b50a2b71d84ed6db18028a28175f74fc6bda105c529a791c25c4f3c7a11f71586268f4a66b726e33de9ea6f1b52b181c760724e47b514520a5a28a283ffd9d81858ffa4686469676573744944096672616e646f6d58204599f81beaa2b20bd0ffcc9aa03a6f985befab3f6beaffa41e6354cdb2ab2ce471656c656d656e744964656e7469666965727264726976696e675f70726976696c656765736c656c656d656e7456616c756582a37576656869636c655f63617465676f72795f636f646561416a69737375655f64617465d903ec6a323031382d30382d30396b6578706972795f64617465d903ec6a323032342d31302d3230a37576656869636c655f63617465676f72795f636f646561426a69737375655f64617465d903ec6a323031372d30322d32336b6578706972795f64617465d903ec6a323032342d31302d32306a697373756572417574688443a10126a118215901d2308201ce30820174a003020102021401ec51916031e6898e8fc7864af5e6d5f86602b6300a06082a8648ce3d04030230233114301206035504030c0b75746f7069612069616361310b3009060355040613025553301e170d3230313030313030303030305a170d3231313030313030303030305a30213112301006035504030c0975746f706961206473310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004ace7ab7340e5d9648c5a72a9a6f56745c7aad436a03a43efea77b5fa7b88f0197d57d8983e1b37d3a539f4d588365e38cbbf5b94d68c547b5bc8731dcd2f146ba38187308184301e0603551d120417301581136578616d706c65406578616d706c652e636f6d301c0603551d1f041530133011a00fa00d820b6578616d706c652e636f6d301d0603551d0e0416041414e29017a6c35621ffc7a686b7b72db06cd12351300e0603551d0f0101ff04040302078030150603551d250101ff040b3009060728818c5d050102300a06082a8648ce3d0403020348003045022100bac6f93a8bacf0fc9aeac1c89a5c9293af2076942e9e972882a113640330702702207b7b73c0444371a4c94c9c888ddfe553ffde84ca492fd64dfbf02ad46a31cbc85903a2d81859039da66776657273696f6e63312e306f646967657374416c676f726974686d675348412d3235366c76616c756544696765737473a2716f72672e69736f2e31383031332e352e31ad00582075167333b47b6c2bfb86eccc1f438cf57af055371ac55e1e359e20f254adcebf01582067e539d6139ebd131aef441b445645dd831b2b375b390ca5ef6279b205ed45710258203394372ddb78053f36d5d869780e61eda313d44a392092ad8e0527a2fbfe55ae0358202e35ad3c4e514bb67b1a9db51ce74e4cb9b7146e41ac52dac9ce86b8613db555045820ea5c3304bb7c4a8dcb51c4c13b65264f845541341342093cca786e058fac2d59055820fae487f68b7a0e87a749774e56e9e1dc3a8ec7b77e490d21f0e1d3475661aa1d0658207d83e507ae77db815de4d803b88555d0511d894c897439f5774056416a1c7533075820f0549a145f1cf75cbeeffa881d4857dd438d627cf32174b1731c4c38e12ca936085820b68c8afcb2aaf7c581411d2877def155be2eb121a42bc9ba5b7312377e068f660958200b3587d1dd0c2a07a35bfb120d99a0abfb5df56865bb7fa15cc8b56a66df6e0c0a5820c98a170cf36e11abb724e98a75a5343dfa2b6ed3df2ecfbb8ef2ee55dd41c8810b5820b57dd036782f7b14c6a30faaaae6ccd5054ce88bdfa51a016ba75eda1edea9480c5820651f8736b18480fe252a03224ea087b5d10ca5485146c67c74ac4ec3112d4c3a746f72672e69736f2e31383031332e352e312e5553a4005820d80b83d25173c484c5640610ff1a31c949c1d934bf4cf7f18d5223b15dd4f21c0158204d80e1e2e4fb246d97895427ce7000bb59bb24c8cd003ecf94bf35bbd2917e340258208b331f3b685bca372e85351a25c9484ab7afcdf0d2233105511f778d98c2f544035820c343af1bd1690715439161aba73702c474abf992b20c9fb55c36a336ebe01a876d6465766963654b6579496e666fa1696465766963654b6579a40102200121582096313d6c63e24e3372742bfdb1a33ba2c897dcd68ab8c753e4fbd48dca6b7f9a2258201fb3269edd418857de1b39a4e4a44b92fa484caa722c228288f01d0c03a2c3d667646f6354797065756f72672e69736f2e31383031332e352e312e6d444c6c76616c6964697479496e666fa3667369676e6564c074323032302d31302d30315431333a33303a30325a6976616c696446726f6dc074323032302d31302d30315431333a33303a30325a6a76616c6964556e74696cc074323032312d31302d30315431333a33303a30325a5840cff12c17d4739aba806035a9cb2b34ae8a830cef4f329289f9a3ebd302dd6b99c584068257569397b92ba9aa5128554eb05d1273dafea313da4aff6b01a5fb3f6c6465766963655369676e6564a26a6e616d65537061636573d81841a06a64657669636541757468a1696465766963654d61638443a10105a0f65820200d73ded787c64652dc8ee743ea83a5260d5a3283fddc919b7b9cfb486addb26673746174757300" def test_parse_mdoc_af_binary(): mdoc = MdocCbor() mdoc.loads(ISSUED_MDOC) - mdoc.verify() + mdoc.verify(allow_untrusted_issuer=True, now=_FIXTURE_NOW) for i in mdoc.documents: assert i.is_valid @@ -23,7 +27,7 @@ def test_parse_mdoc_af_binary(): # testing from export re-import mdoc2 = MdocCbor() mdoc2.loads(mdoc.data_as_bytes) - mdoc2.verify() + mdoc2.verify(allow_untrusted_issuer=True, now=_FIXTURE_NOW) for i in mdoc.documents: assert i.is_valid @@ -43,7 +47,7 @@ def test_parse_mdoc_break(): mdoc_break = MdocCbor() mdoc_break.loads(_breaked_mso) - assert mdoc_break.verify() is False + assert mdoc_break.verify(allow_untrusted_issuer=True, now=_FIXTURE_NOW) is False assert mdoc_break.documents_invalid[0].is_valid is False diff --git a/pymdoccbor/tests/test_02_mdoc_issuer.py b/pymdoccbor/tests/test_02_mdoc_issuer.py index 87edd65..a7b9029 100644 --- a/pymdoccbor/tests/test_02_mdoc_issuer.py +++ b/pymdoccbor/tests/test_02_mdoc_issuer.py @@ -22,7 +22,7 @@ def extract_mso(mdoc: dict): def test_mso_writer(): - validity = {"issuance_date": "2025-01-17", "expiry_date": "2025-11-13"} + validity = {"issuance_date": "2025-01-17", "expiry_date": "2030-11-13"} msoi = MsoIssuer( data=PID_DATA, private_key=PKEY, @@ -45,7 +45,7 @@ def test_mso_writer(): def test_mdoc_issuer(): - validity = {"issuance_date": "2025-01-17", "expiry_date": "2025-11-13"} + validity = {"issuance_date": "2025-01-17", "expiry_date": "2030-11-13"} mdoci = MdocCborIssuer( private_key=PKEY, alg="ES256", @@ -73,7 +73,7 @@ def test_mdoc_issuer(): mdocp = MdocCbor() aa = cbor2.dumps(mdoc) mdocp.loads(aa) - assert mdocp.verify() is True + assert mdocp.verify(allow_untrusted_issuer=True) is True mdoci.dump() mdoci.dumps() @@ -89,7 +89,7 @@ def test_mdoc_issuer(): def test_mdoc_issuer_EdDSA(): - validity = {"issuance_date": "2025-01-17", "expiry_date": "2025-11-13"} + validity = {"issuance_date": "2025-01-17", "expiry_date": "2030-11-13"} mdoci = MdocCborIssuer( private_key=PKEY, alg="ES256", @@ -117,7 +117,7 @@ def test_mdoc_issuer_EdDSA(): mdocp = MdocCbor() aa = cbor2.dumps(mdoc) mdocp.loads(aa) - assert mdocp.verify() is True + assert mdocp.verify(allow_untrusted_issuer=True) is True mdoci.dump() mdoci.dumps() @@ -133,7 +133,7 @@ def test_mdoc_issuer_EdDSA(): def test_mdoc_issuer_RSA(): - validity = {"issuance_date": "2025-01-17", "expiry_date": "2025-11-13"} + validity = {"issuance_date": "2025-01-17", "expiry_date": "2030-11-13"} mdoci = MdocCborIssuer( private_key=PKEY, alg="ES256", @@ -161,7 +161,7 @@ def test_mdoc_issuer_RSA(): mdocp = MdocCbor() aa = cbor2.dumps(mdoc) mdocp.loads(aa) - assert mdocp.verify() is True + assert mdocp.verify(allow_untrusted_issuer=True) is True mdoci.dump() mdoci.dumps() diff --git a/pymdoccbor/tests/test_03_mdoc_issuer.py b/pymdoccbor/tests/test_03_mdoc_issuer.py index 72ffbac..8785d03 100644 --- a/pymdoccbor/tests/test_03_mdoc_issuer.py +++ b/pymdoccbor/tests/test_03_mdoc_issuer.py @@ -37,21 +37,6 @@ def test_MdocCborIssuer_new_single(): assert mdoc.signed['documents'][0]['docType'] == 'org.micov.medical.1' assert mdoc.signed['documents'][0]['issuerSigned']['nameSpaces']['org.micov.medical.1'][0].tag == 24 -# TODO: restore multiple documents support -# def test_MdocCborIssuer_new_multiple(): -# micov_data = {"doctype": "org.micov.medical.1", "data": MICOV_DATA} -# pid_data = {"doctype": "eu.europa.ec.eudiw.pid.1", "data": PID_DATA} -# mdoc.new( -# doctype="org.micov.medical.1", -# data=[micov_data, pid_data], -# validity={"issuance_date": "2024-12-31", "expiry_date": "2050-12-31"}, -# # devicekeyinfo=PKEY # TODO -# ) -# assert mdoc.signed['version'] == '1.0' -# assert mdoc.signed['documents'][0]['docType'] == 'org.micov.medical.1' -# assert mdoc.signed['documents'][1]['docType'] == 'eu.europa.ec.eudiw.pid.1' - - def test_MdocCborIssuer_dump(): dump = mdoc.dump() diff --git a/pymdoccbor/tests/test_05_mdoc_verifier.py b/pymdoccbor/tests/test_05_mdoc_verifier.py index 292bd8f..360395c 100644 --- a/pymdoccbor/tests/test_05_mdoc_verifier.py +++ b/pymdoccbor/tests/test_05_mdoc_verifier.py @@ -111,4 +111,4 @@ def test_mobile_document_verify(): document = mdoc.signed["documents"][0] doc = MobileDocument(**document) - assert doc.verify() + assert doc.verify(allow_untrusted_issuer=True) diff --git a/pymdoccbor/tests/test_07_mso_verifier.py b/pymdoccbor/tests/test_07_mso_verifier.py index 1479747..0b74c56 100644 --- a/pymdoccbor/tests/test_07_mso_verifier.py +++ b/pymdoccbor/tests/test_07_mso_verifier.py @@ -43,7 +43,7 @@ def test_mso_verifier_verify_signatures(): msov = MsoVerifier(issuerAuth) - assert msov.verify_signature() + assert msov.verify_signature(allow_untrusted_issuer=True) def test_mso_verifier_payload_as_cbor(): diff --git a/pymdoccbor/tests/test_08_mdoc_cbor.py b/pymdoccbor/tests/test_08_mdoc_cbor.py index 99a0097..3445f0e 100644 --- a/pymdoccbor/tests/test_08_mdoc_cbor.py +++ b/pymdoccbor/tests/test_08_mdoc_cbor.py @@ -35,7 +35,7 @@ def test_mdoc_cbor_creation(): mdocp = MdocCbor() mdocp.loads(data) - mdocp.verify() + mdocp.verify(allow_untrusted_issuer=True) assert mdoc assert "org.micov.medical.1" in mdocp.disclosure_map diff --git a/pymdoccbor/tests/test_10_cert_chain_and_hashes.py b/pymdoccbor/tests/test_10_cert_chain_and_hashes.py index c048785..cc93ccf 100644 --- a/pymdoccbor/tests/test_10_cert_chain_and_hashes.py +++ b/pymdoccbor/tests/test_10_cert_chain_and_hashes.py @@ -152,8 +152,10 @@ def test_certificate_chain_verification_untrusted(): msov.attest_public_key([untrusted_cert]) -def test_certificate_chain_verification_skipped(): - """Test that verification is skipped when no trusted roots provided.""" +def test_certificate_chain_verification_requires_roots(): + """Fail closed when no trusted roots are provided.""" + from pymdoccbor.exceptions import TrustedRootRequired + mdoc = MdocCborIssuer( private_key=PKEY, alg="ES256", @@ -171,8 +173,33 @@ def test_certificate_chain_verification_skipped(): issuerAuth = mdoc.signed["documents"][0]["issuerSigned"]["issuerAuth"] msov = MsoVerifier(issuerAuth) - # Should return None and log warning - result = msov.attest_public_key(None) + with pytest.raises(TrustedRootRequired): + msov.attest_public_key(None) + + with pytest.raises(TrustedRootRequired): + msov.attest_public_key([]) + + +def test_certificate_chain_verification_skipped_with_opt_out(): + """Skip chain validation only when allow_untrusted_issuer=True.""" + mdoc = MdocCborIssuer( + private_key=PKEY, + alg="ES256", + cert_info=CERT_DATA + ) + mdoc.new( + data=MICOV_DATA, + doctype="org.micov.medical.1", + validity={ + "issuance_date": "2024-12-31", + "expiry_date": "2050-12-31" + }, + ) + + issuerAuth = mdoc.signed["documents"][0]["issuerSigned"]["issuerAuth"] + msov = MsoVerifier(issuerAuth) + + result = msov.attest_public_key(None, allow_untrusted_issuer=True) assert result is None @@ -263,8 +290,8 @@ def test_mobile_document_verify_with_hashes(): document = mdoc.signed["documents"][0] doc = MobileDocument(**document) - # Verify with hash verification enabled - is_valid = doc.verify(verify_hashes=True) + # Verify with hash verification enabled (opt out of trust anchors for unit test) + is_valid = doc.verify(verify_hashes=True, allow_untrusted_issuer=True) assert is_valid is True assert doc.hash_verification is not None @@ -292,16 +319,14 @@ def test_mobile_document_verify_without_hashes(): doc = MobileDocument(**document) # Verify with hash verification disabled - is_valid = doc.verify(verify_hashes=False) + is_valid = doc.verify(verify_hashes=False, allow_untrusted_issuer=True) assert is_valid is True assert doc.hash_verification is None def test_mdoc_cbor_verify_with_all_features(): - """Test MdocCbor.verify() with certificate chain and hash verification.""" - root_cert, ds_cert, ds_key = generate_test_certificates() - + """Test MdocCbor.verify() with hash verification and explicit trust opt-out.""" mdoc = MdocCborIssuer( private_key=PKEY, alg="ES256", @@ -320,8 +345,7 @@ def test_mdoc_cbor_verify_with_all_features(): mdoc_cbor = MdocCbor() mdoc_cbor.loads(cbor2.dumps(mdoc.signed)) - # Verify with hash verification (cert chain will be skipped without trusted roots) - is_valid = mdoc_cbor.verify(verify_hashes=True) + is_valid = mdoc_cbor.verify(verify_hashes=True, allow_untrusted_issuer=True) assert is_valid is True assert len(mdoc_cbor.documents) > 0 diff --git a/pymdoccbor/tests/test_11_cbor2_compat.py b/pymdoccbor/tests/test_11_cbor2_compat.py index f7b577f..6cec9e7 100644 --- a/pymdoccbor/tests/test_11_cbor2_compat.py +++ b/pymdoccbor/tests/test_11_cbor2_compat.py @@ -43,7 +43,7 @@ def test_mso_verifier_with_cbor2_loads_roundtrip(): reloaded = cbor2.loads(cbor2.dumps(issuer_auth)) msov = MsoVerifier(reloaded) assert isinstance(msov.object, Sign1Message) - assert msov.verify_signature() + assert msov.verify_signature(allow_untrusted_issuer=True) def test_mobile_document_from_issuer_signed(): diff --git a/pymdoccbor/x509.py b/pymdoccbor/x509.py index ce2ac1e..945a335 100644 --- a/pymdoccbor/x509.py +++ b/pymdoccbor/x509.py @@ -23,6 +23,7 @@ def load_x509_certificates_from_bytes(data: bytes) -> list[Certificate]: if certs: return certs except ValueError: + # Not PEM (or empty PEM). Fall through to DER parsing. pass return [x509.load_der_x509_certificate(data)] From afea43598bede8f9ab39cb0b3afc87cc15e3b4b5 Mon Sep 17 00:00:00 2001 From: peppelinux Date: Tue, 1 Dec 2026 11:54:12 +0100 Subject: [PATCH 2/4] fix: every returned IssuerSignedItem must match an MSO digest. No digest won't pass --- pymdoccbor/mso/verifier.py | 35 ++++++++++-- .../tests/test_10_cert_chain_and_hashes.py | 53 +++++++++++++++++++ 2 files changed, 84 insertions(+), 4 deletions(-) diff --git a/pymdoccbor/mso/verifier.py b/pymdoccbor/mso/verifier.py index 54a8084..3c2e9e0 100644 --- a/pymdoccbor/mso/verifier.py +++ b/pymdoccbor/mso/verifier.py @@ -375,12 +375,39 @@ def verify_element_hashes(self, namespaces: dict) -> dict: } for namespace, items in namespaces.items(): - if namespace not in value_digests: - logger.warning(f"Namespace {namespace} not found in MSO valueDigests") + namespace_digests = value_digests.get(namespace) + if namespace_digests is None: + # ISO 18013-5 §9.3.1 step 3: every disclosed IssuerSignedItem must + # match a digest in the MSO. A namespace absent from valueDigests + # cannot satisfy that requirement. + logger.error(f"Namespace {namespace} not found in MSO valueDigests") + results['valid'] = False + for item_bytes in items: + results['total'] += 1 + failed = { + 'namespace': namespace, + 'reason': 'namespace not in MSO', + } + try: + item_bytes_raw = ( + cbor2.dumps(item_bytes) + if isinstance(item_bytes, cbor2.CBORTag) + else item_bytes + ) + item_data = cbor2.loads(item_bytes_raw) + if isinstance(item_data, cbor2.CBORTag) and item_data.tag == 24: + item_content = cbor2.loads(item_data.value) + else: + item_content = item_data + failed['digestID'] = item_content.get('digestID') + failed['elementIdentifier'] = item_content.get( + 'elementIdentifier' + ) + except Exception: + pass + results['failed'].append(failed) continue - namespace_digests = value_digests[namespace] - for item_bytes in items: results['total'] += 1 diff --git a/pymdoccbor/tests/test_10_cert_chain_and_hashes.py b/pymdoccbor/tests/test_10_cert_chain_and_hashes.py index cc93ccf..06d6fde 100644 --- a/pymdoccbor/tests/test_10_cert_chain_and_hashes.py +++ b/pymdoccbor/tests/test_10_cert_chain_and_hashes.py @@ -271,6 +271,59 @@ def test_element_hash_verification_tampered(): assert results['failed'][0]['reason'] == 'hash mismatch' +def test_element_hash_verification_rejects_namespace_absent_from_mso(): + """Disclosed IssuerSignedItems under a namespace missing from MSO valueDigests fail.""" + mdoc = MdocCborIssuer( + private_key=PKEY, + alg="ES256", + cert_info=CERT_DATA + ) + mdoc.new( + data=MICOV_DATA, + doctype="org.micov.medical.1", + validity={ + "issuance_date": "2024-12-31", + "expiry_date": "2050-12-31" + }, + ) + + signed = cbor2.loads(cbor2.dumps(mdoc.signed)) + issuer_auth_before = cbor2.dumps( + signed["documents"][0]["issuerSigned"]["issuerAuth"] + ) + forged = { + "digestID": 9003, + "random": b"\x02" * 16, + "elementIdentifier": "given_name", + "elementValue": "C", + } + signed["documents"][0]["issuerSigned"]["nameSpaces"]["org.example.ns2"] = [ + cbor2.CBORTag(24, cbor2.dumps(forged)) + ] + assert cbor2.dumps( + signed["documents"][0]["issuerSigned"]["issuerAuth"] + ) == issuer_auth_before + + msov = MsoVerifier(signed["documents"][0]["issuerSigned"]["issuerAuth"]) + results = msov.verify_element_hashes( + signed["documents"][0]["issuerSigned"]["nameSpaces"] + ) + assert results['valid'] is False + assert any( + f.get('reason') == 'namespace not in MSO' + and f.get('namespace') == 'org.example.ns2' + for f in results['failed'] + ) + + doc = MobileDocument(**signed["documents"][0]) + assert doc.verify(verify_hashes=True, allow_untrusted_issuer=True) is False + + mdoc_cbor = MdocCbor() + mdoc_cbor.loads(cbor2.dumps(signed)) + assert mdoc_cbor.verify(verify_hashes=True, allow_untrusted_issuer=True) is False + assert len(mdoc_cbor.documents_invalid) == 1 + + def test_mobile_document_verify_with_hashes(): """Test MobileDocument.verify() with hash verification enabled.""" mdoc = MdocCborIssuer( From 23b2bc280bfd122211eb6e5b4f8620bf318ce8e7 Mon Sep 17 00:00:00 2001 From: peppelinux Date: Tue, 1 Dec 2026 11:58:57 +0100 Subject: [PATCH 3/4] fix: disclosure_map will only take verified claims --- pymdoccbor/mdoc/verifier.py | 19 ++++++++++++++++--- .../tests/test_10_cert_chain_and_hashes.py | 3 +++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/pymdoccbor/mdoc/verifier.py b/pymdoccbor/mdoc/verifier.py index 7ae41bc..b684e7a 100644 --- a/pymdoccbor/mdoc/verifier.py +++ b/pymdoccbor/mdoc/verifier.py @@ -256,12 +256,25 @@ def verify( clock_skew_seconds=clock_skew_seconds, ): self.documents.append(mso) + # Defence in depth: expose claims only from documents that + # verified. With verify_hashes=True that means every + # disclosed namespace matched MSO valueDigests. + failed_namespaces = set() + if mso.hash_verification: + failed_namespaces = { + entry.get('namespace') + for entry in mso.hash_verification.get('failed', []) + if entry.get('namespace') + } + for namespace, claims in mso.issuersigned.namespaces.items(): + if namespace in failed_namespaces: + continue + self.disclosure_map[namespace] = self._decode_claims( + claims + ) else: self.documents_invalid.append(mso) - for namespace, claims in mso.issuersigned.namespaces.items(): - self.disclosure_map[namespace] = self._decode_claims(claims) - except Exception as e: logger.error( f"COSE Sign1 validation failed to the document number #{doc_cnt}. " diff --git a/pymdoccbor/tests/test_10_cert_chain_and_hashes.py b/pymdoccbor/tests/test_10_cert_chain_and_hashes.py index 06d6fde..c966ac5 100644 --- a/pymdoccbor/tests/test_10_cert_chain_and_hashes.py +++ b/pymdoccbor/tests/test_10_cert_chain_and_hashes.py @@ -322,6 +322,9 @@ def test_element_hash_verification_rejects_namespace_absent_from_mso(): mdoc_cbor.loads(cbor2.dumps(signed)) assert mdoc_cbor.verify(verify_hashes=True, allow_untrusted_issuer=True) is False assert len(mdoc_cbor.documents_invalid) == 1 + # Failed documents must not contribute unverified claims to disclosure_map + assert mdoc_cbor.disclosure_map == {} + assert "org.example.ns2" not in mdoc_cbor.disclosure_map def test_mobile_document_verify_with_hashes(): From f01a38b81240dd292f89d3cc4134cff3fbf614dc Mon Sep 17 00:00:00 2001 From: peppelinux Date: Tue, 1 Dec 2026 12:14:31 +0100 Subject: [PATCH 4/4] fix: make code-quality CI pass for isort, flake8, and bandit --- pymdoccbor/mso/verifier.py | 16 ++++++++-------- pymdoccbor/tests/test_03_mdoc_issuer.py | 1 + 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/pymdoccbor/mso/verifier.py b/pymdoccbor/mso/verifier.py index 3c2e9e0..031f3be 100644 --- a/pymdoccbor/mso/verifier.py +++ b/pymdoccbor/mso/verifier.py @@ -12,12 +12,9 @@ from pycose.messages import Sign1Message from pymdoccbor import settings -from pymdoccbor.exceptions import ( - MsoValidityError, - MsoX509ChainNotFound, - TrustedRootRequired, - UnsupportedMsoDataFormat, -) +from pymdoccbor.exceptions import (MsoValidityError, MsoX509ChainNotFound, + TrustedRootRequired, + UnsupportedMsoDataFormat) from pymdoccbor.tools import bytes2CoseSign1, cborlist2CoseSign1 from pymdoccbor.x509 import X509ChainSource, load_x509_certificates_from_source @@ -403,8 +400,11 @@ def verify_element_hashes(self, namespaces: dict) -> dict: failed['elementIdentifier'] = item_content.get( 'elementIdentifier' ) - except Exception: - pass + except Exception as e: + logger.debug( + f"Could not enrich failed item metadata for " + f"namespace {namespace}: {e}" + ) results['failed'].append(failed) continue diff --git a/pymdoccbor/tests/test_03_mdoc_issuer.py b/pymdoccbor/tests/test_03_mdoc_issuer.py index 8785d03..836f40e 100644 --- a/pymdoccbor/tests/test_03_mdoc_issuer.py +++ b/pymdoccbor/tests/test_03_mdoc_issuer.py @@ -37,6 +37,7 @@ def test_MdocCborIssuer_new_single(): assert mdoc.signed['documents'][0]['docType'] == 'org.micov.medical.1' assert mdoc.signed['documents'][0]['issuerSigned']['nameSpaces']['org.micov.medical.1'][0].tag == 24 + def test_MdocCborIssuer_dump(): dump = mdoc.dump()