|
| 1 | +"""Signer implementation for HashiCorp Vault (Transit secrets engine)""" |
| 2 | + |
| 3 | +from base64 import b64decode, b64encode |
| 4 | +from typing import Optional, Tuple |
| 5 | +from urllib import parse |
| 6 | + |
| 7 | +from securesystemslib.exceptions import UnsupportedLibraryError |
| 8 | +from securesystemslib.signer._key import Key, SSlibKey |
| 9 | +from securesystemslib.signer._signer import SecretsHandler, Signature, Signer |
| 10 | + |
| 11 | +VAULT_IMPORT_ERROR = None |
| 12 | +try: |
| 13 | + import hvac |
| 14 | + from cryptography.hazmat.primitives.asymmetric.ed25519 import ( |
| 15 | + Ed25519PublicKey, |
| 16 | + ) |
| 17 | + |
| 18 | +except ImportError: |
| 19 | + VAULT_IMPORT_ERROR = ( |
| 20 | + "Signing with HashiCorp Vault requires hvac and cryptography." |
| 21 | + ) |
| 22 | + |
| 23 | + |
| 24 | +class VaultSigner(Signer): |
| 25 | + """Signer for HashiCorp Vault Transit secrets engine |
| 26 | +
|
| 27 | + The signer uses "ambient" credentials to connect to vault, most notably |
| 28 | + the environment variables ``VAULT_ADDR`` and ``VAULT_TOKEN`` must be set: |
| 29 | + https://developer.hashicorp.com/vault/docs/commands#environment-variables |
| 30 | +
|
| 31 | + Priv key uri format is: ``hv:<KEY NAME>/<KEY VERSION>``. |
| 32 | +
|
| 33 | + Arguments: |
| 34 | + hv_key_name: Name of vault key used for signing. |
| 35 | + public_key: Related public key instance. |
| 36 | + hv_key_version: Version of vault key used for signing. |
| 37 | +
|
| 38 | + Raises: |
| 39 | + UnsupportedLibraryError: hvac or cryptography are not installed. |
| 40 | + """ |
| 41 | + |
| 42 | + SCHEME = "hv" |
| 43 | + |
| 44 | + def __init__(self, hv_key_name: str, public_key: Key, hv_key_version: int): |
| 45 | + if VAULT_IMPORT_ERROR: |
| 46 | + raise UnsupportedLibraryError(VAULT_IMPORT_ERROR) |
| 47 | + |
| 48 | + self.hv_key_name = hv_key_name |
| 49 | + self._public_key = public_key |
| 50 | + self.hv_key_version = hv_key_version |
| 51 | + |
| 52 | + # Client caches ambient settings in __init__. This means settings are |
| 53 | + # stable for subsequent calls to sign, also if the environment changes. |
| 54 | + self._client = hvac.Client() |
| 55 | + |
| 56 | + def sign(self, payload: bytes) -> Signature: |
| 57 | + """Signs payload with HashiCorp Vault Transit secrets engine. |
| 58 | +
|
| 59 | + Arguments: |
| 60 | + payload: bytes to be signed. |
| 61 | +
|
| 62 | + Raises: |
| 63 | + Various errors from hvac. |
| 64 | +
|
| 65 | + Returns: |
| 66 | + Signature. |
| 67 | + """ |
| 68 | + resp = self._client.secrets.transit.sign_data( |
| 69 | + self.hv_key_name, |
| 70 | + hash_input=b64encode(payload).decode(), |
| 71 | + key_version=self.hv_key_version, |
| 72 | + ) |
| 73 | + |
| 74 | + sig_b64 = resp["data"]["signature"].split(":")[2] |
| 75 | + sig = b64decode(sig_b64).hex() |
| 76 | + |
| 77 | + return Signature(self.public_key.keyid, sig) |
| 78 | + |
| 79 | + @property |
| 80 | + def public_key(self) -> Key: |
| 81 | + return self._public_key |
| 82 | + |
| 83 | + @classmethod |
| 84 | + def from_priv_key_uri( |
| 85 | + cls, |
| 86 | + priv_key_uri: str, |
| 87 | + public_key: Key, |
| 88 | + secrets_handler: Optional[SecretsHandler] = None, |
| 89 | + ) -> "VaultSigner": |
| 90 | + uri = parse.urlparse(priv_key_uri) |
| 91 | + |
| 92 | + if uri.scheme != cls.SCHEME: |
| 93 | + raise ValueError(f"VaultSigner does not support {priv_key_uri}") |
| 94 | + |
| 95 | + name, version = uri.path.split("/") |
| 96 | + |
| 97 | + return cls(name, public_key, int(version)) |
| 98 | + |
| 99 | + @classmethod |
| 100 | + def import_(cls, hv_key_name: str) -> Tuple[str, Key]: |
| 101 | + """Load key and signer details from HashiCorp Vault. |
| 102 | +
|
| 103 | + If multiple keys exist in the vault under the passed name, only the |
| 104 | + newest key is returned. Supported key type is: ed25519 |
| 105 | +
|
| 106 | + See class documentation for details about settings and uri format. |
| 107 | +
|
| 108 | + Arguments: |
| 109 | + hv_key_name: Name of vault key to import. |
| 110 | +
|
| 111 | + Raises: |
| 112 | + UnsupportedLibraryError: hvac or cryptography are not installed. |
| 113 | + Various errors from hvac. |
| 114 | +
|
| 115 | + Returns: |
| 116 | + Private key uri and public key. |
| 117 | +
|
| 118 | + """ |
| 119 | + if VAULT_IMPORT_ERROR: |
| 120 | + raise UnsupportedLibraryError(VAULT_IMPORT_ERROR) |
| 121 | + |
| 122 | + client = hvac.Client() |
| 123 | + resp = client.secrets.transit.read_key(hv_key_name) |
| 124 | + |
| 125 | + # Pick key with highest version number |
| 126 | + version, key_info = sorted(resp["data"]["keys"].items())[-1] |
| 127 | + |
| 128 | + crypto_key = Ed25519PublicKey.from_public_bytes( |
| 129 | + b64decode(key_info["public_key"]) |
| 130 | + ) |
| 131 | + |
| 132 | + key = SSlibKey.from_crypto(crypto_key) |
| 133 | + uri = f"{VaultSigner.SCHEME}:{hv_key_name}/{version}" |
| 134 | + |
| 135 | + return uri, key |
0 commit comments