|
| 1 | +"""Signer implementation for AWS Key Management Service""" |
| 2 | + |
| 3 | +import logging |
| 4 | +from typing import Optional, Tuple |
| 5 | +from urllib import parse |
| 6 | + |
| 7 | +import securesystemslib.hash as sslib_hash |
| 8 | +from securesystemslib import exceptions |
| 9 | +from securesystemslib.exceptions import UnsupportedLibraryError |
| 10 | +from securesystemslib.signer._key import Key |
| 11 | +from securesystemslib.signer._signer import ( |
| 12 | + SecretsHandler, |
| 13 | + Signature, |
| 14 | + Signer, |
| 15 | + SSlibKey, |
| 16 | +) |
| 17 | + |
| 18 | +logger = logging.getLogger(__name__) |
| 19 | + |
| 20 | +AWS_IMPORT_ERROR = None |
| 21 | +try: |
| 22 | + import boto3 |
| 23 | + from botocore.exceptions import BotoCoreError, ClientError |
| 24 | + from cryptography.hazmat.primitives import serialization |
| 25 | +except ImportError: |
| 26 | + AWS_IMPORT_ERROR = "Signing with AWS KMS requires aws-kms and cryptography." |
| 27 | + |
| 28 | + |
| 29 | +class AWSSigner(Signer): |
| 30 | + """AWS Key Management Service Signer |
| 31 | +
|
| 32 | + This Signer uses AWS KMS to sign and supports signing with RSA/EC keys and |
| 33 | + uses "ambient" credentials typically environment variables such as |
| 34 | + AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN. These will |
| 35 | + be recognized by the boto3 SDK, which underlies the aws_kms Python module. |
| 36 | +
|
| 37 | + For more details on AWS authentication, refer to the AWS Command Line |
| 38 | + Interface User Guide: |
| 39 | + https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html |
| 40 | +
|
| 41 | + Some practical authentication options include: |
| 42 | + AWS CLI: https://aws.amazon.com/cli/ |
| 43 | + AWS SDKs: https://aws.amazon.com/tools/ |
| 44 | +
|
| 45 | + The specific permissions that AWS KMS signer needs are: |
| 46 | + kms:Sign for sign() |
| 47 | + kms:GetPublicKey for import() |
| 48 | +
|
| 49 | + Arguments: |
| 50 | + aws_key_id (str): AWS KMS key ID or alias. |
| 51 | + public_key (Key): The related public key instance. |
| 52 | +
|
| 53 | + Returns: |
| 54 | + AWSSigner: An instance of the AWSSigner class. |
| 55 | +
|
| 56 | + Raises: |
| 57 | + UnsupportedAlgorithmError: If the payload hash algorithm is unsupported. |
| 58 | + BotoCoreError: Errors from the botocore.exceptions library. |
| 59 | + ClientError: Errors related to AWS KMS client. |
| 60 | + UnsupportedLibraryError: If necessary libraries for AWS KMS are not available. |
| 61 | + """ |
| 62 | + |
| 63 | + SCHEME = "awskms" |
| 64 | + |
| 65 | + def __init__(self, aws_key_id: str, public_key: Key): |
| 66 | + if AWS_IMPORT_ERROR: |
| 67 | + raise UnsupportedLibraryError(AWS_IMPORT_ERROR) |
| 68 | + |
| 69 | + self.hash_algorithm = self._get_hash_algorithm(public_key) |
| 70 | + self.aws_key_id = aws_key_id |
| 71 | + self.public_key = public_key |
| 72 | + self.client = boto3.client("kms") |
| 73 | + self.aws_algo = self._get_aws_signing_algo(self.public_key.scheme) |
| 74 | + |
| 75 | + @classmethod |
| 76 | + def from_priv_key_uri( |
| 77 | + cls, |
| 78 | + priv_key_uri: str, |
| 79 | + public_key: Key, |
| 80 | + secrets_handler: Optional[SecretsHandler] = None, |
| 81 | + ) -> "AWSSigner": |
| 82 | + uri = parse.urlparse(priv_key_uri) |
| 83 | + |
| 84 | + if uri.scheme != cls.SCHEME: |
| 85 | + raise ValueError(f"AWSSigner does not support {priv_key_uri}") |
| 86 | + |
| 87 | + return cls(uri.path, public_key) |
| 88 | + |
| 89 | + @classmethod |
| 90 | + def import_(cls, aws_key_id: str, local_scheme: str) -> Tuple[str, Key]: |
| 91 | + """Loads a key and signer details from AWS KMS. |
| 92 | +
|
| 93 | + Returns the private key uri and the public key. This method should only |
| 94 | + be called once per key: the uri and Key should be stored for later use. |
| 95 | +
|
| 96 | + Arguments: |
| 97 | + aws_key_id (str): AWS KMS key ID. |
| 98 | + local_scheme (str): Local scheme to use. |
| 99 | +
|
| 100 | + Returns: |
| 101 | + Tuple[str, Key]: A tuple where the first element is a string |
| 102 | + representing the private key URI, and the second element is an |
| 103 | + instance of the public key. |
| 104 | +
|
| 105 | + Raises: |
| 106 | + UnsupportedAlgorithmError: If the AWS KMS signing algorithm is |
| 107 | + unsupported. |
| 108 | + BotoCoreError: Errors from the botocore.exceptions library. |
| 109 | + ClientError: Errors related to AWS KMS client. |
| 110 | + """ |
| 111 | + if AWS_IMPORT_ERROR: |
| 112 | + raise UnsupportedLibraryError(AWS_IMPORT_ERROR) |
| 113 | + |
| 114 | + client = boto3.client("kms") |
| 115 | + request = client.get_public_key(KeyId=aws_key_id) |
| 116 | + kms_pubkey = serialization.load_der_public_key(request["PublicKey"]) |
| 117 | + |
| 118 | + public_key_pem = kms_pubkey.public_bytes( |
| 119 | + encoding=serialization.Encoding.PEM, |
| 120 | + format=serialization.PublicFormat.SubjectPublicKeyInfo, |
| 121 | + ).decode("utf-8") |
| 122 | + try: |
| 123 | + keytype = cls._get_keytype_for_scheme(local_scheme) |
| 124 | + except KeyError as e: |
| 125 | + raise exceptions.UnsupportedAlgorithmError( |
| 126 | + f"{local_scheme} is not a supported signing algorithm" |
| 127 | + ) from e |
| 128 | + |
| 129 | + keyval = {"public": public_key_pem} |
| 130 | + keyid = cls._get_keyid(keytype, local_scheme, keyval) |
| 131 | + public_key = SSlibKey(keyid, keytype, local_scheme, keyval) |
| 132 | + return f"{cls.SCHEME}:{aws_key_id}", public_key |
| 133 | + |
| 134 | + @staticmethod |
| 135 | + def _get_keytype_for_scheme( |
| 136 | + scheme: str, |
| 137 | + ) -> str: |
| 138 | + """Returns the Secure Systems Library key type. |
| 139 | +
|
| 140 | + Arguments: |
| 141 | + (str): The Secure Systems Library scheme. |
| 142 | +
|
| 143 | + Returns: |
| 144 | + str: The Secure Systems Library key type. |
| 145 | + """ |
| 146 | + keytype_for_scheme = { |
| 147 | + "ecdsa-sha2-nistp256": "ecdsa", |
| 148 | + "ecdsa-sha2-nistp384": "ecdsa", |
| 149 | + "ecdsa-sha2-nistp512": "ecdsa", |
| 150 | + "rsassa-pss-sha256": "rsa", |
| 151 | + "rsassa-pss-sha384": "rsa", |
| 152 | + "rsassa-pss-sha512": "rsa", |
| 153 | + "rsa-pkcs1v15-sha256": "rsa", |
| 154 | + "rsa-pkcs1v15-sha384": "rsa", |
| 155 | + "rsa-pkcs1v15-sha512": "rsa", |
| 156 | + } |
| 157 | + return keytype_for_scheme[scheme] |
| 158 | + |
| 159 | + @staticmethod |
| 160 | + def _get_aws_signing_algo( |
| 161 | + scheme: str, |
| 162 | + ) -> str: |
| 163 | + """Returns AWS signing algorithm |
| 164 | +
|
| 165 | + Arguments: |
| 166 | + scheme (str): The Secure Systems Library signing scheme. |
| 167 | +
|
| 168 | + Returns: |
| 169 | + str: AWS signing scheme. |
| 170 | + """ |
| 171 | + aws_signing_algorithms = { |
| 172 | + "ecdsa-sha2-nistp256": "ECDSA_SHA_256", |
| 173 | + "ecdsa-sha2-nistp384": "ECDSA_SHA_384", |
| 174 | + "ecdsa-sha2-nistp512": "ECDSA_SHA_512", |
| 175 | + "rsassa-pss-sha256": "RSASSA_PSS_SHA_256", |
| 176 | + "rsassa-pss-sha384": "RSASSA_PSS_SHA_384", |
| 177 | + "rsassa-pss-sha512": "RSASSA_PSS_SHA_512", |
| 178 | + "rsa-pkcs1v15-sha256": "RSASSA_PKCS1_V1_5_SHA_256", |
| 179 | + "rsa-pkcs1v15-sha384": "RSASSA_PKCS1_V1_5_SHA_384", |
| 180 | + "rsa-pkcs1v15-sha512": "RSASSA_PKCS1_V1_5_SHA_512", |
| 181 | + } |
| 182 | + return aws_signing_algorithms[scheme] |
| 183 | + |
| 184 | + @staticmethod |
| 185 | + def _get_hash_algorithm(public_key: Key) -> str: |
| 186 | + """Helper function to return payload hash algorithm used for this key |
| 187 | +
|
| 188 | + Arguments: |
| 189 | + public_key (Key): Public key object |
| 190 | +
|
| 191 | + Returns: |
| 192 | + str: Hash algorithm |
| 193 | + """ |
| 194 | + if public_key.keytype == "rsa": |
| 195 | + # hash algorithm is encoded as last scheme portion |
| 196 | + algo = public_key.scheme.split("-")[-1] |
| 197 | + if public_key.keytype in [ |
| 198 | + "ecdsa", |
| 199 | + "ecdsa-sha2-nistp256", |
| 200 | + "ecdsa-sha2-nistp384", |
| 201 | + ]: |
| 202 | + # nistp256 uses sha-256, nistp384 uses sha-384 |
| 203 | + bits = public_key.scheme.split("-nistp")[-1] |
| 204 | + algo = f"sha{bits}" |
| 205 | + |
| 206 | + # trigger UnsupportedAlgorithm if appropriate |
| 207 | + _ = sslib_hash.digest(algo) |
| 208 | + return algo |
| 209 | + |
| 210 | + def sign(self, payload: bytes) -> Signature: |
| 211 | + """Sign the payload with the AWS KMS key |
| 212 | +
|
| 213 | + Arguments: |
| 214 | + payload: bytes to be signed. |
| 215 | +
|
| 216 | + Raises: |
| 217 | + BotoCoreError: Errors from the botocore.exceptions library. |
| 218 | + ClientError: Errors related to AWS KMS client. |
| 219 | +
|
| 220 | + Returns: |
| 221 | + Signature. |
| 222 | + """ |
| 223 | + try: |
| 224 | + request = self.client.sign( |
| 225 | + KeyId=self.aws_key_id, |
| 226 | + Message=payload, |
| 227 | + MessageType="RAW", |
| 228 | + SigningAlgorithm=self.aws_algo, |
| 229 | + ) |
| 230 | + |
| 231 | + hasher = sslib_hash.digest(self.hash_algorithm) |
| 232 | + hasher.update(payload) |
| 233 | + logger.debug("signing response %s", request) |
| 234 | + response = request["Signature"] |
| 235 | + logger.debug("signing response %s", response) |
| 236 | + |
| 237 | + return Signature(self.public_key.keyid, response.hex()) |
| 238 | + except (BotoCoreError, ClientError) as e: |
| 239 | + logger.error("Failed to sign with AWS KMS: %s", str(e)) |
| 240 | + raise e |
0 commit comments