/etc/hosts entries not being used for non-root users

Issue

Non-root users are unable to resolve addresses for entries in /etc/hosts.

user@gentoo ~ $ ping localhost
ping: unknown host localhost

Troubleshooting

Potential causes

  • Malformed content or improper permissions on /etc/hosts
  • Malformed content or improper permissions on /etc/host.conf
  • Malformed content or improper permissions on /etc/nsswitch.conf

Diagnostics

One may consider nslookup or dig to be suitable diagnostic tools given the use case, however, they are applicable only when troubleshooting DNS server name resolution issues; these tools do not bother to look at /etc/hosts. strace is suitable given the diagnostic task at hand.

user@gentoo ~ $ strace -e open ping localhost
open("/etc/ld.so.cache", O_RDONLY)      = 3
open("/lib/libc.so.6", O_RDONLY)        = 3
open("/etc/resolv.conf", O_RDONLY)      = 3
open("/etc/resolv.conf", O_RDONLY)      = 3
open("/etc/nsswitch.conf", O_RDONLY)    = -1 EACCES (Permission denied)
open("/etc/ld.so.cache", O_RDONLY)      = 3
open("/lib/libnss_dns.so.2", O_RDONLY)  = 3
open("/lib/libresolv.so.2", O_RDONLY)   = 3
open("/etc/host.conf", O_RDONLY)        = 3
ping: unknown host localhost

Cause

As reported by our strace diagnostic, our user has insufficient privileges to read /etc/nsswitch.conf resulting in the file never being utilized for name resolution. In our case, /etc/nsswitch.conf had a permission mode of 600, allowing only the owner (root in our case) read/write access.

Steps to Reproduce

Change the mode of /etc/resolv.conf, /etc/host.conf, /etc/hosts to 600.

Resolution

Change the mode of /etc/nsswitch.conf to 644.

user@gentoo ~ $ sudo chomod 644 /etc/nsswitch.conf
user@gentoo ~ $ strace -e open ping localhost
open("/etc/ld.so.cache", O_RDONLY)      = 3
open("/lib/libc.so.6", O_RDONLY)        = 3
open("/etc/resolv.conf", O_RDONLY)      = 3
open("/etc/resolv.conf", O_RDONLY)      = 3
open("/etc/nsswitch.conf", O_RDONLY)    = 3
open("/etc/ld.so.cache", O_RDONLY)      = 3
open("/lib/libnss_files.so.2", O_RDONLY) = 3
open("/etc/host.conf", O_RDONLY)        = 3
open("/etc/hosts", O_RDONLY|O_CLOEXEC)  = 3
ping: icmp open socket: Operation not permitted

user@gentoo ~ $ ping -c 2 localhost
PING localhost (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost (127.0.0.1): icmp_req=1 ttl=64 time=0.066 ms
64 bytes from localhost (127.0.0.1): icmp_req=2 ttl=64 time=0.056 ms
--- localhost ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 999ms
rtt min/avg/max/mdev = 0.056/0.061/0.066/0.005 ms

Note: We expect "ping: icmp open socket: Operation not permitted" – non-root users are not allowed to open raw sockets.