在 Fedora 命令行下玩转防火墙
防火墙
![](/data/attachment/album/202004/12/123040ghxuicphyhsoppch.jpg)


网络防火墙，顾名思义：为了阻止不需要的网络连接而设置的防护性屏障。在与外界建立连接或是提供网络服务时常常会用到。例如，在学校或是咖啡厅里使用笔记本电脑时，你一定不想某个陌生人窥探你的电脑。


每个 Fedora 系统都内置了一款防火墙。这是 Linux 内核网络功能的一部分。本文介绍如何通过 `firewall-cmd` 命令修改防火墙的配置。


### 网络基础


本文并不教授计算机网络的[所有知识](https://en.wikipedia.org/wiki/Portal:Internet)，但还是会简单介绍一些网络基础。


网络中的所有计算机都有一个 *IP 地址*，可以把它想象成一个邮箱地址，有了邮箱地址，邮件才知道发往何处。每台计算机还会拥有一组*端口*，端口号范围从 0 到 65535。同样的，你可以把这些端口想象成用来连接邮箱地址的连接点。


通常情况下，端口会是一个标准端口号或是根据应用程序的应答要求选定的一个端口范围。例如，一台 Web 服务器通常会保留 80 端口用于 HTTP 通信，443 端口用于 HTTPS。小于 1024 的端口主要用于系统或常见用途，1024-49151 端口是已经注册的，49152 及以上端口多为临时使用（只限短时间使用）。


互联网传输中最常见的两个协议，[TCP](https://en.wikipedia.org/wiki/Transmission_Control_Protocol) 和 [UDP](https://en.wikipedia.org/wiki/User_Datagram_Protocol)。当要传输的数据很重要，不能有丢包时，就使用 TCP 协议，如果数据包没有按顺序到达，还需要重组为正确的顺序。UDP 协议则更多用于对时间敏感的服务，为了保证时效性，有时允许丢失部分数据。


系统中运行的应用，例如 Web 服务器，会保留一些端口（例如上文提到的 80 和 443）。在网络传输过程中，主机会为传输的两端建立一个链接，一端是源地址和源端口，另一端是目的地址和目的端口。


网络防火墙就是基于地址、端口及其他标准的一组规则集，来对网络数据的传输进行屏蔽或阻断的。通过 `firewall-cmd` 命令，我们就可以查看或修改防火墙的工作配置。


### 防火墙域（zone）


为了验证防火墙是否开启，使用 `firewall-cmd` 命令，输入时要加上 [sudo](https://fedoramagazine.org/howto-use-sudo/)。（通常，在运行了 [PolicyKit](https://en.wikipedia.org/wiki/Polkit) 的环境中，你也可以不加 `sudo`）



```
$ sudo firewall-cmd --state
running
```

firewalld 服务支持任意数量的域。每个域都可以拥有独立的配置和防护规则。一台 Fedora 工作站的外部接口（例如 WIFI 或有线网卡）其默认域为 `FedoraWorkstation`。


要看有哪些域是激活状态，可以使用 `-–get-active-zones` 选项。在本示例中，有两个网卡，有线以太网卡 `wlp2s0` 和虚拟（libvirt）桥接网卡 `virbr0`：



```
$ sudo firewall-cmd --get-active-zones
FedoraWorkstation
  interfaces: wlp2s0
libvirt
  interfaces: virbr0
```

如果想看看默认域是什么，或是直接查询所有域：



```
$ sudo firewall-cmd --get-default-zone
FedoraWorkstation
$ sudo firewall-cmd --get-zones
FedoraServer FedoraWorkstation block dmz drop external home internal libvirt public trusted work
```

查询默认域中防火墙放行了哪些系统，使用 `-–list-services` 选项。下例给出了一个定制系统的查询结果，你可以看到与常见的结果有些不同。



```
$ sudo firewall-cmd --list-services
dhcpv6-client mdns samba-client ssh
```

该系统对外开启了四个服务。每个服务都对应一个常见端口。例如 `ssh` 服务对应 22 端口。


如果要查看当前域中防火墙还开启了哪些端口，可以使用 `--list-ports` 选项。当然，你也可以随时对其他域进行查询：



```
$ sudo firewall-cmd --list-ports --zone=FedoraWorkstation
1025-65535/udp 1025-65535/tcp
```

结果表明，从 1025 到 65535 端口（包含 UDP 和 TCP）默认都是开启的。


### 修改域、端口及服务


以上的配置都是预先设计好的防火墙策略。是为了确保新手用户安装的应用都能够正常访问网络。如果你确定自己心里有数，想要一个保护性更强的策略，可以将接口放入 `FedoraServer` 域，明确禁止所有端口的访问。（**警告**：如果你的服务器之前是联网状态，这么做可能会导致连接中断，那你就得到机房里去修改更多的配置项！）



```
$ sudo firewall-cmd --change-interface=<ifname> --zone=FedoraServer
success
```

**本文并不讨论如何制定防火墙策略，Fedora 社区里已经有很多讨论了。你大可以按照自身需要来修改配置。**


如果你想要开放某个服务的常见端口，可以将该服务加入默认域（或使用 `--zone` 指定一个不同的域）。还可以一次性将其加入多个域。下例开放了 HTTP 和 HTTPS 的常见端口 80、443：



```
$ sudo firewall-cmd --add-service=http --add-service=https
success
```

并非所有的服务都有默认端口，不过大部分都是有的。使用 `-–get-services` 选项可以查看完整列表。


如果你想指定某个特定端口号，可以直接用数字和协议进行配置。（多数情况下，`-–add-service` 和 `-–add-port` 这两个选项是合在一起使用的）下例开启的是 UDP 协议的网络启动服务：



```
$ sudo firewall-cmd --add-port=67/udp
success
```

**重要**：如果想要在系统重启或是 firewalld 服务重启后，配置仍然生效，**必须**在命令中加上 `-–permanent` 选项。本文中的例子只是临时修改了配置，下次遇到系统重启或是 firewalld 服务重启，这些配置就失效了。


以上只是 `firewall-cmd` 和 firewalld 服务诸多功能中的一小部分。firewalld 项目的[主页](https://firewalld.org/)还有更多信息值得你去探索和尝试。




---


via: <https://fedoramagazine.org/control-the-firewall-at-the-command-line/>


作者：[Paul W. Frields](https://fedoramagazine.org/author/pfrields/) 选题：[lujun9972](https://github.com/lujun9972) 译者：[tinyeyeser](https://github.com/tinyeyeser) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
A network *firewall* is more or less what it sounds like: a protective barrier that prevents unwanted network transmissions. They are most frequently used to prevent outsiders from contacting or using network services on a system. For instance, if you’re running a laptop at school or in a coffee shop, you probably don’t want strangers poking around on it.

Every Fedora system has a firewall built in. It’s part of the network functions in the Linux kernel inside. This article shows you how to change its settings using *firewall-cmd*.

## Network basics

This article can’t teach you [everything](https://en.wikipedia.org/wiki/Portal:Internet) about computer networks. But a few basics suffice to get you started.

Any computer on a network has an *IP address*. Think of this just like a mailing address that allows correct routing of data. Each computer also has a set of *ports*, numbered 0-65535. These are not physical ports; instead, you can think of them as a set of connection points at the address.

In many cases, the port is a [standard number](https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers) or range depending on the application expected to answer. For instance, a web server typically reserves port 80 for non-secure HTTP communications, and/or 443 for secure HTTPS. The port numbers under 1024 are reserved for system and well-known purposes, ports 1024-49151 are registered, and ports 49152 and above are usually ephemeral (used only for a short time).

Each of the two most common protocols for Internet data transfer, [TCP](https://en.wikipedia.org/wiki/Transmission_Control_Protocol) and [UDP](https://en.wikipedia.org/wiki/User_Datagram_Protocol), have this set of ports. TCP is used when it’s important that all data be received and, if it arrives out of order, reassembled in the right order. UDP is used for more time-sensitive services that can withstand losing some data.

An application running on the system, such as a web server, reserves one or more ports (as seen above, 80 and 443 for example). Then during network communication, a host establishes a connection between a source address and port, and the destination address and port.

A network firewall can block or permit transmissions of network data based on rules like address, port, or other criteria. The *firewall-cmd* utility lets you interact with the rule set to view or change how the firewall works.

## Firewall zones

To verify the firewall is running, use this command with [sudo](https://fedoramagazine.org/howto-use-sudo/). (In fairness, you can run *firewall-cmd* without the *sudo* command in environments where [PolicyKit](https://en.wikipedia.org/wiki/Polkit) is running.)

$sudo firewall-cmd --state

running

The firewalld service supports any number of *zones*. Each zone can have its own settings and rules for protection. In addition, each network interface can be placed in any zone individually The default zone for an external facing interface (like the wifi or wired network card) on a Fedora Workstation is the *FedoraWorkstation* zone.

To see what zones are active, use the *––get-active-zones* flag. On this system, there are two network interfaces, a wired Ethernet card *wlp2s0* and a virtualization (libvirt) bridge interface *virbr0*:

$sudo firewall-cmd --get-active-zonesFedoraWorkstation interfaces: wlp2s0 libvirt interfaces: virbr0

To see the default zone, or all the defined zones:

$sudo firewall-cmd --get-default-zoneFedoraWorkstation $sudo firewall-cmd --get-zonesFedoraServer FedoraWorkstation block dmz drop external home internal libvirt public trusted work

To see the services the firewall is allowing other systems to access in the default zone, use the *––list-services* flag. Here is an example from a customized system; you may see something different.

$sudo firewall-cmd --list-servicesdhcpv6-client mdns samba-client ssh

This system has four services exposed. Each of these has a well-known port number. The firewall recognizes them by name. For instance, the *ssh* service is associated with port 22.

To see other port settings for the firewall in the current zone, use the *––list-ports* flag. By the way, you can always declare the zone you want to check:

$sudo firewall-cmd --list-ports --zone=FedoraWorkstation1025-65535/udp 1025-65535/tcp

This shows that ports 1025 and above (both UDP and TCP) are open by default.

## Changing zones, ports, and services

The above setting is a design decision.* It ensures novice users can use network facing applications they install. If you know what you’re doing and want a more protective default, you can move the interface to the *FedoraServer* zone, which prohibits any ports not explicitly allowed. *( Warning: if you’re using the host via the network, you may break your connection — meaning you’ll have to go to that box physically to make further changes!)*

$sudo firewall-cmd --change-interface=success<ifname>--zone=FedoraServer

* *This article is not the place to discuss that decision, which went through many rounds of review and debate in the Fedora community. You are welcome to change settings as needed.*

If you want to open a well-known port that belongs to a service, you can add that service to the default zone (or use *––zone* to adjust a different zone). You can add more than one at once. This example opens up the well-known ports for your web server for both HTTP and HTTPS traffic, on ports 80 and 443:

$sudo firewall-cmd --add-service=http --add-service=httpssuccess

Not all services are defined, but many are. To see the whole list, use the *––get-services* flag.

If you want to add specific ports, you can do that by number and protocol as well. (You can also combine *––add-service* and *––add-port* flags, as many as necessary.) This example opens up the UDP service for a network boot service:

$sudo firewall-cmd --add-port=67/udpsuccess

**Important:** If you want your changes to be effective after you reboot your system or restart the firewalld service, you **must** add the *––permanent* flag to your commands. The examples here only change the firewall until one of those events next happens.

These are just some of the many functions of the *firewall-cmd* utility and the firewalld service. There is much more information on firewalld at the project’s [home page](https://firewalld.org/) that’s worth reading and trying out.

*Photo by Jakob Braun on Unsplash.*

## Joao Rodrigues

Or setup your firewall as you like, and in the end use:

$ sudo firewall-cmd –runtime-to-permanent

To make your configuration permanent.

## Paul W. Frields

@Joao: Yes, this is a great tip!

## kb

Best firewald zone for desktop or home laptop ?

## Joao Rodrigues

Zones are not for desktop or laptops.

Zones are for networks. Home networks, Work networks, public networks.

When I connect to my home network, I trust every computer that connects to that network and I expose some services (like samba shares).

In a public network I don’t trust any of the computers, so I don’t want to expose any service.

The cool thing is that you can bind firewalld zones to wifi connections (you have to use nm-connection-editor or nmcli, though), so when I connect to my home wifi I always land on the home zone and if I go to a public library or cafe I usually set it to public, block or drop.

## Paul W. Frields

You’re correct, and I don’t believe the article states zones are for types of systems. It says instead they allow grouping rules. The names of the packaged zones (such as dmv, public, home, etc.) do hint they can be used to assert a level a trust on a specific network type.

## Nils

Thanks for the tutorial!

I think the next interesting step would be to add own services. This is actually quite easy and described here: https://firewalld.org/documentation/howto/add-a-service.html

## Ondrej

What I miss written about firewalld is writting complete router setup. Like masquerading, different zones, etc.

I would be really grateful for complete tutorial like that. 🙂

I am really enjoying using firewall-cmd in oposite to iptables syntax, which I usually have to look up all the time.

## Jordan

Nice! I want more post about this.

## atolstoy

I suspect that Paul got inspired with this after the recent article on Firewalld and OpenSnitch in the Linux Pro magazine.

## Paul W. Frields

Nope, it was actually just an idea someone put in our idea queue for the Magazine some weeks ago, and since no one else wrote it, I decided to. 🙂

## Earl Ramirez

Can you share a bit of detail on the “Idea queue” is this something available for the public?

## Paul W. Frields

Earl: Sure, refer to https://docs.fedoraproject.org/en-US/fedora-magazine/ for the big picture and instructions.

## Earl Ramirez

Thank you, sir

## Frank Dorr

Paul Thanks for making this! I think i need your help! I was recently hi-jhacked by some clown and am currently on what appears to be a contaminated node on THEIR network. I’m so new to linux that I probably installed all of this stuff for them. Where can a nub like me go to clean out my computer, reset my 1 tarabyte hd (it says i have 3 partitions with 999gigs free on 1 I cant access) Where can a noob go to setup his firewall at like AEGIS levels, DETOX the damn drives and be assured his Fedora installation is CLEAN???? Thanking you again, in advance, I am 🙂

## atolstoy

Thanks Paul, you’re great!

## Mark

You do have to keep an eye on what ports are opened when adding services, while a service like http, ssh or cockpit adds 80, 22, 9090 repectively but if you were to add (found from playing around after a previous article on GSConnect) “firewall-cmd –add-service kde-connect” (service provided by the kdeconnectd package) you will see that (on F30 anyway) it opens a huge port range of 1714 to 1764 on both tcp and udp.

Which after a few reboots to check I found the kde-connect process consistently only ever used one port so removed the service and just added the one tcp and udp port.

It does highlight that you need to be aware of what ports a service opens rather than assuming the service knows best, whether by examining the service file at /usr/lib/firewalld/services/yourservicename.xml (where you can also create your own services) or as I do in my active environments by a server checking script that as one of its functions checks that every port defined in the active firewall rules actually matches a port in a listening state on the server which helps me keep the rules up to date when I remove packages.

On the mention in the post for the output of the command “sudo firewall-cmd –list-ports –zone=FedoraWorkstation” allowing ports 1025 and above thanks for mentioning that, most users of a new Fedora desktop install probably don’t realise they are wide open by default and must really trust everything in their network so it is good you mentioned it. The first thing any desktop user should do is change the default/active zone or delete that port range and just define what they need.

## Frank Dorr

So….if I catch a virus, I think its this new Minergate trojan/worm, whatever they did MS released CVE-ID-2020 (hehe THE CVE-ID-19 VIRUS!), to fix that gets in on the printer ports and then acts like WANNACRY, on a network with 2 windows computers, it infects both, i install fedora, it comes in such a state that the virus may be able to mess my brand new fedora up from the windows connection? how do i check/stop it? what can i do, i can see where its adding firewall exceptions in the anaconda files in the jump drive :(.

## nehemiah

typo near the end or your two dashes were turned into an em dash: it say’s add ‘-permanent’ to your commands for the setting to survive reboot, it’s two dashes. could you put that in the code example or in a monospaced font ?

## Paul W. Frields

Thanks for catching, this is a “feature” of the hosting software. Fixed.