Repository navigation
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #165 +/- ##
===========================================
+ Coverage 58.44% 72.57% +14.12%
===========================================
Files 4 6 +2
Lines 580 711 +131
Branches 147 192 +45
===========================================
+ Hits 339 516 +177
+ Misses 140 93 -47
- Partials 101 102 +1 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
6954665 to
f2fd2f7
Compare
9186487 to
299d11d
Compare
299d11d to
f669fef
Compare
rh-ssorce
left a comment
There was a problem hiding this comment.
The frist 3 commits are a) broken b) a noop, what's the point of keeping them ?
In general this PR really should be rebased and commits squashed and better prepared, a review commit by commit caused a lot of useless commenting for things added and removed (up to 3/4 gratuoitous changes in the same area.
Certainly I would not like to see this commit series be merged as is in the code, as it would make the code history incredbily sloppy for no good reason.
This PR should be at most 2/4 commits from what I can tell, not 20
|
|
||
| static int | ||
| rec_kem_secure(json_t *kem_jwk, const json_t *req, char **out) | ||
| rec_kem_secure(json_t *tang_kem_priv, const json_t *req, char **out) |
There was a problem hiding this comment.
this whole commit is just churn, these changes should be done in the original commits ... although you can probably just squash all commits leading up to this point as they are not very useful on their own.
There was a problem hiding this comment.
Sorry for the mess. You are completely right about it. However, at this point, I really believe the way forward is that, once PR is approved, to squash all commits in one to main branch. WDYT?
There was a problem hiding this comment.
There are commits like this one: 18d538c that are general fixes and should probably be rebased as first of the pile on its own
| } | ||
|
|
||
| static const char* const kem_algorithms[] = { | ||
| "ML-KEM-512", "ML-KEM-768", "ML-KEM-1024", NULL |
There was a problem hiding this comment.
I do not see any reason for this, why would you want to provide multiple keys at different security levels by default?
Unless there is a very good reason you should limit default to just ML-KEM-768, and any other option should be an explicit configuration choice at install time.
There was a problem hiding this comment.
I do not see any reason for this, why would you want to provide multiple keys at different security levels by default?
Unless there is a very good reason you should limit default to just ML-KEM-768, and any other option should be an explicit configuration choice at install time.
There is no configuration at install time. The intention here was to generate all the possible keys, then Clevis will ask for the required one by sending a parameter (alg) to Tang endpoint. This way, key generation is avoided on bind time.
There was a problem hiding this comment.
I think tang should be opinionated in what it is willing to serve to clients. May make sense to offer only ML-KEM-1024, otherwise there is a risk that tang will allow clevis to use a level 1 security (up to 128bit security) key to wrap a higher level (AES-256) key.
There was a problem hiding this comment.
I think tang should be opinionated in what it is willing to serve to clients. May make sense to offer only ML-KEM-1024, otherwise there is a risk that tang will allow clevis to use a level 1 security (up to 128bit security) key to wrap a higher level (AES-256) key.
IMHO, there are particular circumstances where clevis could have limitations on using ML-KEM-1024 (For embedded/IoT clevis clients, this might matter)
Apart from that, NIST recommends ML-KEM-768 as the general-purpose default, not ML-KEM-1024. So this seems like not implementing the general-purpose default ...
I would be more confident in letting the clients select the algorithm to use
There was a problem hiding this comment.
sounds like this should be left to whoever deploys tang to decide and otherwise the default should be just what NIST recommends (ML_KEM-768) then.
| if (!pub_alg || (strcmp(pub_alg, "ML-KEM-512") != 0 && | ||
| strcmp(pub_alg, "ML-KEM-768") != 0 && | ||
| strcmp(pub_alg, "ML-KEM-1024") != 0)) |
There was a problem hiding this comment.
if you are validating, you should validate also that the parameter set matches the expected set, which is the same as the tang kem used. You do not want to allow a "downgrade attack" to ML-KEM-512 when your system is configured to use ML-KEM-1024
There was a problem hiding this comment.
if you are validating, you should validate also that the parameter set matches the expected set, which is the same as the tang kem used. You do not want to allow a "downgrade attack" to ML-KEM-512 when your system is configured to use ML-KEM-1024
I am sorry, I don't get this. This is just to ensure that the algorithm selected by clevis is among the supported ones. Later, in this part of the code:
jws = find_jws_kem(tki, alg);
if (!jws)
return http_reply(HTTP_STATUS_NOT_FOUND, NULL);
It is ensuring that requested algorithm is supported, or returning 404 if not
There was a problem hiding this comment.
As I said, I think tang should be more opinionated and not let clevis do things that are not reasonable in most environemnts (like using ML-KEM-512), and the best way to do that is to not generate keys and not offer algos for which you do not have keys
There was a problem hiding this comment.
As I said, I think tang should be more opinionated and not let clevis do things that are not reasonable in most environemnts (like using ML-KEM-512), and the best way to do that is to not generate keys and not offer algos for which you do not have keys
Clevis will use ML-KEM-768 by default. using ML-KEM-512 should be explicitly done on bind time
9fe1aeb to
e6bdf0b
Compare
|
One more thing, I may be blind but I do not see any configure time substitution in test-pqc.c.in so why is this a .c.in file instead of being just a .c regular file? |
File contains: @testjwkdir@ is a meson configure_file substitution — it gets replaced with the actual test fixture directory path at build time (defined in tests/meson.build as meson.source_root() / 'tests' / 'keys'). |
|
Main blockers have been resolved. Please, review when possible @sergio-correia |
| goto cleanup; | ||
| } | ||
|
|
||
| digest = compute_req_digest(req_protected_b64); |
There was a problem hiding this comment.
what is the point of adding a digest of fields you are already sending and are included in the protected header? (therefore already integrity protected)
There was a problem hiding this comment.
According to the "blocker" document I received, there was a statement like:
and the response must be bound to the specific request through an agreed canonical transcript value.
I understood the digest of the protected header could act as that
There was a problem hiding this comment.
No it doesn't, the digest in the protocol binds the decryption key, only the legitimate owner has it, while the transcript hash only binds the tokens to the specific exchange, which anyone can initiate.
Please do not guess at cryptographic protocol details, always ask.
There was a problem hiding this comment.
No it doesn't, the digest in the protocol binds the decryption key, only the legitimate owner has it, while the transcript hash only binds the tokens to the specific exchange, which anyone can initiate.
Please do not guess at cryptographic protocol details, always ask.
I understand I should directly remove it, right?
a7aba17 to
76732e0
Compare
|
I ran an AI review while I am also manually reviewing this, and it highlight stuff that is not critical bu worth considering (missing numbers are things I removed as it as not a real issue considering a wider context or API contract): Review summaryThe series (26 commits, High priority
Medium priority
Minor / nits
Verdict: the uplift is directionally good and the |
1472f2b to
a80991b
Compare
Thank you very much for the thorough and thoughtful review — all points were valid and have been addressed on the branch. A summary of what was done: High priority
Medium priority
Minor nitsAll addressed in a final commit: wipe_jwk_secret() and OPENSSL_clear_free(enc_key_json, …) now cleanse len + 1 bytes (NUL included), with the const-cast and shared-json_t mutation documented;
Thanks again |
Extend Tang with hybrid post-quantum cryptography capabilities: ML-KEM-768 key generation: - Generate an ML-KEM-768 (kty: AKP) key pair alongside the existing ES512 and ECMR keys, both in the C daemon (create_new_keys) and in the tangd-keygen shell script. - Key generation is optional: if jose does not support ML-KEM, the server logs a warning and continues operating with classical keys only. This preserves backward compatibility with older jose builds. PQC state tracking: - Add m_has_pqc field to tang_keys_info, set during key loading when an AKP-type key is found among regular (non-rotated) keys. - Expose PQC availability via the /version endpoint as the "hybrid_recovery" feature flag, allowing clients to detect server support before creating hybrid bindings. KEM decapsulation endpoint (POST /rec-kem/<thumbprint>): - Accept a JSON body with a "ct" field containing base64url-encoded ML-KEM ciphertext. - Look up the server ML-KEM private key by thumbprint, validate it is kty: AKP with deriveKey permission, and call jose_jwk_kem_dec to perform decapsulation. - Return the shared secret as an oct JWK, enabling the client to combine it with the ECDH shared secret for hybrid key derivation. - Support custom --endpoint prefix, consistent with existing routes. Test adjustment: - Relax test_create_new_keys assertion to m_keys_count >= 2, since ML-KEM generation may produce a third key when jose supports it. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
Separate concerns between /rec (ECMR exchange) and /rec-kem (KEM recovery). The legacy plaintext path that returned shared secrets directly is removed — all KEM recovery now uses a bidirectional envelope where enc_kem_key is always encrypted in transit. Removed rec_kem_legacy() and the detection branch in rec_kem(). Removed all ECMR logic from rec_kem_secure() (EC key lookup, jose_jwk_exc exchange, transport_key/tang_ec_pub in response). Added JWE compact serialization helpers (jwe_from_compact, jwe_to_compact) and secure memory cleansing (secure_zero, str_cleanse) for intermediate secrets. Updated tests to exercise the full bidirectional envelope protocol: forward-channel encapsulation, encrypted inner payload, return-channel decapsulation, and shared secret verification. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
The client now includes an ek_digest (SHA-256 JWK thumbprint of the stored shared secret) in the encrypted inner payload. Tang verifies this digest against the decapsulated enc_kem_key before proceeding with the return channel. If verification fails, Tang returns 400 without encrypting or returning anything. This prevents an attacker who intercepts clevis_transport_ct from replaying a recomputed clevis_encrypted_blob to have Tang act as a decapsulation oracle. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
9b6ecdf to
8327c98
Compare
A failed auto-generation could leave the key store partially
populated: the regeneration trigger requires an empty keydir
(m_keys_count == 0), so the orphan keys were never replaced. With
only the signing key left behind, the advertisement even looks
healthy while no client could ever recover; with deriving keys but
no signing key, every endpoint answers 500 until the partial keys
are removed by hand.
Two complementary fixes:
- create_new_keys() rolls back: the keys written so far are unlinked
again when a later key fails, so an interrupted generation leaves
an empty keydir, which the next request retries.
- read_keys() also regenerates when the store holds no deriving key
at all, active or rotated -- the state an interrupted (or crashed)
generation leaves behind, whatever wrote it. Stores that still
serve rotated deriving keys are left untouched, and a store with
deriving keys but no signing key still fails loudly, as before.
test_read_keys_partial_store_regenerates runs read_keys twice
against a partially-populated directory, as suggested: the first run
regenerates the deriving key, the second is stable. Verified by
mutation: with the new trigger reverted, the test aborts on exactly
the wedged state ("got 1 keys").
The rollback path itself has no deterministic test: forcing a
mid-generation write failure would need fault injection, since the
target filename is a random thumbprint. The trigger test pins the
user-visible wedge, and the rollback prevents the state from being
created in the first place.
Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
8327c98 to
c2a4b64
Compare
This is a real violation of tang's own rotation invariant — find_jws_kem_by_thp signs with current signers only while find_jws re-adds rotated ones; I'll fix tang to sign /adv-kem/ with all retained signers (no wire-format change, keeps deployed strict clients working) and add the decrypt-after-rotation regression test.
I agree the kem_kid pin is the decrypt-time trust anchor — the JWS is a binding-time mechanism — so extending the pin fallback to clevis's online mode is the right fix and also subsumes (1) for new clients; I will take it in clevis, as the /rec-returns-KEM-pub alternative doesn't cover the pre-request fetch where the substitution happens.
I'll make /version fail with 5xx on an unreadable key store so it stops reporting "no hybrid" for broken servers, matching the 404/500 semantics the KEM endpoints already maintain; clevis should treat only a valid 200 as "no support" and abort on anything else rather than downgrade.
|
A client that bound offline (storing the adv and adv-kem advertisements) froze the verify keys that were active at binding time and verifies the /adv-kem/<kem_kid> fetch against them. find_jws() re-adds rotated signers for /adv/<thp>, but find_jws_kem_by_thp() signed with the current m_sign only, so a routine tangd-rotate-keys left every such binding failing permanently with "KEM key signature verification failed (possible MITM)!" -- a violation of the rotation invariant the classical leg and the hidden-key retention policy already commit to. find_jws_kem_by_thp() now signs with every retained signer, current and rotated. The URL pins the KEM thumbprint, not the old signer's, so tang cannot know which rotated signer the client froze and all retained signers must sign, unlike find_jws(), which re-adds exactly the one signer the client names. jwk_valid_for_signing() is exported so both paths share the same signer admission predicate. No wire-format change: the JWS gains one signature per historical signer, consistent with rotated keys being retained precisely so bound clients keep working. Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
2781e53 to
8ff8609
Compare
In no-stored-adv mode (every online binding) the JWS on the /adv-kem/<kem_kid> fetch is verified against keys from the same unauthenticated channel and carries no trust: decrypt-time authentication rests on the client's kem_kid thumbprint pin instead. That pin is taken in clevis; what tang owes it is the contract it relies on -- the key served for X is the key whose thumbprint is X, for active and rotated keys alike. - tests/adv asserts the contract in the /adv-kem/<thp> lookup loop, for every advertised key and every hash algorithm: the payload key of the response must thumbprint to the requested value. - tests/rotate-keys asserts it for rotated keys with S256 (the kem_kid clevis pins), covering an online binding that fetches its pinned kem_kid after a rotation. - find_jws_kem_by_thp's comment now documents the trust model: the signature is a binding-time mechanism, the pin is the decrypt-time anchor, and the keyed lookup is what makes the pin sound. Verified by mutation: serving the first KEM key regardless of the request -- what a server-side substitution looks like -- fails both e2e tests on the pin assertions. Also fixes a latent heap corruption in the rotated-signer unit test added in the previous commit: the borrowed json_array_get() result was wrapped in json_auto_t, so the cleanup stole the array's only reference and the tang_keys_info release decrefed the freed element again. glibc only detects this intermittently (the freed chunk's tcache metadata makes the stale refcount look nonzero), which is why earlier runs passed; the borrowed pointer is now plain, the tree was audited for the same pattern, and test-pqc was run eight times in a row to confirm stability. Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
8ff8609 to
97b5f37
Compare
The retained-signer loop in find_jws_kem_by_thp() admitted anything
jwk_valid_for_signing() accepts: jose_jwk_prm with req=false passes
unrestricted keys (no use/key_ops), and AKP keys were not diverted
the way prepare_payload_and_sign() diverts them. jose_jws_sig is
all-or-nothing over the key array, so one such retained key -- e.g.
a hidden ML-KEM key with key_ops deleted, for which no signature
algorithm can be inferred at all (JOSE_CFG_ERR_ALG_NOINFER) -- made
jwk_sign() fail and every /adv-kem/<thp> answer 404, while /adv and
/adv-kem?alg= stayed 200: health checks looked fine and every hybrid
decrypt failed at boot until the file was removed by hand.
jwk_usable_as_retained_signer() now gates the loop: kty AKP is
skipped entirely (mirroring prepare_payload_and_sign(), since
RFC 9864 AKP also covers signature algorithms and a key_ops check
cannot tell a KEM key from a signer), the signing permission is
required, and so is private material (a non-empty "d"), the same
shape as jwk_has_complete_kem_material on the KEM side.
Tests:
- Unit: the reported fixture -- a hidden AKP key with key_ops
deleted -- plus a hidden pub-only signing key, both asserted to be
loaded as retained; the /adv-kem advertisement must still be
produced and verify with the current signer.
- e2e: both rogue keys dropped into the store;
/adv-kem/<kem_thp> must still answer 200 and verify.
Verified by mutation: reverting to the permission-only check fails
both tests exactly as reported ("an unusable retained key took down
/adv-kem", and a 404 in place of the 200).
Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
tang_version() answered 200 with hybrid_recovery:false even when read_keys() failed: the "if (tki)" guard folded an unreadable key store into the default false, so a broken server looked exactly like a legitimately downgraded one. Clients that gate on /version (clevis fetchVersion) would silently bind classical-only against a server that cannot serve anything, instead of failing loudly. /version now answers 5xx for an unusable key store, mirroring the status mapping /adv, /rec and the KEM endpoints already maintain (5xx = broken store, 404 = unsupported). "No support" stays 200 with hybrid_recovery:false: a readable store without an advertised AKP key, or a runtime-unavailable ML-KEM probe (the tangd-unavailable case), still answers 200 with the honest false. tests/errors drops the signing key and now asserts /version -> 500 alongside /adv and /rec. Verified by mutation: reverting to the fold-into-false behavior fails the new assertion. The client half remains on the clevis side: only a well-formed 200 should be read as "no support"; network errors and 5xx must abort rather than downgrade. Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
The complete-material check was added for AKP keys, but the classical derive path still admitted on use/key_ops alone: a public-only ECMR key (the output of "jose jwk pub", which preserves key_ops) was advertised and bound fine -- encapsulation only needs crv/x/y -- and every later recovery failed with 403, since /rec needs the private half. The healing trigger counted the same permissive predicate, so the store was never repaired either. jwk_valid_for_deriving_exchange() now gates the derive admission: private material (a non-empty "d", the classical analog of jwk_has_complete_kem_material) plus jose_jwk_prm with req=true -- exactly /rec's server-key gate, so only keys recovery would accept are advertised. The healing trigger counts the same predicate, so a public-only ECMR key no longer masks a store that cannot serve recovery: read_keys regenerates instead. The req=true alignment also stops advertising unrestricted EC keys, the classical twin of the AKP fix. The permission-only jwk_valid_for_deriving_keys() is gone; its test usages moved to the strict predicate, one of them (the healed-payload check) becoming more correct with it. Tests: - Admission: a store with a complete deriving key plus a pub-only ECMR key does not heal, never advertises the pub-only key, and still advertises the complete one. - Healing: a store whose only deriving key is pub-only is repaired by read_keys, and the pub-only key is never advertised. - e2e: a pub-only ECMR dropped into the live store does not appear among the /adv payload keys. - test_jwk_thumbprint_missing_members gained a complete deriving key so the healing trigger stays quiet and the test keeps its subject, the thumbprint-failure lookups. Verified by mutation: reverting the predicate to permission-only fails the suite on "public-only ECMR key advertised in the payload", exactly as reported. Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
The per-iteration assertions in the /adv-kem by-thumbprint loop and in the pub-only ECMR payload check ran inside a "while read" fed by a pipe, so they executed in a subshell: the [ $? -eq 0 ] after the loop only observes the last command of the last iteration, and jose alg -k hash lists S512 last. A server serving the correct key only for S512-thumbprint lookups but a substituted key for the S256 ones -- the hash every real clevis binding pins -- passed the test green on POSIX-strict shells (verified on dash). On shells where set -e aborts the piped subshell the construct only works by relying on those semantics holding everywhere, including the BSD sh the suite supports. The loops now read from a file instead -- process substitution is not POSIX and does not exist in dash or the BSD sh, but a file-redirected loop has the same no-subshell property -- so the assertions run in the current shell and set a failure flag that is checked once after the loop. The signature checks inside the loop fail loudly in the main shell the same way. The two remaining exit-inside-subshell sites keep their deterministic behavior. Verified by mutation: a server patched to serve the correct key only for S512 thumbprints (86 chars) and a substituted key for every shorter hash fails the restructured test. Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
The rollback in create_new_keys() recorded a key's path only after its chmod succeeded, so a file whose chmod failed was written to disk but never unlinked: it stayed behind as a partial key set, wedging the store the rollback exists to heal. The path is now recorded immediately after the successful json_dump_file(), so recorded means exists on disk. The save-failure test fails on the first key, so the rollback loop never ran with anything to unlink. The write step is now injectable in the test build: keys.c's single json_dump_file() call is rewritten -- the same macro-stub pattern test-pqc.c.in uses for http_reply() -- to a wrapper that performs the real saves until an injected failure point. Key paths are random thumbprints, so a failure at a later key cannot be forced with pre-created files. test_create_new_keys_rollback fails the second save (ECMR; both it and ES512 are mandatory, so the failure point does not depend on jose's ML-KEM support) and asserts the return value, the umask restoration, an empty directory afterwards -- the decisive check, since read_keys() alone would mask a leftover through the healing trigger -- and that the next read_keys() regenerates a full key set. Verified by mutation: removing the rollback fails the test on "rollback left 1 file(s) behind". The chmod-failure branch of the recording fix remains untestable without a second injection point (chmod on a just-created file does not fail deterministically); it is correct by construction now. Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
validate_request_protected() tested only that the server's ECMR key carries a "d" member: an empty string passed, while both the KEM side (jwk_has_complete_kem_material) and the classical derive path (jwk_has_private_material) require non-empty members. An ECMR key with "d": "" therefore passed the /rec-kem binding validation. The check now uses json_string_length(), which is 0 for a missing member, a non-string, and an empty string: one check covers all three, and every side of the key validation agrees on the non-empty rule. test_validate_request_protected_ecmr_key_types gains the empty-d variant (an independently generated key, per the thumbprint-collision discipline) in its rejected bad_kids set. Verified by mutation: reverting to json_string_value() fails the test through exactly that key. Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
jwk_usable_as_retained_signer() screened retained keys by key shape
(kty, sign permission with req=false, non-empty d), and one more
shape slips through it: an ECMR key with key_ops deleted. Unrestricted
keys pass jose_jwk_prm(req=false) and ECMR keys carry a d, so the key
lands in the signer set -- but jose cannot infer a signature algorithm
for alg ECMR, and jose_jws_sig is all-or-nothing over the key array,
so every /adv-kem/<thp> answers 404 while /adv and /version stay
healthy.
Requiring the sign permission with req=true would close the hole, but
it would also drop unrestricted keys jose can sign with (e.g. an
ES512 key with key_ops deleted), and a client that bound while such a
key was active would stop verifying /adv-kem fetches after its
rotation. The predicate instead signs a throwaway JWS with the key
alone: jose_jws_sig itself refuses keys that are not permitted to
sign, that carry no private material, or for which no signature
algorithm can be inferred -- every class of unusable retained key in
one place, and no usable signer is dropped. kty AKP stays excluded up
front: RFC 9864 AKP also covers signature algorithms, so a jose with
ML-DSA could sign with an AKP key, but tang treats AKP keys as hybrid
exchange keys only. A dropped key is logged with its thumbprint, so
the operator can fix the store instead of wondering why pre-rotation
bindings no longer verify.
The comment above jwk_valid_for_signing() in keys.c still claimed the
KEM advertisement path admits retained signers with the same
predicate find_jws() uses, which stopped being true once the stricter
retained-signer check landed; it now states the KEM path probes
jose_jws_sig directly.
test_find_jws_kem_by_thp_unusable_retained_keys gains the ECMR key
with key_ops deleted and a hidden unrestricted ES512 key whose public
half must still verify the advertisement, pinning that the filter
drops keys that cannot sign rather than keys that merely lack
key_ops.
Verified by mutation: reverting src/pqc.c to the shape-based
predicate fails the test through exactly the ECMR rogue ("an
unusable retained key took down /adv-kem"). Confirmed end to end that
a hidden key_ops-less ECMR .jwk takes /adv-kem/<thp> from 200 to 404
with the old predicate and leaves it at 200 with the new one, with
/adv and /version healthy in both cases.
Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
prepare_payload_and_sign() admitted active signers on use/key_ops
alone, while the retained-signer path had learned to require an
actual signature. A hand-edited public-only ES512 file -- d removed,
key_ops kept, so unlike the output of "jose jwk pub" it still passes
the permission checks, since jose_jwk_prm() only inspects
use/key_ops -- landed in m_sign while nothing could produce a
signature with it: jose_jws_sig is all-or-nothing over the key
array, so /adv and /adv-kem answered 404 while /version kept
answering 200 with hybrid_recovery:true, presenting a broken store
as a working one.
The active path now admits signers with the same probe the retained
path uses, moved to keys.c as jwk_can_produce_signature() so both
signer sets share one definition: sign a throwaway JWS with the key
alone, and let jose_jws_sig refuse keys that are not permitted to
sign, that carry no private material, or for which no signature
algorithm can be inferred. A store left without any usable signer
fails read_keys() and every endpoint -- /version included --
answers 500, the broken-store signal, instead of a silent
half-healthy server; a public-only signer standing next to a
complete one is ignored rather than taking the advertisement down
with it.
test_read_keys_public_only_signer_fails mirrors the broken store
(a public-only ES512 with key_ops kept, plus a complete deriving
key so the healing trigger stays quiet and the failure can only
come from the missing signer), and
test_read_keys_public_only_signer_ignored pins the mixed store: the
unusable key is in neither m_sign nor the advertised payload, and
the default advertisement is still produced and verifies.
Verified by mutation: reverting the admission condition fails
test_read_keys_public_only_signer_fails ("a store whose only signer
cannot sign must fail read_keys"). Confirmed end to end with a
store of a public-only ES512 (key_ops kept), an ECMR and an ML-KEM
key: /adv, /version and /adv-kem?alg= all answer 500, while
/adv-kem without alg= still answers 400, since the query validation
must not read the key store.
Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
The rollback in create_new_keys() recorded a key's path only after json_dump_file() reported success, but json_dump_file() creates the path before it can fail. A write error part-way through (ENOSPC, ulimit -f) therefore left a truncated, unrecorded file behind -- harmless, since load_keys() skips files that do not parse. The dangerous shape is a close-time failure after the last write: the file is complete and valid on disk while json_dump_file() still reports failure, so it was never recorded and the rollback left it behind. If it is the ECMR key, the store ends up with a deriving key and no signer: the healing trigger stays quiet and every request answers 500. The path is now recorded before the dump: unlinking a path that was never created is harmless, and both failure shapes -- truncated or complete -- are rolled back. The chmod-ordering guarantee from the earlier fix is kept, since the recording now precedes the dump and the chmod both. The injection wrapper gains a mode that performs the real save and still reports failure, simulating the close-time failure after the last write. test_create_new_keys_rollback_complete_file uses it at the second save (ECMR, mandatory, so the failure point does not depend on jose's ML-KEM support) and asserts the empty directory and the regeneration on the next read_keys(). The directory counting the two rollback tests share is extracted into count_dir_files(). Verified by mutation: restoring the record-after-dump order fails the new test on "rollback left 1 file(s) behind", exactly the complete-but-failed ECMR key. Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
The ECMR key checks did not agree with each other: advertising and the healing trigger required private material and deriveKey with req=true but never looked at alg or kty; /rec required alg to be absent or ECMR but accepted an empty d; /rec-kem required alg ECMR, kty EC and a non-empty d. A hand-edited key with its alg removed (key_ops and d kept) therefore passed the advertising checks, was advertised and bound to, and every later recovery failed at /rec-kem with the protocol-mismatch message; an empty-d key was likewise advertised while /rec-kem refused it. The four places now share one predicate, jwk_valid_for_ecmr_recovery() in keys.c -- kty EC, alg ECMR, deriveKey with req=true, non-empty private material -- replacing jwk_valid_for_deriving_exchange(): prepare_payload_and_sign() admits a deriving key and store_lacks_deriving_keys() counts one only when recovery would accept it, rec() validates its server-side JWK with it, and validate_request_protected() (/rec-kem) keeps accepting exactly the keys it accepted before, now by construction instead of by a hand-maintained copy of the same four checks. The alg and kty requirements are what tang's own key generation always produces, so only hand-edited shapes stop being advertised. test_read_keys_alg_removed_exc_not_advertised pins the mixed store (the alg-less key is in neither the payload nor the healing count while the complete ECMR key stays advertised) and test_read_keys_alg_removed_exc_heals pins the alg-less-only store (the healing trigger fires instead of masking it). test_validate_request_protected_ecmr_key_types gains the alg-removed shape in its rejected bad_kids set. Verified by mutation: dropping the alg/kty checks from the predicate fails test_read_keys_alg_removed_exc_not_advertised on "ECMR key without alg advertised in the payload". Full suite green, including the /adv and /rec round trips against real generated stores. Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
The umask-restoration assertions in the create_new_keys tests read umask(old_umask) == old_umask, but umask() returns the mask that was in effect at the call -- the 0022 the test set and create_new_keys() restores -- while old_umask is the runner's original mask, so the assertion only held when the two happened to be equal. Under Fedora's default 0002 (user-private groups) or a stricter 0077 the runner aborted at the first one, in test_create_new_keys_save_failure, before any key-generation code ran. Both assertions now compare against 0022, the mask the tests set before calling create_new_keys(), which is also what the message always claimed: create_new_keys must restore the umask it changed, not the runner's. Verified by running test-keys under umask 0022, 0002 and 0077: all three aborted at the old assertion before the fix and pass now, and test-pqc and the full suite stay green under each of them. Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
The retained-signer skip log fired for keys that were never signers at all: on a healthy store after one rotation, every GET /adv-kem/<thp> wrote four "Skipping retained key" lines -- one for the rotated deriveKey-only ECMR key and three for the rotated ML-KEM keys. All of them healthy, none of them able to sign, which is expected. The thumbprints are public, so anyone can drive the volume up, and it grows with the rotation count. jose added a line of its own on top: the signature probe passed a NULL cfg, so jose's default error handler printed JOSE_CFG_ERR_ALG_NOINFER (jws.c) to stderr, landing in the middle of the access log output. jwk_usable_as_retained_signer() becomes classify_retained_signer(), returning a three-way outcome: kty AKP keys and keys without the sign permission -- the deriveKey-only ECMR key every rotation leaves behind, and ML-KEM keys -- were never signers and now skip silently; only a key that is permitted to sign but cannot produce a signature still gets the skip log line, the one drop that hides a key bindings frozen earlier would verify against. The probe itself now runs under a jose_cfg with a discarding error callback: a failed probe is an outcome the callers interpret, not something jose needs to report on stderr. Verified by test_find_jws_kem_by_thp_skip_log_policy, which captures stderr around find_jws_kem_by_thp: a store after one rotation (the fixture's rotated ES512 signer and deriveKey-only ECMR key, plus three rotated ML-KEM keys) writes nothing, and a pub-only retained signer (permitted to sign, private material deleted) writes exactly one skip line with no jose line of its own. The full suite passes, and a live /adv-kem/<thp> fetch against a running instance now leaves only the access-log line in the journal. Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
The 500-on-every-endpoint behavior for a store without a usable
signer took recovery down together with the advertisement: a store
with a valid ECMR key, an ML-KEM key and a public-only ES512 file
("d" removed, key_ops kept) used to answer 200 on /rec, since
recovery never needs a signer; after the signature probe every
endpoint reading the key store answered 500. The healing trigger
only looks at deriving keys, so nothing repairs this state: an
operator restoring a broken signer from a backup took unlocking
down for every existing client.
read_keys() gains a recovery mode, used by /rec and /rec-kem: it
shares the loader and the healing trigger with the strict mode, but
only the strict mode requires a usable signer and a non-empty
payload. Recovery resolves the requested thumbprint against every
key in the store, active or rotated, and validates it with the
endpoint's own predicate -- it never signs anything. The signer
requirement moves out of prepare_payload_and_sign() into
keys_satisfy_read_mode(), so the partition itself no longer fails on
an empty set. /adv and /version keep answering 500: the
broken-store signal stays as it is.
A "no usable signer" condition in the healing trigger was considered
and rejected: create_new_keys() writes a full key set, so healing
would duplicate the healthy deriving keys already present, and under
a restrictive crypto policy where a fresh signer also fails the
probe it would accumulate a new key set on every request.
Verified by the new tests -- test_read_keys_for_recovery_broken_signer
and test_read_keys_for_recovery_rotated_deriving_key pin the unit
behavior, rec-broken-signer exercises the full repro over HTTP
(/adv and /version 500, /rec 200 with a matching exchange, /rec-kem
round-trip), and the updated error_no_signing_keys now pins /rec 200
next to /adv and /version 500. The full suite passes in the PQC,
default and no-OpenSSL builds.
Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
Sharing one ECMR recovery predicate across the four validation sites tightened /rec: it used to accept a server key with no alg member and now answers 403 for one. The tightening is deliberate and breaks no client: no binding can exist for an alg-less server key, because the classic pin runs "jose fmt -Od alg", which fails when alg is absent, so it can never produce a binding for such a key. Since the predicate-sharing commit is already published, this note lands here and in the code comment at the refusal site. rec() was also the one site of the four with no test pinning it: putting the old plain key_ops check back in rec() left the whole suite green. rec_error_cases -- running in all four rec-* e2e tests -- now posts against an ECMR key with its alg removed and one with an empty private member, asserting both are refused with 403, the same answer the shared predicate gives everywhere else. Verified by reverting rec() to the plain key_ops check: the new assertions fail, and the full suite is green with the predicate in place. Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
| if (!pqc_is_available()) | ||
| return http_reply(HTTP_STATUS_NOT_FOUND, NULL); | ||
|
|
||
| thumbprint = load_thp_keys(path, matches, jwkdir, KEYS_READ_STRICT, |
There was a problem hiding this comment.
The recovery mode gives /rec and /rec-kem back to classical clients, but a hybrid binding still cannot unlock in this state. I bound with clevis-encrypt-tang-pqc and then removed d from the ES512 key while keeping its key_ops: with a stored advertisement, decrypt gets /rec 200 and then fails here with HTTP 500. In the default tang_pub mode it fails earlier, at /adv, for the same reason. The client always fetches /adv-kem/<kem_kid> before /rec-kem, and this endpoint reads the store strictly, so /rec-kem is never reached. The round trip the recovery mode restored is not one a real client can drive.
rec-broken-signer does not catch this, because it builds the /rec-kem request from the KEM key on disk instead of fetching the advertisement. Could it drive the client path, or at least assert 500 here next to the /rec-kem 200, so the test says what actually works? The comment above keys_satisfy_read_mode ("still serves unlocking for every existing client") also reads broader than this.
Two ways out, as I see it. One is to serve this endpoint in recovery mode, signed with whatever signers are still usable: at decrypt time the kem_kid pin is what authenticates the key, and the clevis side already treats the signature on this fetch as diagnostics only. The other is to state the limitation -- hybrid recovery needs a usable signer, classical does not. The first changes what the signature on this fetch is for, so it deserves its own discussion before it is committed to.
| continue; | ||
| } | ||
| } else if (jwk_valid_for_deriving_keys(jwk)) { | ||
| } else if (jwk_valid_for_ecmr_recovery(jwk)) { |
There was a problem hiding this comment.
One more shape gets through this branch. A key with kty EC, alg ECMR and key_ops [sign, verify, deriveKey] passes the permission check, fails the probe (no signature algorithm can be inferred for ECMR), and then lands here. jose_jwk_pub strips sign but keeps verify, so the advertisement carries the key as [verify, deriveKey] while nothing signs with it. I tried it here: /adv answers 200 and /version stays healthy. Every new binding fails client side, since jose jws ver -a refuses the whole advertisement when a verify key has no matching signature. Before the probe existed this shape took /adv down with a 404, which was at least visible on the server.
Even key_ops [verify, deriveKey] with no sign at all reaches the same place, since the branch never looks at the sign/verify permissions. Could the ECMR branch require the key to carry no sign or verify permission, so a key that looks like a signer cannot be published as an exchange key? I made that change here as well. The suite stays green.
| return 0; | ||
| } | ||
| } | ||
| json_array_foreach(tki->m_rotated_keys, idx, jwk) { |
There was a problem hiding this comment.
This trigger almost never fires on a store that has been rotated. The loop counts rotated ECMR keys, but the advertisement only ever holds active keys, and the strict read is satisfied by a signer alone. I ran keygen, one rotation, and then removed alg from the active ECMR key: /adv still answers 200 with only the ES512 verify key, /version looks fine, and nothing heals -- the file count is unchanged across requests. New bindings then fail client side, classic and PQC alike. A deleted or truncated ECMR file takes the same path, since load_keys skips what does not parse.
The heal tests only use stores that were never rotated, so nothing pins this. Would it be simpler to make the strict read fail when the payload holds no deriving key, instead of healing? That answers 500, the broken-store signal this series already uses, and the recovery read keeps serving the rotated key. The strict == NULL check in test_read_keys_for_recovery_rotated_deriving_key would need adjusting, since it pins the no-heal behavior only as a side effect.
| * (pub-only: key_ops kept, private material deleted) is logged | ||
| * exactly once, with its thumbprint, and nothing else -- in | ||
| * particular no jose line -- reaches the log. */ | ||
| json_auto_t *pub_only = json_pack("{s:s}", "alg", "ES512"); |
There was a problem hiding this comment.
The pub-only key here never makes jose print, so the "no jose line" half of the assertion cannot fail. I put the probe back to a NULL cfg and the whole suite still passes, while jose's ALG_NOINFER line returns to stderr on a live server. A hidden ECMR key with key_ops deleted is the shape that makes jose complain. Could scenario 2 add one, so the quiet error callback is pinned too?
| { | ||
| const json_t* pub = json_object_get(jwk, "pub"); | ||
| const json_t* priv = json_object_get(jwk, "priv"); | ||
| return json_is_string(pub) && json_string_length(pub) > 0 |
There was a problem hiding this comment.
The material checks are string-length checks. A key whose priv was swapped from another ML-KEM key, or truncated, or simply corrupt, still passes admission. The check only requires a non-empty string. The key is advertised, and a client binds to it, since encapsulation only needs pub. Every recovery then fails with 400: jose refuses the key at decapsulation time. I swapped the priv members of two ML-KEM-768 keys. Both were advertised and the bind succeeded. Decrypt then failed at /rec-kem, with "JWK 'pub' does not match the private key" in the server log. A corrupt d on an ECMR key gives the same picture on the classical side: /rec answers 400 next to a healthy /adv. Since the predicate passes, the store never repairs itself.
This needs write access to the key directory, so it is an operator-error shape rather than an attack. It fails closed, and on the KEM side jose's error lands in the server log. Would it be worth validating priv against pub at admission? jose already runs that check on the decapsulation side.
| int saved = dup(fileno(stderr)); | ||
| if (saved < 0) | ||
| return -1; | ||
| if (!freopen(path, "w", stderr)) { |
There was a problem hiding this comment.
One small thing in the new helper: freopen gives stderr a fully buffered heap buffer, and the dup2 in restore_stderr only retargets the file descriptor. The buffer survives the restore. An abort() after a failed assertion never flushes it, and the diagnostic message is lost. I hit this while making the skip log policy test fail on purpose: a failing ASSERT_WITH_MSG produced nothing, while 2270 bytes of earlier stderr arrived intact. A setvbuf(stderr, NULL, _IONBF, 0) after the dup2 would fix it.
| * still serves unlocking for every existing client, so an operator | ||
| * restoring a broken signer from a backup cannot take recovery | ||
| * down. The healing trigger cannot repair this state (it only | ||
| * regenerates deriving keys), so without this tolerance recovery |
There was a problem hiding this comment.
Two comments in keys.c have drifted from the code. The one here says the healing trigger "only regenerates deriving keys", but create_new_keys writes the full set, signer included. What is deriving-only is the trigger condition. The conclusion still holds, though for a different reason: the trigger never fires for a broken signer because it looks at deriving keys alone. Further up, the comment above jwk_valid_for_signing says the KEM advertisement path no longer uses it, but classify_retained_signer uses it again now, as its silent-skip pre-check.
For PQC to work appropriately, library requires usage of updated JOSE library. Changes (unmerged) available at:
latchset/jose#184
In case specific JOSE functions and algorithms are not available, Tang will work as previously, not including the files that are PQC specific
Add hybrid post-quantum cryptography support to Tang via a bidirectional KEM envelope protocol, with configurable ML-KEM algorithm selection and full backward compatibility with existing Clevis clients.
Tang generates ML-KEM keypairs (512, 768, and 1024 variants) alongside its existing EC keys. Servers with only classical keys automatically generate all supported ML-KEM variants on first
access. Two new endpoints handle the PQC key lifecycle:
GET /adv-kem — Serves a signed JWS containing only KEM (kty=AKP) keys, separate from /adv so legacy Clevis clients never encounter key types they can't handle. Accepts an optional ?alg= query parameter to filter by algorithm (e.g. ?alg=ML-KEM-512); defaults to ML-KEM-768 when unfiltered, preserving backward compatibility with clients that don't specify a variant.
POST /rec-kem/:thp — Bidirectional KEM recovery endpoint implementing a forward+return channel envelope:
a. Client encapsulates to Tang's KEM public key (forward channel), encrypts an inner payload under that shared secret
b. Tang decapsulates, verifies ek_digest (SHA-256 thumbprint of the enc_key) to prevent oracle attacks, then encapsulates back to the client's ephemeral KEM public key (return channel)
c. Tang encrypts enc_key under the return-channel shared secret and returns it — enc_key never appears in plaintext in the response
All KEM shared secrets are securely wiped from memory on every exit path, including error conditions.
Architecture
PQC code is cleanly isolated from the core server:
Other changes
GET /version — New endpoint reporting server capabilities (tang_pub, hybrid_recovery) and version.
tangd-keygen — Generates ML-KEM keys when jose supports it (soft-fails otherwise).
Test coverage