Monday, October 27, 2014

Creating an IAM user policy to restrict user to add only ingress ports

The AWS CLI is not the most intuitive in terms of mandatory switches that it needs. To make matters worse, the IAM policy simulator is rudimentary in terms of functionally checking the policies. Recently, I had to enable a user to allow adding ingress rules to a particular security group in a vpc, the user policy looked like

*************
{
"Version": "2012-10-17",
  "Statement":[{
    "Effect":"Allow",
    "Action": [
       "ec2:AuthorizeSecurityGroupIngress",
       ],
     "Resource": "arn:aws:ec2:<region>:<aws_account>:security-group/<sg-group-name>",
        "Condition": {
        "StringEquals": {
          "ec2:Vpc": "arn:aws:ec2:<region>:<aws_account>:vpc/<vpc-id>"
        }
      }
    },
    {
      "Effect": "Allow",
      "Action": "ec2:DescribeSecurityGroups",
      "Resource": "*"
    }
  ]
}
*************

The above policy passed in the IAM policy simulator just fine. However, during runtime, using the below command

*************
$aws ec2 authorize-security-group-ingress --group-name <sg-group-name> --protocol tcp --port 80 --cidr <block ip> --profile <profile-name>

A client error (InvalidGroup.NotFound) occurred when calling the AuthorizeSecurityGroupIngress operation: The security group '<sg-group-name>' does not exist in default VPC '<default-vpc-id>'
*************

Since the user policy was created with resource arn pointing to <sg-group-name>, the above was assumed to work, but it does not. As per AWS doc, it is required to give security group id instead of name

So the above policy had to be modified to include security group id:

*************
....
"Resource": "arn:aws:ec2:<region>:<aws_account>:security-group/<sg-group-id>",
....
*************

Correspondingly, the aws cli command needs to pass security group id as well:

*************
$aws ec2 authorize-security-group-ingress --group-id <sg-group-id> --protocol tcp --port 80 --cidr <block ip> --profile <profile-name>
{
    "return": "true"
}
*************

Had to spend sometime troubleshooting this subtle difference in group id and group name, whereas policy simulator or aws cli can save folks some time if this difference is made obvious.

No comments:

Post a Comment