1
votes

I'm running an AWS EC2 instance with a public IP address (e.g. 1.2.3.4) and a service listening on 1.2.3.4:8080. In front of this EC2 there is a Network Load Balancer with a target group pointing to the instance.

Now I want to enforce that all connections to port 8080 go through that load balancer.

For that I have added a security group to my EC2 that only allows incoming traffic to port 8080 from the load balancer's private IP address. But because the load balancer also uses the target's security groups for granting client access I need to add 0.0.0.0/0 to it as well because otherwise nobody can access the load balancer from the Internet. And with that the direct access to 1.2.3.4:8080 is possible for everyone.

Is there anything I can do about that?

3

3 Answers

2
votes

You should not assign public ip for EC2 instances.
Just assign public ip for your network load balancer.
But, in this way, you could not ssh to EC2 instance directly.
And that time you will need other way to ssh to EC2 instance.

But, if you're not insist on network load balancer
you could use application load balancer to prevent user from accessing EC2 instance directly without removing public ip from EC2 instance.
And you could still ssh to EC2 instance directly.

2
votes

Now I want to enforce that all connections to port 8080 go through that load balancer.
allows incoming traffic to port 8080 from the load balancer's private IP address
And with that the direct access to 1.2.3.4:8080 is possible for everyone
Is there anything I can do about that?

If you are using port 8080, I'd assume you are exposing an HTTP endpoint. In that case it is advised to use ALB instead of NLB (only reason to use NLB with HTTP that comes to my mind is using SSL with client cert authentication)

Using ALB you may have 2 SG:

  1. A SG for LB open from internet
  2. A SG for EC2 open from the SG of the LB (instead of an IP address you can specify a SG)

I any case (using ALB or NLB) it is advised to place the EC2 instance behind a LB into a private subnet without public IP address - not routed to the internet gateway) If you need other access to the EC2 instance (ssh, ..) you may still create some temporary connection - e.g. using the Session Manager + NAT Gateway or a NAT instance.

Note: edit based on the comments

1
votes

The simple answer is: Do not assign a public IP address to the Amazon EC2 instance

If you wish to connect to the instance separately (eg SSH), some options are: