Protect hosts file

command linehostsSecurityterminal

I am under the impression that there is no real way to protect the hosts file completely without creating a none-admin user account on my Mac and setting the password of the admin account to one that I won't remember.

So therefore I would like to make editing of my hosts file difficult as a next-best alternative.

I have read that it is possible to set a system immutable flag on specific files which would need to be disabled before the files are able to be edited.

So of course it would still be possible to edit the hosts file, but it would at least make it a bit trickier.

Is this a recommended approach? or is there a better way to achieve it?

Best Answer

Protecting with ‘schg’, the system immutable flag, is a potential solution, depending on how much protection you need. You can set the schg flag using

sudo chflags schg /etc/hosts

Removal of the protection depends on your kernel security level. Run sysctl kern.securelevel:

  • 1 means you need to boot to single-user mode to run chflags noschg /etc/hosts,
  • 0 means you can simply sudo chflags noschg /etc/hosts.

Instead of schg, you can use System Integrity Protection's restricted flag in El Capitan and later. You can boot to the Recovery HD to set the flag using chflags restricted /etc/hosts.

This protects the file from modification whilst SIP is enabled, which is enabled by default and can only be disabled by booting to the Recovery HD and running csrutil disable.

Check the status of SIP by running csrutil status: if it is enabled, any files with the restricted flag cannot be modified without disabling SIP from Recovery first or by installers signed with Apple's Software Update certificate (even root cannot modify the file).