0

I am validation KMS ARN value by String and pattern match in Regular Expression.

Sample Input: arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab

Rules:

  • Start with “arn:aws:kms:” string value.
  • Followed by Region Name.
  • c. Followed by colon “:”
  • d. Followed by numeric value.
  • Followed by colon “:”
  • Followed by “key” string value.
  • Followed by Alphabets and/or numbers and/or underscore string value. Which is again validate against UUD.

Code to get AWS Regions:

>>> import boto3
>>> session_obj = boto3.session.Session()
>>> session_obj.get_available_regions('lambda')

Code for KMS Validation:

def validate_aws_kms_arns(kms_arns_str):
    """
        Validate KMS ARNS
        Format: arn:aws:kms:$RegionCode$:$AccountNumber$:key/$UUID$
        $RegionCode$ : list of region Ids
        $AccountNumber$ : Interger account number.
        $UUID$: uuid
    """
    # Get Region Value list from AWS.
    lambda_region_list = ['ap-northeast-1', 'ap-northeast-2', 'ap-south-1', 'ap-southeast-1', 'ap-southeast-2', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'sa-east-1', 'us-east-1', 'us-east-2', 'us-west-1', 'us-west-2']

    pattern = re.compile("\Aarn:aws:kms:({}):\d+:key/([\w-]+)\Z".format(
            '|'.join(lambda_region_list))
    )
    match_obj = pattern.match(kms_arns_str)
    if bool(pattern.match(kms_arns_str)):
        uuid_value = match_obj.groups()[1]
    else:
        print("Invalid KMS ARNS value: {}".format(kms_arns_str))
        return False

    # UUID Validation.
    # ...

    return True

but I saw https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces this.

We need to validate KMS ARNS value for partition and service also? And above code is correct to validate KMS value?

Vivek Sable
  • 9,938
  • 3
  • 40
  • 56
  • 2
    Why are you doing this? – kdgregory Jan 30 '18 at 11:41
  • :) its work-flow of my code. I am passing this value in code, I do not want to see any exception raise due to invalid KMS value. – Vivek Sable Jan 30 '18 at 18:17
  • That seems like a significant waste of time. All you are really testing is whether the key ARN is blatantly malformed, not whether it is actually valid or whether it is enabled, what its purpose is, or whether you have the right to use it. The KMS API has a [`DescribeKey`](https://docs.aws.amazon.com/kms/latest/APIReference/API_DescribeKey.html) action that will tell you most of what you want to know about a key ARN. – Michael - sqlbot Jan 31 '18 at 00:20

0 Answers0