# 18.4 ipfirewall（IPFW）

IPFirewall（IPFW，IP Firewall）是由 FreeBSD 项目维护的防火墙软件，也是 FreeBSD 中最早的包过滤软件。

IPFW 最初由 Daniel Boulet 于 1993 年为 BSDI（Berkeley Software Design, Inc.）编写，后由 Ugen J.S. Antsilevich 大幅修改并移植至 FreeBSD，当前的 ipfw2 版本则由 Luigi Rizzo 为 FreeBSD 重写。

IPFW 未包含在 GENERIC 内核中，但以可加载内核模块（ipfw\.ko）的形式提供，也可通过内核配置选项 `options IPFIREWALL` 编译进自定义内核。

作为 FreeBSD 原生防火墙，IPFW 采用基于规则编号的优先级机制。规则编号越小，优先级越高，可覆盖编号较大的规则。

> **警告**
>
> IPFW 默认包含一条规则，规则号为 `65535`，不可删除：该规则会阻断所有未匹配的流量。此默认行为可通过内核选项 `IPFIREWALL_DEFAULT_TO_ACCEPT` 或 sysctl `net.inet.ip.fw.default_to_accept` 改为允许。因此，在防火墙配置完成之前，请勿启动 IPFW，以免被阻断在防火墙之外。

## 服务项

配置 IPFW 服务需先启用系统防火墙，再执行启动与状态检查等操作，具体步骤如下。

* 启用系统防火墙设置：

```sh
# sysrc firewall_enable="YES"
```

> **技巧**
>
> 参见 FreeBSD 源代码中的 routing rc 脚本：<https://github.com/freebsd/freebsd-src/blob/main/libexec/rc/rc.d/routing#L387>。

可以使用以下命令设置 IPFW 防火墙在系统启动时自动启动：

```sh
# service ipfw enable # 重启后生效
```

设置防火墙开机自启有两种方法：`sysrc firewall_enable="YES"` 直接修改 rc.conf 配置，`service ipfw enable` 通过服务管理工具设置，两者均需重启后生效。

* 启动 IPFW 防火墙服务：

```sh
# service ipfw start

Firewall rules loaded.
Firewall logging enabled.
ifconfig: interface ipfw0 already exists
Firewall logging pseudo-interface (ipfw0) created.
```

* 查看 IPFW 防火墙的当前状态：

```sh
# service ipfw status

ipfw is enabled
```

## 文件结构

IPFW 防火墙的配置文件结构如下。

```sh
/
├── etc
│   └── ipfw.rules
├── usr
│   └── local
│       └── etc
│           └── ipfw.rules
└── boot
    └── loader.conf
```

## 参考文献

* FreeBSD Foundation. IPFW Overview\[EB/OL]. \[2026-04-17]. <https://freebsdfoundation.org/wp-content/uploads/2014/05/IPFW-An-Overview.pdf>. 概述 IPFW 防火墙的架构设计与规则匹配机制。
* FreeBSD Project. ipfw -- IP firewall and traffic shaper control program\[EB/OL]. \[2026-04-17]. <https://man.freebsd.org/cgi/man.cgi?query=ipfw&sektion=8>. IPFW 防火墙管理工具手册页，Daniel Boulet 为 BSDI 编写了原始版本，Luigi Rizzo 重写了 ipfw2。
* FreeBSD Project. rc.conf -- system configuration information\[EB/OL]. \[2026-04-17]. <https://man.freebsd.org/cgi/man.cgi?query=rc.conf&sektion=5>. 系统配置文件手册页。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://book.bsdcn.org/di-18-zhang-fang-huo-qiang/di-18.4-jie-ipfirewall-ipfw.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
