- Linux Administration Cookbook
- Adam K. Dean
- 453字
- 2021-07-02 14:24:37
There's more...
If you make changes with firewall-cmd or ufw, you can generally save the running config to the persistent config at the same time.
With iptables, we want to use iptables-save to modify our saved configuration, and ensure that it starts at boot:
$ sudo iptables-save
# Generated by iptables-save v1.4.21 on Sun Aug 19 15:04:14 2018
*filter
:INPUT DROP [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [3:236]
-A INPUT -i eth1 -p tcp -m tcp --dport 22 -j DROP
-A INPUT -s 10.0.2.0/24 -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
COMMIT
# Completed on Sun Aug 19 15:04:14 2018
This is all fine and dandy, except it's printed the configuration to standard out instead of saving it somewhere. Let's fix that by redirecting it to the default iptables config location:
$ sudo iptables-save | sudo tee /etc/sysconfig/iptables
Now, to properly start this at boot, we need the iptables-services package, which includes things such as the systemd unit files:
$ sudo yum install -y iptables-services
We can now enable iptables to start at boot:
$ sudo systemctl enable iptables
Run the systemctl restart command for iptables and ensure your configuration is correct:
$ sudo service iptables restart
Redirecting to /bin/systemctl restart iptables.service
$ sudo iptables -S
-P INPUT DROP
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -i eth1 -p tcp -m tcp --dport 22 -j DROP
-A INPUT -s 10.0.2.0/24 -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
There's also the iptables -F option, which we didn't cover in this section.
-F means flush, and it can be incredibly handy in certain situations for flushing your firewall back to its default configuration.
However, it's worth noting that if you have your default INPUT policy set to DROP incoming traffic, then flushing any rules that otherwise allow you access will render your session unusable.
My default policy is DROP:
$ sudo iptables -S
-P INPUT DROP
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -i eth1 -p tcp -m tcp --dport 22 -j DROP
-A INPUT -s 10.0.2.0/24 -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
If I now flush my rules, my session locks up:
$ sudo iptables -F
$
We would now need to get to the console of the box and reinstate the rules that allowed us access. Most of the time, this is simply a case of running the start command of the firewall.