Skip to content

Tang Hybrid PQC Recovery implementation - #165

Open
sarroutbi wants to merge 77 commits into
latchset:masterfrom
sarroutbi:tang-kem-pub
Open

sarroutbi wants to merge 77 commits into
latchset:masterfrom
sarroutbi:tang-kem-pub

Conversation

@sarroutbi

@sarroutbi sarroutbi commented Oct 5, 2026 •

Copy link
Copy Markdown
Collaborator

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:

  • src/pqc.c / src/pqc.h — All KEM handlers (adv_kem, rec_kem), JWE compact serialization, secure memory zeroing. Only compiled when jose supports the KEM API.
  • src/pqc_noop.c — Stub implementations (404 responses) compiled when jose lacks KEM support.
  • No #ifdef in core files — keys.h, keys.c, and tangd.c have zero PQC conditional compilation. A meson compiler.links() probe detects jose KEM API support at build time, and src/meson.build selects pqc.c or pqc_noop.c accordingly.

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

  • /adv-kem tests: verifies only AKP keys are returned, JWS is signed by the signing key, /adv excludes AKP keys
  • /rec-kem tests: full 10-step bidirectional envelope round-trip, plus error cases (bad JSON, wrong key type, non-existent thumbprint, invalid ek_digest)
  • Unit tests: AKP key filtering into m_kem_payload, m_has_pqc detection, jwk_sign edge cases, cleanup NULL safety
  • All tests gracefully skip on jose without ML-KEM support

@codecov

codecov Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 70.44025% with 47 lines in your changes missing coverage. Please review.
✅ Project coverage is 72.57%. Comparing base (83de399) to head (4d8d55c).
⚠️ Report is 8 commits behind head on master.

Files with missing lines Patch % Lines
src/keys.c 67.85% 15 Missing and 21 partials ⚠️
src/tangd.c 72.72% 0 Missing and 9 partials ⚠️
src/http.c 0.00% 0 Missing and 2 partials ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@sarroutbi
sarroutbi force-pushed the tang-kem-pub branch 2 times, most recently from 6954665 to f2fd2f7 Compare October 5, 2026 16:21
@sarroutbi sarroutbi changed the title [DONTMERGE] Tang Hybrid PQC Recovery implementation Tang Hybrid PQC Recovery implementation Oct 7, 2026
@sarroutbi
sarroutbi marked this pull request as ready for review October 7, 2026 10:42
@sarroutbi
sarroutbi force-pushed the tang-kem-pub branch 2 times, most recently from 9186487 to 299d11d Compare October 27, 2026 16:51
Comment thread src/keys.c Resolved
Comment thread src/pqc.c Resolved

@rh-ssorce rh-ssorce left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread src/tangd.c Resolved
Comment thread src/tangd.c Resolved
Comment thread src/tangd.c Resolved
Comment thread src/tangd.c Outdated

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are commits like this one: 18d538c that are general fixes and should probably be rebased as first of the pile on its own

Comment thread src/pqc.c Resolved
Comment thread src/pqc.c Resolved
Comment thread src/keys.c Outdated
}

static const char* const kem_algorithms[] = {
"ML-KEM-512", "ML-KEM-768", "ML-KEM-1024", NULL

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@sarroutbi sarroutbi Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/pqc.c Outdated
Comment on lines +207 to +209
if (!pub_alg || (strcmp(pub_alg, "ML-KEM-512") != 0 &&
strcmp(pub_alg, "ML-KEM-768") != 0 &&
strcmp(pub_alg, "ML-KEM-1024") != 0))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread src/pqc.c Resolved
Comment thread src/pqc.c Resolved
@sarroutbi
sarroutbi force-pushed the tang-kem-pub branch 2 times, most recently from 9fe1aeb to e6bdf0b Compare November 10, 2026 17:07
@rh-ssorce

Copy link
Copy Markdown

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?

@sarroutbi

Copy link
Copy Markdown
Collaborator Author

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:

  const char* jwkdir = "@testjwkdir@";

@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').

@sarroutbi

Copy link
Copy Markdown
Collaborator Author

Main blockers have been resolved. Please, review when possible @sergio-correia

Comment thread src/pqc.c Outdated
goto cleanup;
}

