Whitelist source IP addresses in CentOS 7

  • I want to set up CentOS 7 firewall such that, all the incoming requests will be blocked except from the originating IP addresses that I whitelist. And for the Whitelist IP addresses all the ports should be accessible.

    I'm able to find few solutions (not sure whether they will work) for iptables but CentOS 7 uses firewalld. I can't find something similar to achieve with firewall-cmd command.

    The interfaces are in Public Zone. I have also moved all the services to Public zone already.

  • dougBTV

    dougBTV Correct answer

    6 years ago

    I'd accomplish this by adding sources to a zone. First checkout which sources there are for your zone:

    firewall-cmd --permanent --zone=public --list-sources
    

    If there are none, you can start to add them, this is your "whitelist"

    firewall-cmd --permanent --zone=public --add-source=192.168.100.0/24
    firewall-cmd --permanent --zone=public --add-source=192.168.222.123/32
    

    (That adds a whole /24 and a single IP, just so you have a reference for both a subnet and a single IP)

    Set the range of ports you'd like open:

    firewall-cmd --permanent --zone=public --add-port=1-22/tcp
    firewall-cmd --permanent --zone=public --add-port=1-22/udp
    

    This just does ports 1 through 22. You can widen this, if you'd like.

    Now, reload what you've done.

    firewall-cmd --reload
    

    And check your work:

     firewall-cmd --zone=public --list-all
    

    Side note / editorial: It doesn't matter but I like the "trusted" zone for a white-listed set of IPs in firewalld. You can make a further assessment by reading redhat's suggestions on choosing a zone.

    See also:


    If you'd like to DROP packets outside this source, here's an example for dropping those outside the /24 I used as an example earlier, you can use rich rules for this, I believe. This is conceptual, I have not tested it (further than seeing that centos 7 accepts the command), but, should be easy enough to do a pcap and see if it behaves how you'd expect

    firewall-cmd --zone=public --add-rich-rule='rule family="ipv4" source address="192.168.100.0/24" invert="True" drop'
    

    Thanks a lot for answering. Can't vote up due to shortage in reputation. But how do I drop all other IP's except the one that I added using sources?

    Thanks @KrishnanduSarkar -- you're right, by default it should be an ICMP reject. But, I think you can add a rich rule to drop the packets. I added an example to my answer that I think will work. Thanks regarding the upvote, I understand, if an answer works, consider accepting an answer.

    Great answer, I had been using iptables up until now.

    (!) This answer won't work as expected for current default FirewallD configuration (interfaces are assigned to public zone by default).

    Very nice answer, Thanks :)

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM