80

I would like to open port 4567 for the IP address 1.2.3.4 with the firewall-cmd command on a CentOS 7.1 server.

How can I achieve this, as the documentation I could find was too specific on this?

Michaël Perrin
  • 903
  • 1
  • 7
  • 7
  • First install and start firewalld service `sudo yum install -y firewalld && sudo systemctl start firewalld`. Then open port 80 and 443 (and ssh 22 for remote shell if needed) (use _--permanent_ flag to keep changes after system reboot) `sudo firewall-cmd --zone=public --permanent --add-port=80/tcp && sudo firewall-cmd --zone=public --permanent --add-port=443/tcp && sudo firewall-cmd --zone=public --permanent --add-port=22/tcp`. Then reload firewalld service to activate new configuration `sudo systemctl reload firewalld`. – Takman Mar 15 '21 at 07:47

2 Answers2

101

Try this command

firewall-cmd --permanent --zone=public --add-rich-rule='
  rule family="ipv4"
  source address="1.2.3.4/32"
  port protocol="tcp" port="4567" accept'

Check the zone file later to inspect the XML configuration

cat /etc/firewalld/zones/public.xml

Reload the firewall

firewall-cmd --reload
Vasili Syrakis
  • 4,435
  • 3
  • 21
  • 29
  • 1
    That's exactly what I was looking for, thanks for your useful and simple answer! – Michaël Perrin Apr 22 '15 at 10:10
  • 1
    The change won't take place immediately unless you subsequently run `filewall-cmd reload` – Mike S May 11 '16 at 15:37
  • 3
    The correct way to reload is actually: `firewall-cmd --reload` – k00k May 19 '16 at 22:50
  • 1
    I think you should be using single quotes after --add-rich-rule='rule family="ipv4" source address="1.2.3.4/32" port protocol="tcp" port="4567" accept' – Basil A Jun 17 '16 at 19:40
  • Is there no way to accomplish the same with a service file so that public.xml can remain unedited (e.g. multiple service files rendered from templates)? – ColinM Oct 22 '16 at 21:20
  • incidentally this is pretty much the ONLY WAY TO ADD IPV6 rules also, work to the wise, for those ready to dive in. – Brian Thomas Feb 01 '17 at 05:10
  • 3
    While this solution will work, @michael-hampton's solution is the most firewalld-esque way to do this. In my opinion, rich rules should be used as a last resort when there are no better ways to do something. – totokaka Oct 10 '17 at 19:10
  • 5
    I completed the RHCSA much after this answer, and I agree. Avoiding rich rules would lead to a more maintainable configuration down the line. – Vasili Syrakis Oct 10 '17 at 20:13
87

Create a new zone to accommodate this configuration. FirewallD zones are defined by source addresses and by interfaces.

firewall-cmd --new-zone=special --permanent
firewall-cmd --reload
firewall-cmd --zone=special --add-source=192.0.2.4/32
firewall-cmd --zone=special --add-port=4567/tcp

Add --permanent of course to the latter two commands to make them permanent.

Michael Hampton
  • 237,123
  • 42
  • 477
  • 940