|
| 1 | +"""Reviewable local cryptographic primitive boundary and self-tests.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import hashlib |
| 6 | +import hmac |
| 7 | +import os |
| 8 | + |
| 9 | +from cryptography.hazmat.primitives.ciphers.aead import AESGCM |
| 10 | + |
| 11 | + |
| 12 | +class CryptoSelfTestError(RuntimeError): |
| 13 | + """Raised when a required local primitive check fails.""" |
| 14 | + |
| 15 | + |
| 16 | +_SELF_TEST_PASSED = False |
| 17 | + |
| 18 | + |
| 19 | +def ensure_crypto_self_tests(): |
| 20 | + global _SELF_TEST_PASSED |
| 21 | + if _SELF_TEST_PASSED: |
| 22 | + return True |
| 23 | + try: |
| 24 | + _check_aes_gcm() |
| 25 | + _check_hmac_sha256() |
| 26 | + _check_random_bytes() |
| 27 | + except Exception as exc: |
| 28 | + raise CryptoSelfTestError("cryptographic self-test failed") from exc |
| 29 | + _SELF_TEST_PASSED = True |
| 30 | + return True |
| 31 | + |
| 32 | + |
| 33 | +def random_bytes(length: int): |
| 34 | + if length <= 0: |
| 35 | + raise ValueError("length must be positive") |
| 36 | + return os.urandom(length) |
| 37 | + |
| 38 | + |
| 39 | +def _check_aes_gcm(): |
| 40 | + key = bytes.fromhex("00" * 31 + "01") |
| 41 | + nonce = bytes.fromhex("00" * 11 + "01") |
| 42 | + aad = b"phantasm-self-test" |
| 43 | + plaintext = b"local primitive check" |
| 44 | + aesgcm = AESGCM(key) |
| 45 | + ciphertext = aesgcm.encrypt(nonce, plaintext, aad) |
| 46 | + recovered = aesgcm.decrypt(nonce, ciphertext, aad) |
| 47 | + if recovered != plaintext: |
| 48 | + raise CryptoSelfTestError("aes-gcm check failed") |
| 49 | + |
| 50 | + |
| 51 | +def _check_hmac_sha256(): |
| 52 | + digest = hmac.new(b"phantasm", b"self-test", hashlib.sha256).hexdigest() |
| 53 | + expected = "e22f31e13630eceeca685522387389b16ed3ef5378b55eb4f37871fd72d29cf5" |
| 54 | + if not hmac.compare_digest(digest, expected): |
| 55 | + raise CryptoSelfTestError("hmac check failed") |
| 56 | + |
| 57 | + |
| 58 | +def _check_random_bytes(): |
| 59 | + first = random_bytes(32) |
| 60 | + second = random_bytes(32) |
| 61 | + if len(first) != 32 or len(second) != 32 or first == second: |
| 62 | + raise CryptoSelfTestError("random byte check failed") |
0 commit comments