digest = compute_req_digest(req_protected_b64);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Comment thread src/pqc.c Resolved
Comment thread src/pqc.c Resolved
@rh-ssorce

Copy link
Copy Markdown

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 summary

The series (26 commits, 99b3af3..refs/vimini/pr/165) adds a hybrid ML‑KEM /adv-kem[?alg=], /adv-kem/<thp> lookup, a /rec-kem envelope with enriched JWE protected headers, key rotation for hybrid keys, plus a lot of hardening (secret wiping, null‑safety, tests). Architecture is reasonable (pqc.c/pqc_noop.c split, single goto cleanup, centralized KEM alg constants) and the final req_digest removal is well argued. There are, however, several correctness/consistency issues worth fixing before merge.

High priority

  1. suite/kid are echoed without verification – the anti‑downgrade goal is not met. validate_request_protected() (src/pqc.c) only checks msg_dir, kem_kid == path echo, kem_ver, and that suite matches the pattern ECMR+ML-KEM-{512,768,1024}, and that kid is a string. It never:

    • looks up kid in the key store (find_jwk() is available), so tang will echo a kid for a key it does not hold;
    • cross‑checks suite's ML‑KEM variant against the algorithm of the KEM key selected by path_kem_kid, nor against clevis_kem_pub->alg.

    A client can therefore request an ML‑KEM‑768 key while declaring suite: "ECMR+ML-KEM-1024" and tang will happily assert that lie in the response header. Since the commit's stated purpose is “prevent downgrade between KEM parameter sizes”, the field must be derived from the actual key (SUITE_PREFIX + alg_of(tang_kem_priv)), and clevis_kem_pub / suite / tang key alg should all be required to agree.

  2. validate_request_protected() allocates a VLA from attacker‑controlled length (uint8_t dec_buf[dec_len + 1] after decoding the request protected header). This is on an unauthenticated endpoint, before any authorization decision. Body is capped at 64 KiB (http.h), so worst case is tens of KB of stack in a fork‑per‑connection/threaded server – enough to be a DoS smell. Use malloc (or reject dec_len above a small cap such as a few KiB).

Medium priority

  1. No negative tests for the new header validation. Every rec_kem_secure() test uses build_enriched_header("ecmr-kid", kem_kid, "ML-KEM-768"), i.e. only the happy path; the two “failure” tests fail later for unrelated reasons. Add unit cases for: missing protected, non‑base64 protected, wrong msg_dir, wrong kem_ver, kem_kid ≠ path, malformed suite, missing kid. Additionally, tests/rec only deletes the req_digest assertion – add an explicit ! json_object_get(..., "req_digest") and an assertion that crit exactly matches the extra header members, to prevent silent reintroduction/drift.

  2. tangd-rotate-keys hides all keys before generating new ones and swallows ML‑KEM failures. If ES512/ECMR generation fails, the daemon is left with only dot‑prefixed keys and /adv returns 500 (prepare_payload_and_sign fails on empty m_sign/m_payload). The new ML‑KEM loop additionally discards stderr (2>/dev/null) and only prints a “not supported by jose” line, so a real failure looks like a benign skip. Consider generating into temporary names then renaming, and distinguishing “unsupported” from “generation failed” (fail loudly in the latter case). Note also that the unconditional per‑rotation creation means hidden KEM keys accumulate with no pruning/documented policy.

  3. Unconditional new build dependency on OpenSSL. libcrypto = dependency('libcrypto') is added globally and linked into tangd even when has_pqc is false (pqc_noop needs nothing). This adds a BuildRequires: openssl-devel requirement (packaging, FreeBSD/port CI) and a new DT_NEEDED. Consider dependency('libcrypto', required: has_pqc) and only adding it to the tangd/test deps in that case – or keep the previous explicit_bzero/memset_s fallback, which needed no new dependency.

  4. Commit history hygiene. The range contains duplicated commits with identical subject/author date (f597060 vs upstream 99b3af3; also e73fa97/c8757a4), and one commit in the series commits literal <<<<<<< HEAD / ======= / >>>>>>> markers into tests/adv (later removed). The branch looks rebased onto a rewritten base; please squash/fixup the secrets‑wiping and header‑enrichment chains (fffd6ec→6068dba→96ca025, 65aa987→e6bdf0b) before merge so the history doesn't add‑then‑remove the same code.

