Protect hosts file
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).