IPTables: Allow outgoing MySQL connections but not incoming connections
Take advantage of the state engine:
iptables -t filter -A OUTPUT -p tcp --dport 3306 -j ACCEPT
iptables -t filter -A INPUT -p tcp --sport 3306 -m state --state ESTABLISHED -j ACCEPT
or in later versions of iptables
iptables -t filter -A OUTPUT -p tcp --dport 3306 -j ACCEPT
iptables -t filter -A INPUT -p tcp --sport 3306 -m conntrack --ctstate ESTABLISHED -j ACCEPT
This is exactly what the state engine exists to do: allow traffic which meets various criteria (eg, protocol, source port) but is also part of an existing connection (as it defines connection). The upshot is that the outgoing TCP SYN
packet to a particular external IP address on destination port 3306, from a local ephmeral port, will create a state table entry for that particular combination of IP addresses and port numbers, and only return traffic with the same combination of addresses and ports will be permitted through, and only for the duration of that connection.