Search code examples
pythonamazon-web-servicesaws-sdkamazon-kms

MalformedPolicyDocumentException when creating AWS KMS Key


I am trying to create a key in KMS by using kms_client in Python 3.x-

import boto3

kms_client = boto3.client('kms')

policy = """
{
    "Sid": "Allowing access",
    "Effect": "Allow",
    "Principal": {"AWS": [
                "arn:aws:iam::123456:user/sample-user",
                "arn:aws:iam::123456:role/sample-role"
    ]},
    "Action": "kms:*",
    "Resource": "*"
}"""

# Creating client key
desc = "Key for testing"
response = kms_client.create_key(
    Description=desc,
    Policy=policy
)

But I face the MalformedPolicyDocumentException error when I run it.

I've already tried keeping the value of Principal as {"Fn::Join": ["", ["arn:aws:iam::", {"Ref": "AWS::123456"}, ":root"]]}, but it didn't work.

Also tried using the put_key_policy command after creating the key, but it gave the same error-

    # Creating client key
    desc = "Key for testing"
    response = kms_client.create_key(
        Description=desc
    )

    key_id = response['KeyMetadata']['KeyId']

    # Adding policy to the created key
    policy = """
    {
        "Version": "2019-5-31",
        "Statement": [{
            "Sid": "Allowing access",
            "Effect": "Allow",
            "Principal": {"AWS": [
                "arn:aws:iam::123456:user/sample-user",
                "arn:aws:iam::123456:role/sample-role"
            ]},
            "Action": "kms:*",
            "Resource": "*"
        }]
    }"""

    response = kms_client.put_key_policy(
        KeyId=key_id,
        Policy=policy,
        PolicyName='test'
    )

What is wrong here?


Solution

  • Found the solution - apparently, KMS key policy requires a specific version number. And the correct version would be 2012-10-17.

    import boto3
    
    kms_client = boto3.client('kms')
    
    policy = """
        {
            "Version": "2012-10-17",
            "Statement": [{
                "Sid": "Allowing Access",
                "Effect": "Allow",
                "Principal": {"AWS": [
                    "arn:aws:iam::123456:user/sample-user",
                    "arn:aws:iam::123456:role/sample-role"
                ]},
                "Action": "kms:*",
                "Resource": "*"
            }]
        }"""
    
    # Creating client key
    desc = "Key for testing"
    response = kms_client.create_key(
        Description=desc,
        Policy=policy
    )