AWS security groups work as whitelists: each line is a permissive rule. Anything that is not allowed, is denied, yet what is allowed, is allowed, you can't override that in any other rule.
Roughly, security groups can allow specific inbound traffic from:
- a given IP address or IP address range;
- all instances that are assigned a given security group.
Unfortunately, you can not specify anything more complex, like "allow access from any instance that does not have a public IP" - you can only specify a source security group. As you correctly assumed, security groups listed in Source
field can be regarded as labels.
So, in your case, configuration should be as follows:
- EC2 instances with Web applicationsh should have sg-public-group;
- EC2 instance with DB should have sg-db-group and sg-private-group;
- EC2 instances that require access via SSH from internal subnet only should have sg-access-group (yet you still need to think how to access those instances you are planning to access from).
sg-access-from should be set up to allow connections via 22/TCP from EC2 instances that belong to sg-private-group. However, it is going to be your responsibility to make sure that all EC2 instances belonging to sg-private-group indeed do not have any public IP addresses.
For more detail look at AWS Security Groups document:
For each rule, you specify the following:
- Protocol: The protocol to allow. The most common protocols are 6 (TCP) 17 (UDP), and 1 (ICMP).
- Port range : For TCP, UDP, or a custom protocol, the range of ports to allow.
- ICMP type and code: For ICMP, the ICMP type and code. Source or destination: The source (inbound rules) or destination (outbound
rules) for the traffic. Specify one of these options:
- An individual IPv4 address. You must use the /32 prefix after the IPv4 address; for example, 203.0.113.1/32.
- (VPC only) An individual IPv6 address. You must use the /128 prefix length; for example 2001:db8:1234:1a00::123/128.
- A range of IPv4 addresses, in CIDR block notation, for example, 203.0.113.0/24.
- (VPC only) A range of IPv6 addresses, in CIDR block notation, for example, 2001:db8:1234:1a00::/64.
- Another security group. This allows instances associated with the specified security group to access instances associated with this
security group. This does not add rules from the source security group
to this security group. You can specify one of the following security
groups:
- The current security group.
- EC2-Classic: A different security group for EC2-Classic in the same region.
- EC2-Classic: A security group for another AWS account in the same region (add the AWS account ID as a prefix; for example,
111122223333/sg-edcd9784).
- EC2-VPC: A different security group for the same VPC or a peer VPC in a VPC peering connection.