Initially an important point in iptables the PREROUTING
rules that port redirects perform before the filter rules that define which ports can be accessed and by which IPs, as shown in the diagram below: / p>
SowhenanIPtriestoaccessthe3306
port,itwillfirstberedirectedtothe54235
port,andonlythenwillthefilteringrulesbeexecutedonwhichportsitcanaccess.ThismeansthatanyIPthathasaccesstothe54235
portwillalsobeabletoaccessthe3306
portevenifitdoesnothaveaccesstoitsinceassoonasitaccessesthe3306
portitwillalreadyberedirected,itcanaccess(butnowitisalreadyinthe54235
port).
Knowingthis,ifyouwanttocontinuethenconfigureiptablesasfollowstoallowaccessonlytoacertainiponport3306(thisrulewillnotbeusefulbecauseaspreviouslysaiditwillnotbeverifiedjustputtomakecleariptablesrules):
sudo iptables -A INPUT -p tcp -s IP_AQUI --dport 3306 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
sudo iptables -A OUTPUT -p tcp --sport 3306 -m conntrack --ctstate ESTABLISHED -j ACCEPT
The first rule you should repeat for the two allowed IPs, this will make only the ips defined in this rule can initiate a connection on this port, the second step is to redirect the ports, this is the command:
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 3306 -j REDIRECT --to-port 54235
Finally, do not allow other connections to the port 3306
(again this rule will not be executed)
iptables -A INPUT -p tcp --dport 3306 -j DROP
To accept all connections on port 54235
iptables -A INPUT -p tcp --dport 54235 -j ACCEPT
And to modify the default policy for DROP
iptables -P INPUT DROP