dnsmasq (简体中文) - ArchWiki

Jump to content

Related articles

- Domain name resolution

dnsmasq 提供 DNS 服务器、支持 DHCPv6 和 PXE 的 DHCP 服务器、TFTP 服务器。它设计为轻量且占用空间小，适用于资源受限的路由器和防火墙。还可以将 dnsmasq 配置为 DNS 缓存查询，以提高对以前访问过站点的 DNS 查找速度。

## 安装

安装 dnsmasq 软件包。

## 启动守护程序

启动/启用 `dnsmasq.service`。

要查看 dnsmasq 是否正确启动，可以检查系统的 journal：

    # journalctl -u dnsmasq.service

还需要重新启动网络，以便 DHCP 客户端可以创建新的 `/etc/resolv.conf`。

## 配置

要配置 dnsmasq，需要编辑 `/etc/dnsmasq.conf`。该文件包含选项的注释。有关全部可用选项，请参阅 dnsmasq(8)。

注意： dnsmasq 的默认配置启用 DNS 服务器。如果不使用的话，需要显式设置 `port=0` 来禁用它。

如果 dnsmasq 不用作本地 DNS 解析程序，还需要 编辑 `dnsmasq.service`，使其不唤起 `nss-lookup.target`：

    /etc/systemd/system/dnsmasq.service.d/no-nss-lookup-target.conf

    [Unit]
    Wants=

提示： 要检查配置文件语法，请执行：

    $ dnsmasq --test

### DNS 服务器

要在单台计算机上将 dnsmasq 设置为 DNS 缓存守护程序，请指定 `listen-address` 指令，添加本地主机 IP 地址：

    listen-address=::1,127.0.0.1

使用此计算机在其 LAN IP 地址上侦听网络上的其他计算机，建议使用静态 LAN IP。例如：

    listen-address=::1,127.0.0.1,192.168.1.1

使用 `cache-size=size` 设置缓存域名的数量（默认值为 `150`，硬限制为 `10000`）：

    cache-size=1000

要验证 DNSSEC，请加载 dnsmasq 软件包提供的 DNSSEC 信任锚，并设置选项 `dnssec`：

    conf-file=/usr/share/dnsmasq/trust-anchors.conf
    dnssec

要了解更多选项，请参阅 dnsmasq(8)。

#### DNS 地址文件和转发

配置 dnsmasq 后，需要将本地主机地址添加为 `/etc/resolv.conf` 中的唯一名称服务器。这会导致所有查询都发送到 dnsmasq。

由于 dnsmasq 是存根解析器而不是递归解析器，因此必须设置转发到外部 DNS 服务器。可以通过 openresolv 自动完成或在 dnsmasq 的配置中手动指定 DNS 服务器完成。

##### openresolv

如果网络管理器支持 resolvconf 而不是直接更改 `/etc/resolv.conf`，可以使用 openresolv 生成 dnsmasq 的配置文件。

编辑 `/etc/resolvconf.conf` 并将 loopback 地址添加为名称服务器，然后配置 openresolv 输出 dnsmasq 配置：

    /etc/resolvconf.conf

    # 使用本地名称服务器
    name_servers="::1 127.0.0.1"
    resolv_conf_options="trust-ad"

    # 输出 dnsmasq 扩展配置和解析文件
    dnsmasq_conf=/etc/dnsmasq-conf.conf
    dnsmasq_resolv=/etc/dnsmasq-resolv.conf

运行 `resolvconf -u` 创建配置文件。如果文件不存在，则 `dnsmasq.service` 无法启动。

编辑 dnsmasq 的配置文件使用 openresolv 生成的配置 [1]：

    # 读取 openresolv 生成的配置文件
    conf-file=/etc/dnsmasq-conf.conf
    resolv-file=/etc/dnsmasq-resolv.conf

##### 手动转发

首先，必须将本地主机地址设置为 `/etc/resolv.conf` 中的唯一名称服务器：

    /etc/resolv.conf

    nameserver ::1
    nameserver 127.0.0.1
    options trust-ad

确保 `/etc/resolv.conf` 不被修改，详述见 Domain name resolution#Overwriting of /etc/resolv.conf。

然后，必须在 dnsmasq 的配置文件中设置 `server=server_address` 指定上游 DNS 服务器地址。还要添加 `no-resolv`，以便 dnsmasq 不会非必要地读取只包含本地主机地址的 `/etc/resolv.conf`。

    /etc/dnsmasq.conf

    [...]
    no-resolv

    # 示例：Google 的名称服务器
    server=8.8.8.8
    server=8.8.4.4

现在，DNS 查询将使用 dnsmasq 解析，仅在缓存查询无结果时才会从外部服务器查询。

#### 添加自定域

可以将自定域主机添加到（本地）网络中：

    local=/lan/
    domain=lan

在此示例中，可以 ping （在 `/etc/hosts` 文件中定义的）主机/设备为 `hostname.lan`。

取消注释 `expand-hosts` 将自定域添加到主机条目：

    expand-hosts

如果没有此设置，则必须将域添加到 `/etc/hosts` 的条目中。

#### 测试

要执行查找速度测试，请选择自 dnsmasq 启动以来未访问过的网站（drill 是 ldns 软件包的一部分）：

    $ drill archlinux.org | grep "Query time"

再次运行该命令将使用缓存的 DNS IP，如果正确设置了 dnsmasq，则查找时间会缩短：

    $ drill archlinux.org | grep "Query time"

    ;; Query time: 18 msec

    $ drill archlinux.org | grep "Query time"

    ;; Query time: 2 msec

若要测试 DNSSEC 验证是否正常工作，请参阅 DNSSEC#Testing。

### DHCP 服务器

This article or section needs expansion.

Reason: 添加 IPv6 的说明 (Discuss in Talk:Dnsmasq (简体中文))

默认情况下，dnsmasq 关闭了 DHCP 功能，如要使用则必须将其打开。以下是重要的设置：

    # 仅侦听路由器的 LAN NIC。这样会将 tcp/udp 端口 53 开放给本地主机，并将 udp 端口 67 开放给全世界：
    interface=enp0s0

    # dnsmasq 将向全世界开放 tcp/udp 端口 53 和 udp 端口 67，以帮助动态接口（分配动态 IP）。
    # dnsmasq 将丢弃全部请求，但某些人可能希望关闭它并由内核处理。
    bind-interfaces

    # 设置域名（可选）
    domain=example.org

    # 设置默认网关
    dhcp-option=3,0.0.0.0

    # 设置要公布的 DNS 服务器
    dhcp-option=6,0.0.0.0

    # 如果 dnsmasq 服务器同时也为网络执行路由，则可以使用选项 121 推出静态路由。
    # x.x.x.x 是目标 LAN，yy 是 CIDR 表示法（通常为 /24），z.z.z.z 是执行路由的主机。
    dhcp-option=121,x.x.x.x/yy,z.z.z.z

    # 提供给 LAN PC 的 IP 动态范围和租赁时间。
    # 建议首先将租赁时间设置为 5m，以便测试一切正常之后再设置持久记录。
    dhcp-range=192.168.111.50,192.168.111.100,12h

    # 提供 IPv6 DHCP 租约，使用网络接口作为前缀构建范围
    dhcp-range=::f,::ff,constructor:enp0s0

    # 如果要让 dnsmasq 将固定 IP 分配给某些客户端，请绑定 LAN 计算机的 NIC MAC 地址：
    dhcp-host=aa:bb:cc:dd:ee:ff,192.168.111.50
    dhcp-host=aa:bb:cc:ff:dd:ee,192.168.111.51

更多选项请参阅 dnsmasq(8)。

#### Proxy DHCP

In case there is already a DHCP server running on the network and you want to interoperate with it, dnsmasq can be set to behave as a "proxy DHCP", therefore only serving the #PXE server specific information to the client. This mode is only available with IPv4. Use the following syntax, providing the existing DHCP server address:

    dhcp-range=192.168.0.1,proxy

#### Test

From a computer that is connected to the one with dnsmasq on it, configure it to use DHCP for automatic IP address assignment, then attempt to log into the network normally.

If you inspect the `/var/lib/misc/dnsmasq.leases` file on the server, you should be able to see the lease.

### TFTP server

dnsmasq has built-in TFTP server.

To use it, create a root directory for TFTP (e.g. `/srv/tftp`) to put transferable files in.

    enable-tftp
    tftp-root=/srv/tftp

For increased security it is advised to use dnsmasq's TFTP secure mode. In secure mode only files owned by the `dnsmasq` user will be served over TFTP. You will need to chown TFTP root and all files in it to `dnsmasq` user to use this feature.

    tftp-secure

See dnsmasq(8) for more options.

### PXE server

PXE requires a DHCP and a TFTP server; both can be provided by dnsmasq. To setup the PXE server, follow these steps:

