Skip to content

Tang Hybrid PQC Recovery implementation - #165

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

sarroutbi wants to merge 84 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 71.03825% with 53 lines in your changes missing coverage. Please review.
✅ Project coverage is 72.65%. Comparing base (83de399) to head (127b3f1).
⚠️ Report is 8 commits behind head on master.

Files with missing lines Patch % Lines
src/keys.c 69.04% 18 Missing and 21 partials ⚠️
src/tangd.c 72.72% 0 Missing and 9 partials ⚠️
src/http.c 0.00% 0 Missing and 2 partials ⚠️
src/pqc.h 60.00% 0 Missing and 2 partials ⚠️
src/pqc_noop.c 92.30% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           master     #165       +/-   ##
===========================================
+ Coverage   58.44%   72.65%   +14.20%     
===========================================
  Files           4        7        +3     
  Lines         580      735      +155     
  Branches      147      201       +54     
===========================================
+ Hits          339      534      +195     
+ Misses        140       96       -44     
- Partials      101      105        +4     

☔ 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>
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 Resolved
Comment thread src/keys.c Resolved
Comment thread src/keys.c Resolved
Comment thread tests/test-pqc.c.in Resolved
Comment thread src/keys.c Resolved
Comment thread tests/test-pqc.c.in Resolved
Comment thread src/keys.c Resolved
The recovery read restored /rec and /rec-kem for classical clients,
but not for hybrid ones: a hybrid client always fetches
/adv-kem/<kem_kid> before /rec-kem, and that advertisement reads the
store strictly, so with no usable signer it answers 500 and the
hybrid unlock stops there -- /rec-kem is never reached through the
client path. In the default tang_pub mode the fetch fails earlier,
at /adv, for the same reason. The round trip the recovery mode
restored is not one a real client can drive for a hybrid binding.

The comments claiming a store without a usable signer "still serves
unlocking for every existing client" read broader than that, so they
now state the split precisely: classical recovery keeps serving,
hybrid recovery needs a usable signer. adv_kem_thp() documents why
it deliberately stays strict -- the advertisement must be signed,
and a store without a usable signer has nothing to sign it with --
and that serving it in recovery mode anyway, signed with whatever
signers remain usable, would change what the signature on this
fetch is for, which is left for its own discussion.

rec-broken-signer also asserted more than it drove: it built the
/rec-kem request from the KEM key on disk instead of fetching the
advertisement. It now asserts the client-path order --
/adv-kem/<kem_kid> answers 500 next to the /rec-kem 200 -- so the
test says what actually works: the endpoint serves, the client path
cannot reach it.

Verified by rec-broken-signer and the full suite, both green with
the new assertion in place.

Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
One more shape got through the ECMR branch of
prepare_payload_and_sign(): a key with kty EC, alg ECMR and key_ops
[sign, verify, deriveKey] passes the sign+verify permission check,
fails the signature probe (no signature algorithm can be inferred
for ECMR), and then lands in the ECMR branch. jose_jwk_pub strips
sign but keeps verify, so the advertisement carries the key as
[verify, deriveKey] while nothing signs with it: /adv answers 200
and /version stays healthy, but every new binding fails client
side, since jose jws ver -a refuses the whole advertisement when a
verify key has no matching signature. key_ops [verify, deriveKey]
with no sign at all reaches the same place, since the branch never
looked at the sign or verify permissions. Before the signature
probe existed this shape took /adv down with a 404, which was at
least visible on the server.

The ECMR branch now also requires the key to carry no sign or
verify permission (jose_jwk_prm with req = true, so an unrestricted
key counts as carrying neither), so a key that looks like a signer
cannot be published as an exchange key. Only publication is
refused: the shared recovery predicate is unchanged, so /rec and
/rec-kem keep serving such keys for existing bindings, and the
healing trigger keeps counting them as deriving keys.

Verified by test_read_keys_signer_looking_exc_not_advertised, which
pins both shapes absent from the payload next to the healthy keys,
and by the /adv e2e cases, which pin the advertisement free of both
shapes and still passing the client-side validate() -- the exact
jose jws ver -a check that broke. Both fail without the fix, and
the full suite is green in the PQC, default and no-OpenSSL builds.

Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
The healing trigger almost never fires on a store that has been
rotated: store_lacks_deriving_keys() counts rotated ECMR keys, but
the advertisement only ever holds active keys, and the strict read
was satisfied by a signer alone. Keygen, one rotation, and then
removing alg from the active ECMR key left /adv answering 200 with
only the ES512 verify key, /version looking fine, and nothing
healing -- the file count unchanged across requests -- while every
new binding failed client side, classic and hybrid alike. A deleted
or truncated ECMR file takes the same path, since load_keys skips
what does not parse. The heal tests only used stores that were
never rotated, so nothing pinned this.

The strict read now also requires the advertised payload to hold a
deriving key, and answers 500 -- the broken-store signal this
series already uses -- instead of healing. The healing trigger is
unchanged: it keeps counting rotated keys, so a rotated store never
regenerates a duplicate key set, and the recovery read keeps
serving the rotated key. The payload check also subsumes the old
non-empty-payload requirement: a signer-only advertisement is
exactly the state it refuses.

Verified by test_read_keys_rotated_store_broken_active_deriving_key,
which pins the repro -- strict read NULL, healing quiet, rotated key
recoverable -- and by the new /adv 500, /version 500 and /rec 200
assertions for the rotated key over HTTP in the errors test. The
strict assertion in test_read_keys_for_recovery_rotated_deriving_key
now names both failure reasons, since it pinned the no-heal
behavior only as a side effect. Both new tests fail without the
fix, and the full suite is green in the PQC, default and
no-OpenSSL builds.

Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
The pub-only ES512 key in scenario 2 never makes jose print, so the
"no jose line" half of the assertion could not fail: putting the
signature probe back on a NULL cfg kept the whole suite green while
jose's JOSE_CFG_ERR_ALG_NOINFER line returned to stderr on a live
server. The shape that makes the probe complain is a hidden ECMR key
with key_ops deleted -- unrestricted, so it passes the sign
permission check, but no signature algorithm can be inferred for
ECMR.

Scenario 2 now drops one of those next to the pub-only ES512 and
asserts exactly two skip lines, each with its thumbprint, in either
order (the rotated array follows the directory order of the hidden
files). Any jose line -- or any other output -- breaks the
assertion.

Verified by an experiment as the negative control: with
the probe reverted to a NULL cfg the test fails on the extra jose
line, and it is green with the quiet callback in place. The full
suite passes in the PQC and default builds.

Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
The material checks were string-length checks: a KEM key whose
"priv" was swapped from another ML-KEM key, truncated or simply
corrupt still passed admission, was advertised, and clients bound to
it, since encapsulation only needs "pub". Every recovery then failed
with 400, with jose refusing the key at decapsulation time ("JWK
'pub' does not match the private key") and the error landing in the
server log. A corrupt "d" on an ECMR key gave the same picture on
the classical side, and since the predicates passed, the store never
repaired itself. This needs write access to the key directory, so it
is an operator-error shape rather than an attack -- but it fails
closed and silently, so admission now runs the check jose runs at
decapsulation time.

jwk_valid_for_kem_exchange() gains an encapsulation/decapsulation
round trip -- the same pair of calls /rec-kem performs -- comparing
the shared secrets on top, and jwk_valid_for_ecmr_recovery() gains
an exchange of the key with itself, which jose refuses for a private
member that does not correspond to the public ones. The ECMR probe
stays in keys.c with its predicate; the KEM predicate moves to the
pqc layer, where the PQC functions belong: declared in pqc.h, with
the structural material check as a self-contained inline there (the
way kem_alg.h shares is_valid_kem_alg()), the probing implementation
in pqc.c and a structural fallback in pqc_noop.c for builds whose
jose does not declare the ML-KEM API -- which also keeps the
jose_jwk_kem_enc/dec calls out of keys.c, which is compiled into
every build and every test binary. When the runtime cannot run
ML-KEM, pqc_is_available() gates the probe down to the same
structural fallback: every KEM endpoint is hidden in that state
anyway. The probes run under the quiet jose configuration, and the
ephemeral shared secrets are cleansed before release, as jose's own
guidance asks. Sharing the predicates keeps the series' invariant:
such a key is neither advertised nor reachable through /rec or
/rec-kem (403, like the public-only shapes), and the healing trigger
no longer counts it, so a never-rotated store repairs itself instead
of serving advertisements nothing can recover with.
test_read_keys_with_advertised_akp now generates a real ML-KEM key,
since fabricated material no longer passes admission, and test-keys
links the build's pqc flavor so the key-store tests exercise the
same predicate the daemon does.

Verified by test_jwk_valid_for_kem_exchange_rejects_mismatched_
privates and the corrupt-d and swapped-d ECMR unit tests, plus the
/adv-kem 404, /rec-kem 403 and /rec 403 e2e cases. Unwiring the
probes makes all of them fail -- the unit tests on the admitted
keys, the e2e tests on the 200/400 answers -- and the full suite is
green in the PQC, default, no-OpenSSL and pqc=disabled builds.

Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
freopen() gives stderr a fully buffered heap buffer, and the dup2()
in restore_stderr() only retargets the descriptor: the buffer
survives the restore. An abort() after a failed assertion never
flushes it, so the diagnostic message is lost -- a failing
ASSERT_WITH_MSG in the skip log policy test produced nothing, while
the earlier captured stderr arrived intact. setvbuf(stderr, NULL,
_IONBF, 0) after the dup2 puts stderr back on the process default
of unbuffered, and the same call after the freopen() keeps a
mid-capture abort from swallowing its message into capture.log
either.

Verified by tampering the expected skip line: the test aborts with
no diagnostic before the fix and prints the full "unexpected skip
log" message after it. The full suite passes.

Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
The comment above keys_satisfy_read_mode() said 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 holds for that reason instead: the
condition looks at deriving keys alone, so it never fires while
they are healthy -- even though the regeneration would include a
signer -- and a broken-signer store is left alone.

The comment above jwk_valid_for_signing() said the KEM advertisement
path no longer uses it, but classify_retained_signer() does, as its
silent-skip pre-check for retained keys that were never signers. It
now names both users.

Signed-off-by: Sergio Arroutbi <sarroutb@redhat.com>
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