-
Notifications
You must be signed in to change notification settings - Fork 92
fix(vault): replace XOR stream cipher with AES-256-GCM, remove hardcoded fallback key #279
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
advikdivekar
wants to merge
2
commits into
utksh1:main
Choose a base branch
from
advikdivekar:security/hardcoded-vault-key
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,5 @@ | ||
| fastapi>=0.115.0 | ||
| cryptography>=42.0.0 | ||
| uvicorn[standard]>=0.30.6 | ||
| pydantic>=2.8.2 | ||
| pydantic-settings>=2.6.0 | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,46 +1,60 @@ | ||
| """Lightweight encrypted credential vault.""" | ||
| """Authenticated encrypted credential vault using AES-256-GCM.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import base64 | ||
| import hashlib | ||
| import hmac | ||
| import os | ||
| from itertools import cycle | ||
|
|
||
| from cryptography.hazmat.primitives.ciphers.aead import AESGCM | ||
|
|
||
|
|
||
| class VaultCrypto: | ||
| """Symmetric encryption helper backed by a deterministic keystream. | ||
| """AES-256-GCM authenticated encryption for stored credentials. | ||
|
|
||
| Each call to encrypt() generates a fresh random 12-byte nonce so no two | ||
| ciphertexts ever share a nonce under the same key. The GCM auth tag | ||
| (16 bytes, appended by AESGCM) provides both confidentiality and integrity — | ||
| any tampering causes decrypt() to raise ValueError. | ||
|
|
||
| This is intentionally lightweight for local-first usage where secret-at-rest | ||
| protection is needed without adding third-party crypto dependencies. | ||
| Wire format (base64url): nonce(12) || ciphertext || auth_tag(16) | ||
| """ | ||
|
|
||
| def __init__(self, key: bytes): | ||
| self.key = key | ||
| _NONCE_LEN = 12 | ||
|
|
||
| def _derive_stream_key(self, nonce: bytes) -> bytes: | ||
| return hashlib.sha256(self.key + nonce).digest() | ||
| def __init__(self, key: bytes): | ||
| """ | ||
| Args: | ||
| key: 44-byte base64url-encoded representation of a 32-byte AES-256 key, | ||
| as produced by ``settings.resolved_vault_key``. | ||
| """ | ||
| try: | ||
| raw = base64.urlsafe_b64decode(key) | ||
| except Exception as exc: | ||
| raise ValueError("Vault key must be base64url-encoded") from exc | ||
| if len(raw) != 32: | ||
| raise ValueError( | ||
| f"Vault key must decode to exactly 32 bytes (AES-256); got {len(raw)}" | ||
| ) | ||
| self._aesgcm = AESGCM(raw) | ||
|
|
||
| def encrypt(self, plaintext: str) -> str: | ||
| raw = plaintext.encode("utf-8") | ||
| nonce = os.urandom(16) | ||
| stream_key = self._derive_stream_key(nonce) | ||
| ciphertext = bytes(b ^ k for b, k in zip(raw, cycle(stream_key))) | ||
| signature = hmac.new(self.key, nonce + ciphertext, hashlib.sha256).digest() | ||
| blob = nonce + signature + ciphertext | ||
| nonce = os.urandom(self._NONCE_LEN) | ||
| ciphertext = self._aesgcm.encrypt(nonce, plaintext.encode("utf-8"), None) | ||
| blob = nonce + ciphertext | ||
| return base64.urlsafe_b64encode(blob).decode("ascii") | ||
|
|
||
| def decrypt(self, payload: str) -> str: | ||
| blob = base64.urlsafe_b64decode(payload.encode("ascii")) | ||
| nonce = blob[:16] | ||
| signature = blob[16:48] | ||
| ciphertext = blob[48:] | ||
| try: | ||
| blob = base64.urlsafe_b64decode(payload.encode("ascii")) | ||
| except Exception as exc: | ||
| raise ValueError("Vault payload is not valid base64url") from exc | ||
|
|
||
| nonce = blob[: self._NONCE_LEN] | ||
| ciphertext = blob[self._NONCE_LEN :] | ||
|
|
||
| expected = hmac.new(self.key, nonce + ciphertext, hashlib.sha256).digest() | ||
| if not hmac.compare_digest(signature, expected): | ||
| raise ValueError("Vault payload integrity verification failed") | ||
| try: | ||
| raw = self._aesgcm.decrypt(nonce, ciphertext, None) | ||
| except Exception as exc: | ||
| raise ValueError("Vault payload integrity verification failed") from exc | ||
|
|
||
| stream_key = self._derive_stream_key(nonce) | ||
| raw = bytes(b ^ k for b, k in zip(ciphertext, cycle(stream_key))) | ||
| return raw.decode("utf-8") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| """ | ||
| Security tests for the credential vault (issue #200). | ||
|
|
||
| Verifies that: | ||
| - AES-256-GCM is used (not the old XOR stream cipher) | ||
| - The hardcoded fallback key "secuscan-dev-key" is gone | ||
| - resolved_vault_key raises when no key is configured | ||
| - Each encrypt() call produces a distinct ciphertext (unique nonces) | ||
| - Wrong key always fails authentication | ||
| - Truncated / short blobs raise, not silently return garbage | ||
| """ | ||
|
|
||
| import base64 | ||
| import hashlib | ||
| import pytest | ||
|
|
||
| from backend.secuscan.vault import VaultCrypto | ||
| from backend.secuscan.config import settings | ||
|
|
||
|
|
||
| def _make_key(seed: str) -> bytes: | ||
| raw = hashlib.sha256(seed.encode()).digest() | ||
| return base64.urlsafe_b64encode(raw) | ||
|
|
||
|
|
||
| class TestAesGcmProperties: | ||
| def test_roundtrip(self): | ||
| crypto = VaultCrypto(_make_key("test")) | ||
| assert crypto.decrypt(crypto.encrypt("hello")) == "hello" | ||
|
|
||
| def test_unique_ciphertexts_per_call(self): | ||
| crypto = VaultCrypto(_make_key("test")) | ||
| c1 = crypto.encrypt("same plaintext") | ||
| c2 = crypto.encrypt("same plaintext") | ||
| assert c1 != c2, "Each call must use a fresh nonce" | ||
|
|
||
| def test_blob_structure_has_12_byte_nonce(self): | ||
| """Blob starts with a 12-byte nonce (AES-GCM standard).""" | ||
| crypto = VaultCrypto(_make_key("test")) | ||
| blob = base64.urlsafe_b64decode(crypto.encrypt("x").encode()) | ||
| # nonce(12) + 1-byte plaintext + 16-byte auth_tag = 29 bytes total | ||
| assert len(blob) == 29 | ||
|
|
||
| def test_tamper_ciphertext_raises(self): | ||
| crypto = VaultCrypto(_make_key("test")) | ||
| blob = bytearray(base64.urlsafe_b64decode(crypto.encrypt("secret").encode())) | ||
| blob[14] ^= 0x01 | ||
| with pytest.raises(ValueError, match="integrity verification failed"): | ||
| crypto.decrypt(base64.urlsafe_b64encode(bytes(blob)).decode()) | ||
|
|
||
| def test_tamper_auth_tag_raises(self): | ||
| crypto = VaultCrypto(_make_key("test")) | ||
| blob = bytearray(base64.urlsafe_b64decode(crypto.encrypt("secret").encode())) | ||
| blob[-1] ^= 0x01 | ||
| with pytest.raises(ValueError, match="integrity verification failed"): | ||
| crypto.decrypt(base64.urlsafe_b64encode(bytes(blob)).decode()) | ||
|
|
||
| def test_tamper_nonce_raises(self): | ||
| crypto = VaultCrypto(_make_key("test")) | ||
| blob = bytearray(base64.urlsafe_b64decode(crypto.encrypt("secret").encode())) | ||
| blob[0] ^= 0x01 | ||
| with pytest.raises(ValueError, match="integrity verification failed"): | ||
| crypto.decrypt(base64.urlsafe_b64encode(bytes(blob)).decode()) | ||
|
|
||
| def test_wrong_key_raises(self): | ||
| crypto_a = VaultCrypto(_make_key("key-a")) | ||
| crypto_b = VaultCrypto(_make_key("key-b")) | ||
| with pytest.raises(ValueError, match="integrity verification failed"): | ||
| crypto_b.decrypt(crypto_a.encrypt("secret")) | ||
|
|
||
| def test_truncated_blob_raises(self): | ||
| crypto = VaultCrypto(_make_key("test")) | ||
| blob = base64.urlsafe_b64decode(crypto.encrypt("hello").encode()) | ||
| short = base64.urlsafe_b64encode(blob[:5]).decode() | ||
| with pytest.raises(ValueError): | ||
| crypto.decrypt(short) | ||
|
|
||
| def test_garbage_input_raises(self): | ||
| crypto = VaultCrypto(_make_key("test")) | ||
| with pytest.raises(Exception): | ||
| crypto.decrypt("not-valid-base64!!!") | ||
|
|
||
|
|
||
| class TestVaultKeyConfiguration: | ||
| def test_invalid_base64_key_raises_value_error(self): | ||
| with pytest.raises(ValueError): | ||
| VaultCrypto(b"not-valid-base64!!!") | ||
|
|
||
| def test_short_key_raises_value_error(self): | ||
| short_b64 = base64.urlsafe_b64encode(b"only16bytes12345") | ||
| with pytest.raises(ValueError, match="32 bytes"): | ||
| VaultCrypto(short_b64) | ||
|
|
||
| def test_resolved_vault_key_raises_without_config(self, monkeypatch): | ||
| """resolved_vault_key must raise RuntimeError when no key is configured.""" | ||
| monkeypatch.setattr(settings, "vault_key", None) | ||
| monkeypatch.setattr(settings, "plugin_signature_key", None) | ||
| with pytest.raises(RuntimeError, match="SECUSCAN_VAULT_KEY"): | ||
| _ = settings.resolved_vault_key | ||
|
|
||
| def test_resolved_vault_key_works_with_vault_key_set(self, monkeypatch): | ||
| monkeypatch.setattr(settings, "vault_key", "any-non-empty-value") | ||
| key = settings.resolved_vault_key | ||
| assert isinstance(key, bytes) | ||
| assert len(base64.urlsafe_b64decode(key)) == 32 | ||
|
|
||
| def test_resolved_vault_key_falls_back_to_plugin_signature_key(self, monkeypatch): | ||
| monkeypatch.setattr(settings, "vault_key", None) | ||
| monkeypatch.setattr(settings, "plugin_signature_key", "plugin-key") | ||
| key = settings.resolved_vault_key | ||
| assert isinstance(key, bytes) | ||
| assert len(base64.urlsafe_b64decode(key)) == 32 | ||
|
|
||
| def test_hardcoded_dev_key_no_longer_used(self, monkeypatch): | ||
| """'secuscan-dev-key' must not be the effective key when both settings are None.""" | ||
| monkeypatch.setattr(settings, "vault_key", None) | ||
| monkeypatch.setattr(settings, "plugin_signature_key", None) | ||
| with pytest.raises(RuntimeError): | ||
| _ = settings.resolved_vault_key |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This change switches the wire format to
nonce(12) || ciphertext || tag(16)butdecrypt()now unconditionally parses every stored blob with that layout, so any secret written before this commit (old format: 16-byte nonce + 32-byte HMAC + ciphertext) will fail authentication and become unreadable after upgrade. In environments with existingcredential_vaultrows,/vault/{name}will start returning decryption failures until each secret is manually re-entered; add legacy-format decryption or a migration path to avoid data loss on upgrade.Useful? React with 👍 / 👎.