Secure Your AWS API Gateway More Effectively By Blocking Access By IP Address

Secure Your AWS API Gateway More Effectively By Blocking Access By IP Address

·

2 min read

API Gateway is an Amazon service that makes it easy to develop APIs at scale. It handles the logic to process concurrent API requests, manages auth concerns, and handles API versioning. You can also use API Gateway to allow access to other AWS services that would normally be inaccessible.

A common use case is to execute an AWS lambda function via API Gateway.

While this pattern is powerful, it's also risky. If you're not careful you can expose your internal services to the wrong people. By default, your open API Gateway is freely accessible on the open internet.

This probably isn't what you want.

Instead, you should make sure you restrict access to your internal services. A common way to do this is through auth management. For example, if you're exposing a lambda function, you could validate a session token in your lambda before executing any logic.

But what if your lambda doesn't need session information?

Are the additional costs worth the security benefits?

Handling auth in your lambda means having to:

  • Explicitly maintain session logic

  • Force your API Gateway consumers to authenticate

  • Add overhead for code that's unrelated to your business logic

Restrict access at the API Gateway level with resource policies

Let's say you're working on an internal application at your company.

Your goal is to prevent anyone outside of your company from accessing your endpoints. To do this, you can whitelist traffic coming from your company network, which employees will likely access through something like a VPN.

API Gateway makes this easy to set up through resource policies.

A resource policy is a JSON document that defines a set of permissions. These documents control who has access to a resource, what actions can be performed on the resource, and when those actions can be performed. In this case, we can define a resource policy that whitelists a set of IP addresses for our API Gateway resource.

The resource policy might look something like this:

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": "*",
    "Action": "execute-api:Invoke",
    "Resource": "execute-api:/*/*/*",
    "Condition": {
      "IpAddress": {
        "aws:SourceIp": ["sourceIpOrCIDRBlock"]
      }
    }
  }]
}

The policy allows access to the API Gateway endpoints based on the condition. If a request is made from an IP Address that's not listed in the aws:SourceIp array, the request is blocked.

That's it!

Instead of writing explicit code to handle auth, you describe your level of access control through a resource policy. Your code is more focused on your business logic and your end users have a better experience when they try to use your APIs.

A simple resource policy can secure your API Gateway more effectively.