You can also use
iptables to allow/restrict by udp/tcp ports on desired interfaces.
For example let's introduce a rule in the
filter table in the
OUTPUT chain to allow all traffic on tcp/udp port 143 (IMAP).
(sudo) iptables -A OUTPUT -o eth0 -p udp --destination-port 143 -j ACCEPT
(sudo) iptables -A OUTPUT -o eth0 -p tcp --destination-port 143 -j ACCEPT
(sudo) iptables -A OUTPUT -o eth0 -j DROP
I think IMAP goes over TCP but just in case I restrict also UDP protocol. For this matter I am assuming your interface to the internet as
eth0. And that your mail client uses IMAP protocol to connect a remote mail server. I just tried it myself and I only have access to the mail server. Remember that the order of the rules is important otherwise it won't do what you expect.
Edit#1: As you asked in the comment. To restore internet traffic just remove the rules you have just inserted. You can do that as follows:
(sudo) iptables -D OUTPUT -o eth0 -p udp --destination-port 143 -j ACCEPT
(sudo) iptables -D OUTPUT -o eth0 -p tcp --destination-port 143 -j ACCEPT
(sudo) iptables -D OUTPUT -o eth0 -j DROP
(sudo) iptables -nvL --line-numbers
Running the command above will show you in front of each rule a corresponding number which will help you remove the rules using that number instead of rewriting the whole rule. An output example would be as follows:
Chain OUTPUT (policy ACCEPT 73 packets, 8766 bytes)
num pkts bytes target prot opt in out source destination
1 0 0 ACCEPT udp -- * eth0 0.0.0.0/0 0.0.0.0/0 udp dpt:143
And then to remove the rule just run this command:
(sudo) iptables -D OUTPUT 1
The short way is also recommended if you haven't set up the rule and you don't really know how exactly was. Although you can reconstruct the rule from the output of
Note: This is the
non-persistent way of using
iptables which means that you won't maintain the rules if you reboot your system. If you want your rules to be
persistent the easiest way is to run the following:
(sudo) iptables-save > /etc/iptables/rules.v4
which saves/dumps your current rules to
/etc/iptables/rules.v4. Then after rebooting iptables would read the stored configuration from that files. For
IPv6 you use this other file
rules.v6. Have in mind that this holds for
Debian where you need to install an additional package. Please check this guide for detailed explanation. For Ubuntu I have found this other guide. For other systems you could browse the internet but the principle is the same:
You dump your current rules to file and set up a script at boot time to apply those saved rules to the current iptables configuration.