aws / amazon-ecs-init

ecs-init is now part of the amazon-ecs-agent repo https://github.com/aws/amazon-ecs-agent/tree/master/ecs-init
https://github.com/aws/amazon-ecs-agent
Apache License 2.0
200 stars 118 forks source link

check ipv4 routes for default network interface, only fall back to eth0 if none can be found #498

Closed yinyic closed 2 years ago

yinyic commented 2 years ago

Summary

Currently we default to eth0 when creating iptables rules for blocking offhost introspection endpoint access.

However, with the introduction of predictable network interface names, primary network interfaces may no longer have the name eth0. This has been observed on a few EC2 Nitro instances when launched with AL2022 AMI (systemd > v197) where the primary network interfaces were named such as ens3, ens5, etc.

Reference this page for more information on predictable network interface names. Quoting the summary -

Starting with v197 systemd/udev will automatically assign predictable, stable network interface names for all local Ethernet, WLAN and WWAN interfaces. This is a departure from the traditional interface naming scheme ("eth0", "eth1", "wlan0", ...), but should fix real problems.

This PR attempts to remedy this by identifying the default network interface name through route file. If none could be found, we fall back to eth0 to be backward-compatible (in the rare case that it might affect some customer with a special routing setup that's previously working).

Implementation details

/proc/net/route file stores IPv4 kernel routing table, where each row (except header) represent a route, e.g.

$ sudo cat /proc/net/route 
Iface   Destination Gateway     Flags   RefCnt  Use Metric  Mask        MTU Window  IRTT                                                       
ens5    00000000    01201FAC    0003    0   0   512 00000000    0   0   0                                                                             
ens5    00201FAC    00000000    0001    0   0   0   00F0FFFF    0   0   0                                                                               
ens5    01201FAC    00000000    0005    0   0   512 FFFFFFFF    0   0   0   

We will be looking for the interface that's mapped to the all-zero destination (the default route).

This is equivalent to using ip route command

$ ip route show to default
default via 172.31.32.1 dev ens5 proto dhcp src 172.31.32.21 metric 512

However introducing a new utility command seems a bit overkill if we are only using it once. More importantly, I found ip route sometimes not showing full routes in the case of IPv6 (ip route -6) which can potentially cause gaps if we are to add IPv6 support.

Testing

New tests cover the changes: new unit tests

Description for the changelog

[Enhancement] check ipv4 routes for default network interface instead of defaulting to eth0

Licensing

This contribution is under the terms of the Apache 2.0 License: