Skip to content

refactor(proxy): derive fips_mode keys with cryptography KBKDF - #51822

Open
yucheng-berri wants to merge 2 commits into
mainfrom
litellm_fips_kbkdf_cryptography
Open

yucheng-berri wants to merge 2 commits into
mainfrom
litellm_fips_kbkdf_cryptography

Conversation

@yucheng-berri

@yucheng-berri yucheng-berri commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

<make-me-human-readable>
With general_settings.fips_mode: true, the proxy derives its MCP token keys and plugin claim keys from LITELLM_SALT_KEY with KBKDF (SP 800-108, HMAC-SHA256). That derivation was a hand-written ctypes binding into OpenSSL. It is now one call to the cryptography library's KBKDFHMAC, and every derived key is byte-for-byte the same, so tokens already issued keep working. Without fips_mode nothing changes
</make-me-human-readable>

Details

TLDR

Problem this solves:

  • _kbkdf_hmac_sha256 reached OpenSSL's EVP_KDF through about 45 lines of ctypes: a hand-declared OSSL_PARAM struct, five function prototypes and manual frees. litellm owned a C binding that no library maintains for us
  • It could not run on a Python that links OpenSSL statically (uv's managed builds), so its tests skipped there
  • A review of open source projects with FIPS builds found that each one derives keys through a mainstream crypto library, and none writes its own binding

How it solves it:

  • _kbkdf_hmac_sha256 is now KBKDFHMAC(SHA256, CounterMode, length=32, rlen=4, llen=4, BeforeFixed, label, context).derive(key) from cryptography, which the proxy already depends on
  • This is the same SP 800-108r1 construction OpenSSL's KBKDF runs by default: HMAC-SHA256(key, [1]_32 || label || 0x00 || context || [256]_32)
  • ctypes, _OsslParam, _param, the _OSSL_PARAM_* constants and _KBKDF_PROPERTIES are removed
  • derive_key_from_salt_key keeps its signature, its 32-byte hex check on LITELLM_SALT_KEY and its error text. The three callers (bridge_credentials.py, session_credentials.py, plugin_routes.py) are not touched

Linear ticket

Relates to LIT-8426

Relation to #50032: that PR added derive_key_from_salt_key and its ctypes KBKDF. This PR replaces only the function body that computes KBKDF. The keys, labels, contexts, salt key rule and the fips_mode_active() switch are as #50032 left them

Behavior changes

Removed / renamed

  • The private names _OsslParam, _param, _OSSL_PARAM_UTF8_STRING, _OSSL_PARAM_OCTET_STRING, _OSSL_PARAM_UNMODIFIED and _KBKDF_PROPERTIES are gone from encrypt_decrypt_utils.py. Nothing else in the repo used them except the shared fips_openssl test fixture, which is updated
  • The error text OpenSSL could not run KBKDF no longer exists. git grep at base finds it in two places only: the line that raised it and the one test that matched it, both removed here

Silent regressions to watch

  • None without fips_mode: derive_key_from_salt_key is only called when fips_mode_active() is true
  • With fips_mode: true the derived keys are unchanged, so session tokens, bridge envelopes and plugin claims minted before this PR open after it (proof below). What does change:
    1. The KDF no longer runs as the FIPS module's KBKDF service. cryptography computes the SP 800-108 counter loop in its own Rust code and calls OpenSSL only for HMAC-SHA256. On the Chainguard FIPS image that HMAC goes through libcrypto's HMAC_* functions, not through the provider's EVP_KDF KBKDF and not through its EVP_MAC service (traced on 11-06 for fix(mcp): derive MCP bridge and session keys with the FIPS provider's KBKDF #50032, not re-run here: an LD_PRELOAD trace of KBKDFHMAC.derive showed only HMAC_Init_ex, HMAC_Update and HMAC_Final, and cryptography 50.0.0's kdf.rs has no call to OpenSSL's KBKDF). The digest underneath is still fetched from the active provider. This is how the peer FIPS builds we reviewed derive keys: through their crypto library, not through a binding to the module's KDF service
    2. The module's own key-length check no longer applies. The Chainguard module refuses a KBKDF key under 112 bits. Re-measured on the image for this PR: with a 13-byte key base raises and head returns a key. derive_key_from_salt_key still refuses any LITELLM_SALT_KEY that is not at least 32 bytes of hex before the KDF is called, so no litellm caller can pass a short key
    3. The fips=yes pin is gone. Base fetched KBKDF with fips=yes, so it raised ValueError (a 500 on MCP token routes) when no FIPS provider could serve the fetch. Whether a proxy can be in that state:
      • Not at boot. fips_mode_active() is true only after enforce_fips_mode accepted fips_mode: true, and that requires Python's OpenSSL to have FIPS default properties and refuse scrypt, and cryptography's OpenSSL to have FIPS enabled and hash SHA-256 under it. Otherwise the proxy does not start
      • After boot, only if code in the process rewrites OpenSSL's default properties (EVP_set_default_properties(NULL, "provider=default")). No litellm code does that. Re-measured on the image: in that state base raises ValueError: OpenSSL could not run KBKDF and head returns the same key bytes, computed with the default provider's HMAC
      • By reading only, not measured: a host where Python and cryptography load two different libcrypto builds, and Python's has fips=yes default properties but no FIPS provider. The boot gate accepts that host. Base then raised on the first key derivation; head derives the key in cryptography's OpenSSL, the one the boot gate checked for a working FIPS provider
    4. Pythons with a statically linked OpenSSL now derive keys. On uv's managed CPython the ctypes binding could not reach EVP_KDF, so base raised and four tests skipped. Head runs there: the same test files give 0 skips on CPython 3.13.18 with static OpenSSL 3.5.9

Migration for existing customers

  • None required. No config, env var, stored value or token format changes

Regression tests

  • test_derive_key_from_salt_key_keeps_the_keys_fips_mode_deployments_already_issued (new, 10 cases) pins keys produced by the base ctypes implementation, as hex: both salt key spellings, empty context, empty label, a 256-byte binary context, a 100-byte salt key, and the four production labels (litellm-mcp-bridge:envelope-signing:, litellm-mcp-bridge:envelope-encryption:, litellm-mcp-gateway:session-signing:, litellm-plugin:session-claim:)
  • test_derive_key_from_salt_key_is_sp800_108_counter_mode_hmac_sha256 (existing) checks the KDF against the SP 800-108 formula computed by hand. It no longer needs the fips_openssl fixture or a shared libcrypto
  • test_derive_key_from_salt_key_refuses_an_openssl_without_a_fips_provider is removed with the pin it tested (item 3)
  • The "links OpenSSL statically, out of ctypes reach" skips are removed from test_encrypt_decrypt_utils.py, test_session_credentials.py and test_plugin_routes.py
  • The salt key refusal tests in tests/unit/proxy/mcp_server/outbound_credentials are unchanged and pass

Mutations of the new implementation at 2152227, each run on test_encrypt_decrypt_utils.py, tests/unit/proxy/mcp_server/outbound_credentials and test_plugin_routes.py (907 tests, all green before), then restored:

  • rlen 4 -> 2: 14 failed (all 10 pinned keys, both formula cases, 2 caller tests)
  • llen 4 -> 2: 14 failed
  • Counter after the fixed input, not before: 14 failed
  • Label and context swapped: 14 failed
  • SHA256 -> SHA384: 14 failed
  • Separator byte and length field dropped (fixed=label + context): 14 failed
  • Context dropped: 14 failed (9 of 10 pinned keys; the tenth has an empty context)
  • Label dropped: 13 failed (9 of 10 pinned keys; the tenth has an empty label)
  • Key bytes reversed: 9 failed
  • sk- prefix handling broken (wrong hex slice): 14 failed
  • Salt key minimum lowered from 32 to 16 bytes: 1 failed (the existing refusal test)

Pre-Submission checklist

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Screenshots / Proof of Fix

E2E exception at d289a07. Scope: one private function body swapped for a library call with the same inputs and outputs. Rationale: the only observable of this function is the 32 bytes it returns, and those are compared byte for byte against base below, including inside the Chainguard FIPS image. Callers, routes, config and token formats are untouched

Head returns the same bytes as base

Base is encrypt_decrypt_utils.py from main 3ad1643 (ctypes EVP_KDF, with _KBKDF_PROPERTIES set to None because this host has no FIPS provider). Both run in one process on CPython 3.12.3, where hashlib uses the system OpenSSL 3.0.13 and cryptography 50.0.0 uses its bundled OpenSSL 4.0.1

$ python equiv.py base_encrypt_decrypt_utils.py old_vectors.json
python 3.12.3 | hashlib: OpenSSL 3.0.13 30 Jan 2024 | cryptography 50.0.0 on OpenSSL 4.0.1 9 Jun 2026
random inputs: 5000 of 5000 byte-identical (key 32-200 bytes, label 0-300, context 0-1000)
saved base vectors: 10 of 10 identical through derive_key_from_salt_key
bad salt keys: 5 of 5 raise the same ValueError text on base and head

The 10 saved vectors are the ones hard-coded in the new test. They were written by base before the change:

$ python gen_vectors.py   # base tree, ctypes implementation asserted in the script
python 3.12.3 | OpenSSL 3.0.13 30 Jan 2024 | _hashlib shared: True | get_fips_mode 0
label litellm-test:label:                      context sk-test-master-key  -> 8984eed36332e32c815b17a7b7af615c12a39689069999b8002b1e126e8205a1
label litellm-test:label:                      context (empty)             -> 6e5325ba09ebcba77ad8ebda431cbfb4f07132f79de05558f62d6dc7df4cb856
label (empty)                                  context sk-test-master-key  -> 64d895aba9f82a9601af527f0d54333e629af122011a8f979bd1306a1b4eaa2e
label litellm-test:label:                      context bytes(range(256))   -> ec14e121031c15fdc0e0c9a1fe5865d721ee0aecb566d35f895d93a6d310d2d2
label litellm-mcp-bridge:envelope-signing:     context sk-test-master-key  -> f79c523d3eb85f1c76e690f5952f64fd2f4bd8974316c284e4588ca6a45b5a32
label litellm-mcp-bridge:envelope-encryption:  context sk-test-master-key  -> 3a5a1c0d6869e879ff6b8ac216a1391640ee6cd23d73fcc9b684e9995db22f7c
label litellm-mcp-gateway:session-signing:     context sk-test-master-key  -> 96bf0dfc44b74e843737e6eb2f00cf263eb9c1a2a1da5f8478d0020f246cf0f6
label litellm-plugin:session-claim:            context chat-ui             -> 137c07f867c139b131bb4beb86dc3de5612d856c4c40a8461ca371f02743bb37
100-byte salt key, session-signing label       context sk-mmm... (67 bytes)-> ea8946893757df506a43285c984aa1810e8c8603a035d5b296a3cdfae468cadf

The first value is also what the FIPS provider's KBKDF returned for the same inputs on the Chainguard image in #50032's check

The three MCP label rows were regenerated at d289a07 with the context sk-test-master-key, because the repo's check_no_publicly_known_master_key check refuses the literal used first. They come from the same base ctypes function, run on CPython 3.14.6 with OpenSSL 3.6.5 on a Mac, and that run reproduced the first row's value as a control. The equiv.py and Chainguard runs on this page used the earlier 10 vectors, which differ only in that context

Chainguard FIPS image

litellm-fips-b2cg:head (OpenSSL 4.0.3 with the Chainguard FIPS provider, CPython 3.13.18, cryptography 50.0.0 built against that OpenSSL), with base's or head's encrypt_decrypt_utils.py mounted over the image's copy. Same output under the image defaults and CHAINGUARD_LEGACY_ALLOWED=0

variant base (ctypes EVP_KDF) | python 3.13.18 | hashlib OpenSSL 4.0.3 29 Sep 2026 | cryptography 50.0.0 on OpenSSL 4.0.3 29 Sep 2026
get_fips_mode 1 | cryptography is_fips_enabled True
enforce_fips_mode(fips_mode: true) accepted | fips_mode_active True
derive_key_from_salt_key on the 10 pinned vectors: 10 identical
_kbkdf_hmac_sha256 with a 32-byte key: returns 56ee569520bd7530...
_kbkdf_hmac_sha256 with a 14-byte key: returns a143009c63614082...
_kbkdf_hmac_sha256 with a 13-byte key: ValueError: OpenSSL could not run KBKDF
_kbkdf_hmac_sha256 with a 7-byte key: ValueError: OpenSSL could not run KBKDF
after the boot gate: default fetch KBKDF -> fips, HMAC -> fips | derive_key_from_salt_key returns the key, same bytes: True
EVP_set_default_properties(NULL, 'provider=default') -> 1
default properties repointed: default fetch KBKDF -> default, HMAC -> default | fips_mode_active True | derive_key_from_salt_key ValueError: OpenSSL could not run KBKDF

variant head (cryptography KBKDFHMAC) | python 3.13.18 | hashlib OpenSSL 4.0.3 29 Sep 2026 | cryptography 50.0.0 on OpenSSL 4.0.3 29 Sep 2026
get_fips_mode 1 | cryptography is_fips_enabled True
enforce_fips_mode(fips_mode: true) accepted | fips_mode_active True
derive_key_from_salt_key on the 10 pinned vectors: 10 identical
_kbkdf_hmac_sha256 with a 32-byte key: returns 56ee569520bd7530...
_kbkdf_hmac_sha256 with a 14-byte key: returns a143009c63614082...
_kbkdf_hmac_sha256 with a 13-byte key: returns 88dc65c2de29f83b...
_kbkdf_hmac_sha256 with a 7-byte key: returns 6523a85810955c61...
after the boot gate: default fetch KBKDF -> fips, HMAC -> fips | derive_key_from_salt_key returns the key, same bytes: True
EVP_set_default_properties(NULL, 'provider=default') -> 1
default properties repointed: default fetch KBKDF -> default, HMAC -> default | fips_mode_active True | derive_key_from_salt_key returns the key, same bytes: True

So on the real FIPS image the provider's KBKDF (base) and cryptography (head) return the same 10 keys, and the two differences are the ones declared above: the short-key refusal and the behavior after the default properties are repointed

Tests and gates

On the GCP dev VM at 2152227 (d289a07 changes only three test vectors; test_encrypt_decrypt_utils.py rerun there on a Mac: 49 passed)

$ pytest tests/unit/proxy/common_utils tests/unit/proxy/mcp_server/outbound_credentials tests/unit/proxy/test_plugin_routes.py -n 16
3350 passed, 994 warnings in 59.36s          # CPython 3.13.18, statically linked OpenSSL 3.5.9, 0 skipped

$ pytest tests/unit/proxy/common_utils/test_encrypt_decrypt_utils.py tests/unit/proxy/common_utils/test_fips.py \
    tests/unit/proxy/mcp_server/outbound_credentials tests/unit/proxy/test_plugin_routes.py -n 16
2 failed, 933 passed in 33.93s               # CPython 3.12.3, system OpenSSL 3.0.13

The 2 failures on 3.12 are test_sso_assertion_store.py rotation tests failing with ModuleNotFoundError: No module named 'prisma.models': that borrowed venv has no generated Prisma client. They pass in the 3.13 run above, where it is generated

Wider sweep, run on a Mac (the VM login had expired), CPython 3.12.13 with statically linked OpenSSL 3.5.7:

$ pytest tests/unit/proxy/common_utils tests/unit/proxy/mcp_server tests/unit/proxy/test_plugin_routes.py \
    tests/unit/proxy/utils/prisma_and_spend/test_password_helpers.py tests/unit/llms/custom_httpx/test_http_handler.py -n 6
10371 passed, 1 skipped, 2142 warnings in 130.68s    # the skip is test_mcp_server.py:27 "Local only test"
gates at 2152227844df5ceddc67f10603b4569153d082f0 vs base 3ad164382b1c4bf72c37fda0b2468a62168b365b
ruff_strict_gate      OK: no strict rule grew past its merge-base count
type_discipline_gate  OK: no LIT rule grew past its merge-base count
test_quality_gate     OK: no TQ rule grew past its merge-base count
type_check_gate       OK: every basedpyright rule is within its ceiling (94690 errors total)

openapi_docs_gate was left to CI

Type

🧹 Refactoring

Caveats (if any)

Medium

  • In fips_mode the key derivation is computed by cryptography over HMAC-SHA256 and is no longer the FIPS module's KBKDF service (Behavior changes, items 1 to 3). Whether a deployment's compliance statement needs the KDF itself to be a module service is a policy question this PR does not answer; it follows what peer FIPS builds do

Low

  • The LD_PRELOAD trace behind item 1 is from 11-06 on the same image and cryptography version, and was not re-run for this PR
  • No live proxy run: the proof is the byte comparison above (E2E exception)

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

Note

Medium Risk
Touches FIPS key derivation for MCP tokens and plugin session claims; outputs are pinned in tests but compliance may differ from OpenSSL’s FIPS KBKDF service path.

Overview
When general_settings.fips_mode is on, MCP and plugin keys still come from LITELLM_SALT_KEY via SP 800-108 counter-mode HMAC-SHA256 KBKDF, but _kbkdf_hmac_sha256 no longer uses a hand-rolled ctypes binding to OpenSSL’s EVP_KDF. It now delegates to cryptography’s KBKDFHMAC, dropping ctypes, _OsslParam, and the fips=yes fetch path.

derive_key_from_salt_key keeps the same contract and salt-key validation; callers are unchanged. Tests add 10 pinned output vectors so existing FIPS deployments keep the same derived keys, drop skips for statically linked OpenSSL, and remove the test that expected OpenSSL could not run KBKDF when no FIPS KBKDF provider is available.

Reviewed by Cursor Bugbot for commit d289a07. Bugbot is set up for automated code reviews on this repo. Configure here.

Replace the ctypes binding to OpenSSL EVP_KDF with cryptography's KBKDFHMAC
(SP 800-108r1 counter mode, HMAC-SHA256, 32-bit counter before the fixed
input, 32-bit length after). The derived bytes are unchanged; a known-answer
test pins keys produced by the ctypes implementation.
@veria-ai

veria-ai Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

The PR refactors proxy key derivation in FIPS mode to use cryptography’s KBKDF implementation for MCP/plugin encryption keys.

One issue remains open: the replacement KBKDF implementation can run outside the FIPS provider’s validated derivation service even when startup FIPS checks pass. This creates a FIPS assurance gap, rather than a demonstrated key compromise; matching known-answer vectors does not establish validation of the implementation. No issues have been addressed yet.

Open issues (1)

Fixed/addressed: 0 · PR risk: 4/10

Reviews

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ Devin Review: No Issues Found

Devin Review analyzed this PR and found no bugs or issues to report.

Devin Review

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@greptile-apps

greptile-apps Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with no new actionable findings.

Summary

Replaces the hand-written OpenSSL binding with KBKDFHMAC and adds fixed compatibility vectors. The latest changes replace three test contexts and their expected keys. All three replacement keys match the derivation formula. No new actionable issues were found.

yucheng-berri accepted the previously raised FIPS caveat as intentional because the maintainer chose library-based derivation knowing it leaves the module's KBKDF service. Human approval remains the stated sign-off.

  • FIPS-mode proxy keys now use cryptography's KBKDF.

Reviews (3) · Last reviewed commit: "test(proxy): pin the production-label KB..." · Reviewed by Greptile

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.kbkdf import KBKDFHMAC, CounterLocation, Mode

return KBKDFHMAC(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium: Preserve provider-backed key derivation in FIPS mode

In cryptography 50.0.0, KBKDFHMAC constructs counter-mode KBKDF in Rust over HMAC rather than invoking OpenSSL's EVP_KDF, so the startup FIPS checks can pass while MCP/plugin key derivation runs outside the provider's validated KBKDF service. (raw.githubusercontent.com) Keep an explicitly FIPS-provider-backed KBKDF for this path; matching known-answer vectors establishes compatibility, not validation of the replacement implementation. (csrc.nist.gov)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is the change the PR makes on purpose, and it is declared in the description under Behavior changes, items 1 to 3: in fips_mode the SP 800-108 counter loop is now computed by cryptography over HMAC-SHA256 and is no longer the provider's EVP_KDF KBKDF service. The known-answer vectors are there to show the keys do not change, not to claim validation of the replacement.

Keeping a provider-backed KBKDF means keeping the hand-written ctypes binding to EVP_KDF, since cryptography exposes no binding to OpenSSL's KBKDF. That binding is what this PR removes: a review of open source projects with FIPS builds found each one derives keys through its crypto library and none maintains its own binding to the module's KDF service. What remains in place: the boot gate still refuses fips_mode unless both Python's and cryptography's OpenSSL enforce FIPS, the HMAC digest is still served by the active provider, and derive_key_from_salt_key still refuses a LITELLM_SALT_KEY under 32 bytes of hex.

Not changing the code for this. Whether a deployment's compliance statement needs the KDF itself to be a module service is listed as an open caveat in the description for the maintainers to decide.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

@codspeed

codspeed Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 1 benchmark is dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 44 untouched benchmarks


Comparing litellm_fips_kbkdf_cryptography (d289a07) with main (d81c55f)

Open in CodSpeed

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

@codecov

codecov Bot commented Nov 14, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit d289a07. Configure here.

This branch has not been deployed

No deployments
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.

1 participant