1. Setup the #TFTP server and the #DHCP server (in full DHCP or proxy mode) in the dnsmasq configuration file,
2. Copy and configure a PXE compatible bootloader (e.g. PXELINUX) in the TFTP root directory,
3. Enable PXE in the dnsmasq configuration file:

To simply send one file:

    dhcp-boot=lpxelinux.0

To send a file depending on client architecture:

    pxe-service=x86PC,"PXELINUX (BIOS)",bios/lpxelinux
    pxe-service=X86-64_EFI,"PXELINUX (EFI)",efi64/syslinux.efi

Note:

- File paths are relative to the TFTP root path
- If the file has a .0 suffix, you must exclude the suffix in `pxe-service` options

In case `pxe-service` does not work to identify the architecture (especially for UEFI-based clients), combination of `dhcp-match` and `dhcp-boot` can be used. See RFC 4578 2.1 for more `client-arch` numbers for use with dhcp boot protocol.

    dhcp-match=set:efi-x86_64,option:client-arch,7
    dhcp-match=set:efi-x86_64,option:client-arch,9
    dhcp-match=set:efi-x86,option:client-arch,6
    dhcp-match=set:bios,option:client-arch,0
    dhcp-boot=tag:efi-x86_64,efi64/syslinux.efi
    dhcp-boot=tag:efi-x86,efi32/syslinux.efi
    dhcp-boot=tag:bios,bios/lpxelinux.0

See dnsmasq(8) for more options.

The rest is up to the bootloader.

## Tips and tricks

### Prevent OpenDNS redirecting Google queries

To prevent OpenDNS from redirecting all Google queries to their own search server, add to `/etc/dnsmasq.conf`:

    server=/www.google.com/<ISP DNS IP>

### Override addresses

In some cases, such as when operating a captive portal, it can be useful to resolve specific domains names to a hard-coded set of addresses. This is done with the `address` config:

    address=/example.com/1.2.3.4

Furthermore, it is possible to return a specific address for all domain names that are not answered from `/etc/hosts` or DHCP by using a special wildcard:

    address=/#/1.2.3.4

### More than one instance

If we want two or more dnsmasq servers works per interface(s).

#### Static

To do this staticly, server per interface, use `interface` and `bind-interfaces` options. This enforce start second dnsmasq.

#### Dynamic

In this case we can exclude per interface and bind any others:

    except-interface=lo
    bind-dynamic

Note: This is the default in libvirt.

### Domain blocklisting

To blocklist domains, i.e. answer queries for them with NXDOMAIN, use the `address` option without specifying the IP address:

    address=/blocked.example/
    address=/anotherblocked.example/

Note: Unlike the `/etc/hosts` file, dnsmasq will block these domains and also all subdomains such as subdomain.blocked.example.

Wildcards are also supported. Add a `*` to the start of the pattern:

    # blocks both blocked.example and anotherblocked.example and all their subdomains
    address=/*blocked.example/

    # blocks subdomains like mail.google.com but not google.com
    address=/*.google.com/

Some specific subdomains can be unblocked using `#` as the server address:

    # blocks google.com and all subdomains except mail.google.com.
    address=/google.com/
    server=/mail.google.com/#

Note:

- The options `address=/example.com/` and `server=/example.com/` are equivalent. Both will answer queries for them with NXDOMAIN.
- The options `address=/example.com/#` and `server=/example.com/#` are not equivalent.
  - `address=/example.com/#` will answer queries for the domain with the NULL address (0.0.0.0 or :: for IPv6).
  - `server=/example.com/#` will send queries for the domain to the standard configured servers.
- The patterns `/example.com/` and `/.example.com/` are equivalent. Both will match example.com and all its subdomains.

For ease of use place the blocklist in a separate file, e.g. `/etc/dnsmasq.d/blocklist.conf` and load it from `/etc/dnsmasq.conf` with `conf-file=/etc/dnsmasq.d/blocklist.conf` or `conf-dir=/etc/dnsmasq.d/,*.conf`.

Tip:

- A list of potential sources for the blocklist can be found in OpenWrt's adblock package's README.
- A hosts file blocklist can be used with the `addn-hosts=hosts.txt` option or it can be converted to a dnsmasq blocklist with this awk command: `awk '/^[^#]/ { print "address=/"$2"/"$1"" }' hosts.txt`.

## 参阅

- Caching Nameserver using dnsmasq, and a few other tips and tricks.

Categories:

- Domain Name System (简体中文)
- DHCP (简体中文)

Hidden category:

- Pages or sections flagged with Template:Expansion