Minor / nits

  • wipe_jwk_secret() writes through the const char * returned by json_string_value() (API violation, pragmatically fine) and cleanses json_string_length(k) bytes, leaving the NUL terminator. Use len + 1. Also document that it mutates a shared json_t (any other holder loses "k").
  • validate_request_protected() runs after the transport KEM decapsulation + AES‑GCM decrypt; validating the header right after jwe_from_compact() would reject garbage cheaply.
  • is_valid_suite() uses strncmp(suite, SUITE_PREFIX, strlen(SUITE_PREFIX)); prefer sizeof(SUITE_PREFIX) - 1.
  • Protocol constants KEM_VERSION, SUITE_PREFIX, DIR_REQUEST/DIR_RESPONSE live in pqc.c (tests only see them because they #include "pqc.c"), while shell tests hardcode "hybrid-v1". Move them to pqc.h and avoid duplicated literals in tests/rec.
  • crit lists are inconsistent: the server emits ["kem_ver","suite","kid","kem_kid","msg_dir"], while tests/rec builds the request with only 4 entries (no kid). Pick one set and document it; also consider whether kid belongs in crit at all (RFC 7515 §4.1.11 semantics).
  • The server never inspects the request's crit; RFC 7515 requires rejecting unknown critical parameters. Consider rejecting any crit entry outside the known set.
  • adv_kem_thp() and rec_kem() duplicate the matches[1] → strndup → read_keys → status‑mapping boilerplate; a small helper would reduce the chance of the copies diverging (they already differ: 500 vs 400/404 handling).
  • src/keys.c now includes pqc.h (which pulls in http.h) just for KEM_ALG_*/is_valid_kem_alg; consider moving these to keys.h or a tiny kem_alg.h to avoid a layering inversion.
  • snprintf(adv_kem_thp_endpoint, MAX_URL, ...) with a user‑supplied endpoint is unchecked for truncation (same as the pre‑existing buffers, but this adds another instance of silently broken routing for long -e prefixes).
  • tests/keygen/tests/rotate-keys call jose jwk gen inside jose_supports_alg() many times (entropy + runtime); jose alg listing would be cheaper.
  • OPENSSL_clear_free(enc_key_json, strlen(enc_key_json)) leaves the NUL byte uncleaned (same off‑by‑one as above).

Verdict: the uplift is directionally good and the req_digest rationale is sound, but items 1–3 should be addressed before merge (especially the unverified suite/kid echo, which undermines the security property the series claims to add), and items 4–9 are cheap, high‑value follow‑ups.

@sarroutbi

Copy link
Copy Markdown
Collaborator Author

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 summary

The series (26 commits, 99b3af3..refs/vimini/pr/165) adds a hybrid ML‑KEM /adv-kem[?alg=], /adv-kem/<thp> lookup, a /rec-kem envelope with enriched JWE protected headers, key rotation for hybrid keys, plus a lot of hardening (secret wiping, null‑safety, tests). Architecture is reasonable (pqc.c/pqc_noop.c split, single goto cleanup, centralized KEM alg constants) and the final req_digest removal is well argued. There are, however, several correctness/consistency issues worth fixing before merge.

High priority

1. **`suite`/`kid` are echoed without verification – the anti‑downgrade goal is not met.** `validate_request_protected()` (src/pqc.c) only checks `msg_dir`, `kem_kid == path echo`, `kem_ver`, and that `suite` matches the _pattern_ `ECMR+ML-KEM-{512,768,1024}`, and that `kid` is a string. It never:
   
   * looks up `kid` in the key store (`find_jwk()` is available), so tang will echo a `kid` for a key it does not hold;
   * cross‑checks `suite`'s ML‑KEM variant against the algorithm of the KEM key selected by `path_kem_kid`, nor against `clevis_kem_pub->alg`.
   
   A client can therefore request an ML‑KEM‑768 key while declaring `suite: "ECMR+ML-KEM-1024"` and tang will happily assert that lie in the response header. Since the commit's stated purpose is “prevent downgrade between KEM parameter sizes”, the field must be _derived from_ the actual key (`SUITE_PREFIX + alg_of(tang_kem_priv)`), and `clevis_kem_pub` / `suite` / tang key alg should all be required to agree.

2. **`validate_request_protected()` allocates a VLA from attacker‑controlled length** (`uint8_t dec_buf[dec_len + 1]` after decoding the request `protected` header). This is on an unauthenticated endpoint, before any authorization decision. Body is capped at 64 KiB (`http.h`), so worst case is tens of KB of stack in a fork‑per‑connection/threaded server – enough to be a DoS smell. Use `malloc` (or reject `dec_len` above a small cap such as a few KiB).

Medium priority

4. **No negative tests for the new header validation.** Every `rec_kem_secure()` test uses `build_enriched_header("ecmr-kid", kem_kid, "ML-KEM-768")`, i.e. only the happy path; the two “failure” tests fail later for unrelated reasons. Add unit cases for: missing `protected`, non‑base64 `protected`, wrong `msg_dir`, wrong `kem_ver`, `kem_kid` ≠ path, malformed `suite`, missing `kid`. Additionally, `tests/rec` only _deletes_ the `req_digest` assertion – add an explicit `! json_object_get(..., "req_digest")` and an assertion that `crit` exactly matches the extra header members, to prevent silent reintroduction/drift.

5. **`tangd-rotate-keys` hides all keys _before_ generating new ones and swallows ML‑KEM failures.** If ES512/ECMR generation fails, the daemon is left with only dot‑prefixed keys and `/adv` returns 500 (`prepare_payload_and_sign` fails on empty `m_sign`/`m_payload`). The new ML‑KEM loop additionally discards stderr (`2>/dev/null`) and only prints a “not supported by jose” line, so a real failure looks like a benign skip. Consider generating into temporary names then renaming, and distinguishing “unsupported” from “generation failed” (fail loudly in the latter case). Note also that the unconditional per‑rotation creation means hidden KEM keys accumulate with no pruning/documented policy.

6. **Unconditional new build dependency on OpenSSL.** `libcrypto = dependency('libcrypto')` is added globally and linked into `tangd` even when `has_pqc` is false (pqc_noop needs nothing). This adds a `BuildRequires: openssl-devel` requirement (packaging, FreeBSD/port CI) and a new DT_NEEDED. Consider `dependency('libcrypto', required: has_pqc)` and only adding it to the tangd/test deps in that case – or keep the previous `explicit_bzero`/`memset_s` fallback, which needed no new dependency.

7. **Commit history hygiene.** The range contains duplicated commits with identical subject/author date (`f597060` vs upstream `99b3af3`; also `e73fa97`/`c8757a4`), and one commit in the series commits literal `<<<<<<< HEAD` / `=======` / `>>>>>>>` markers into `tests/adv` (later removed). The branch looks rebased onto a rewritten base; please squash/fixup the secrets‑wiping and header‑enrichment chains (`fffd6ec`→`6068dba`→`96ca025`, `65aa987`→`e6bdf0b`) before merge so the history doesn't add‑then‑remove the same code.

Minor / nits

* `wipe_jwk_secret()` writes through the `const char *` returned by `json_string_value()` (API violation, pragmatically fine) and cleanses `json_string_length(k)` bytes, leaving the NUL terminator. Use `len + 1`. Also document that it mutates a _shared_ `json_t` (any other holder loses `"k"`).

* `validate_request_protected()` runs _after_ the transport KEM decapsulation + AES‑GCM decrypt; validating the header right after `jwe_from_compact()` would reject garbage cheaply.

* `is_valid_suite()` uses `strncmp(suite, SUITE_PREFIX, strlen(SUITE_PREFIX))`; prefer `sizeof(SUITE_PREFIX) - 1`.

* Protocol constants `KEM_VERSION`, `SUITE_PREFIX`, `DIR_REQUEST/DIR_RESPONSE` live in `pqc.c` (tests only see them because they `#include "pqc.c"`), while shell tests hardcode `"hybrid-v1"`. Move them to `pqc.h` and avoid duplicated literals in `tests/rec`.

* `crit` lists are inconsistent: the server emits `["kem_ver","suite","kid","kem_kid","msg_dir"]`, while `tests/rec` builds the request with only 4 entries (no `kid`). Pick one set and document it; also consider whether `kid` belongs in `crit` at all (RFC 7515 §4.1.11 semantics).

* The server never inspects the request's `crit`; RFC 7515 requires rejecting unknown critical parameters. Consider rejecting any `crit` entry outside the known set.

* `adv_kem_thp()` and `rec_kem()` duplicate the `matches[1]` → `strndup` → `read_keys` → status‑mapping boilerplate; a small helper would reduce the chance of the copies diverging (they already differ: 500 vs 400/404 handling).

* `src/keys.c` now includes `pqc.h` (which pulls in `http.h`) just for `KEM_ALG_*`/`is_valid_kem_alg`; consider moving these to `keys.h` or a tiny `kem_alg.h` to avoid a layering inversion.

* `snprintf(adv_kem_thp_endpoint, MAX_URL, ...)` with a user‑supplied endpoint is unchecked for truncation (same as the pre‑existing buffers, but this adds another instance of silently broken routing for long `-e` prefixes).

* `tests/keygen`/`tests/rotate-keys` call `jose jwk gen` inside `jose_supports_alg()` many times (entropy + runtime); `jose alg` listing would be cheaper.

* `OPENSSL_clear_free(enc_key_json, strlen(enc_key_json))` leaves the NUL byte uncleaned (same off‑by‑one as above).

Verdict: the uplift is directionally good and the req_digest rationale is sound, but items 1–3 should be addressed before merge (especially the unverified suite/kid echo, which undermines the security property the series claims to add), and items 4–9 are cheap, high‑value follow‑ups.

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

  • Unverified suite/kid echo — Fixed. The suite in the response header is now derived from the algorithm of the KEM key selected via the path (ECMR + alg_of(tang_kem_priv)), and the client-declared suite must match it exactly; kid must resolve through find_jwk() to an ECMR/deriveKey key actually held by tang; and clevis_kem_pub->alg must equal the tang key's algorithm — all three must agree, otherwise the request is rejected with 400. A downgrade/upgrade attempt (768 key, declared 1024 suite) is now covered by negative tests both in test-pqc and tests/rec.
  • VLA from attacker-controlled length — Fixed both ways suggested: decoded protected headers above 4 KiB are rejected outright, and the buffer is heap-allocated and freed as soon as the header JSON is parsed, so no attacker-controlled size ever touches the stack.

Medium priority

  • Negative header tests — Added test_validate_request_protected() calling the validator directly, covering missing/non-string/non-base64/non-JSON protected, wrong/missing msg_dir/kem_ver, kem_kid ≠ path, malformed suites (including a well-formed wrong variant), missing/non-string/unknown/non-ECMR kid, plus the happy path. tests/rec and the unit tests now assert req_digest is absent and that crit matches exactly, to prevent drift.
  • tangd-rotate-keys — Restructured to generate-then-swap: new keys are staged in a temporary directory and published (renamed) before the old ones are hidden, so a failure anywhere aborts non-zero with the old keys still advertised and /adv never breaks. "Unsupported" (checked via jose alg) is distinguished from "generation failed" (fatal, stderr visible); the same fix was applied to tangd-keygen. The hidden-key retention policy (never pruned automatically, remove manually once no client depends on them) is now documented in the man page. A failure-injection test verifies the daemon keeps serving through a failed rotation.
  • Unconditional OpenSSL dependency — libcrypto is now declared dependency('libcrypto', required: has_pqc) and linked into tangd/test-pqc only when the PQC path is built; pqc_noop.c needs nothing. Verified with a real has_pqc=false build (no direct DT_NEEDED on libcrypto, configure succeeds without libcrypto.pc).
  • History hygiene — The branch was reorganized: the duplicate of upstream 99b3af3, the conflict-marker commit, and its reverter (net effect zero) were dropped, and the secrets-wiping chains (65aa987+e6bdf0b, fffd6ec+6068dba+96ca025) and the header-enrichment pair (76732e0+147a9f7, so req_digest is never introduced) were squashed. The final tree is byte-identical to the pre-rewrite state (verified against the remote), all commits are signed, and the full test suite passes.

Minor nits

All 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;

  • Header validation moved before the KEM decapsulation/decrypt;
  • sizeof instead of strlen in is_valid_suite();
  • protocol constants moved to pqc.h with shell tests sourcing them from the header;
  • crit unified to the four extension parameters (kid removed per RFC 7515 §4.1.4/§4.1.11 semantics) and unknown request crit entries rejected;
  • adv_kem_thp()/rec_kem() now share one load_thp_keys() helper; KEM algorithm constants moved to a new kem_alg.h so keys.c no longer pulls in http.h; tangd refuses to start on endpoint-regex truncation;
  • tests' jose_supports_alg() uses the jose alg listing instead of generating probe keys.

Thanks again

sarroutbi and others added 3 commits November 17, 2026 14:21
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>
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>
@sarroutbi

Copy link
Copy Markdown
Collaborator Author

@rh-ssorce: thanks for all the reviews -- I think we are moving these PRs in a nice direction with your guidance, but I still have a few doubts here. @sarroutbi

1. A routine signing-key rotation bricks offline hybrid bindings. Reproduced at the current heads: bind offline with adv + adv_kem, run tangd-rotate-keys, and every later decrypt fails permanently with "KEM key signature verification failed (possible MITM)!". /adv/<thp> re-adds rotated signers (find_jws), but /adv-kem/<thp> signs with the current m_sign only (find_jws_kem_by_thp), and clevis verifies that fetch against the binding's frozen verify keys. Three ways out: (a) tang signs /adv-kem/<thp> with the retained signers too, mirroring /adv/<thp>; (b) clevis accepts the key on thumbprint == kem_kid when the signature check fails; (c) re-store the KEM pub. On (b): fetchKemKey already pins the key by kem_kid, which sits inside the tag-protected header and feeds the HKDF info, so at decrypt time the JWS adds nothing the thumbprint pin does not already provide. (a) is the smaller wire change; (c) undoes the kem_kid-only binding (09d017c). Either way, we need a decrypt-after-rotation regression test.

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.

2. /adv-kem verify keys for bindings with no stored adv. When the server reports tang_pub, clevis stores no advertisement at all -- every online binding is in this mode, carrying only kid/kem_kid. The classical leg got its answer: /rec returns the EC pub in the response. The KEM leg did not, and if I understood the recovery flow right: the verify keys for the signed /adv-kem/<kem_kid> fetch come from a live, unverified /adv (the ecmrRecover fallback). A MITM can supply its own KEM key there and read the PQ share in transit -- the ECMR leg is blinded, the KEM leg is not, so the hybrid's PQ half is lost in exactly the scenario it exists for. Failing closed would be the safe direction, but with no stored adv there is nothing to verify against, so it breaks every online binding. Two ways out, as I see it: extend the kem_kid pin from 1(b) to this path (if the thumbprint pin authenticates the key, the unverified /adv is not carrying the trust anyway), or have /rec return the KEM pub alongside tang_pub, mirroring what the classical leg already does.

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.

3. /version as a hard gate. fetchVersion folds every error into "no support" with downgrade advice, and tang's /version answers 200 hybrid_recovery:false even for a broken key store (that half is in the inline comments). If it stays a gate, the error paths need to tell "no support" from "server broken"; if not, dropping it simplifies the client.

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.

With a call on these, the rest appears to be straightforward on both sides.
Glad to read that

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>
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>
Comment thread src/pqc.c Resolved
Comment thread src/keys.c Resolved
Comment thread tests/adv Resolved
Comment thread src/keys.c Resolved
Comment thread src/pqc.c Resolved
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>
Comment thread src/pqc.c Resolved
Comment thread src/keys.c Resolved
Comment thread src/keys.c Resolved
Comment thread src/keys.c Resolved
Comment thread tests/test-keys.c.in Resolved
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>
Comment thread src/pqc.c Resolved
Comment thread src/keys.c Resolved
Comment thread src/tangd.c Resolved
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>
Comment thread src/pqc.c
if (!pqc_is_available())
return http_reply(HTTP_STATUS_NOT_FOUND, NULL);

thumbprint = load_thp_keys(path, matches, jwkdir, KEYS_READ_STRICT,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/keys.c
continue;
}
} else if (jwk_valid_for_deriving_keys(jwk)) {
} else if (jwk_valid_for_ecmr_recovery(jwk)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/keys.c
return 0;
}
}
json_array_foreach(tki->m_rotated_keys, idx, jwk) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread tests/test-pqc.c.in
* (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");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Comment thread src/keys.c
{
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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread tests/test-pqc.c.in
int saved = dup(fileno(stderr));
if (saved < 0)
return -1;
if (!freopen(path, "w", stderr)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/keys.c
* 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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants