问题
不知道哪次升级以后,笔者的libvirt虚拟机突然无法连接到外网。在检查了libvirt的网络设置、虚拟机的网络设置、dnsmasq的设置等等之后,发现问题出在了防火墙上。
解决
防火墙规则
首先,查看ufw的状态:
sudo ufw status
如果ufw是启用的,可以看到类似如下的输出:
Status: active
To                         Action      From
--                         ------      ----
xxxx                       ALLOW       Anywhere
首先允许virbr0的访问:
sudo ufw allow in on virbr0
sudo ufw allow out on virbr0
然后,编辑ufw的默认配置文件/etc/default/ufw,将DEFAULT_FORWARD_POLICY设置为ACCEPT:
DEFAULT_FORWARD_POLICY="ACCEPT"
可以直接运行sed命令:
sudo sed -i 's/DEFAULT_FORWARD_POLICY="DROP"/DEFAULT_FORWARD_POLICY="ACCEPT"/' /etc/default/ufw
最后,重启ufw:
sudo ufw disable
sudo ufw enable
监听接口占用1
在使用virsh net-start default启用网桥的时候,可能会遇到类似如下的错误:
internal error: Child process (VIR_BRIDGE_NAME=virbr0 /usr/bin/dnsmasq --conf-file=/var/lib/libvirt/dnsmasq/default.conf --leasefile-ro --dhcp-script=/usr/lib/libvirt/libvirt_leaseshelper) unexpected exit status 2: 
dnsmasq: failed to create listening socket for 192.168.122.1: Address already in use
这是因为dnsmasq的监听接口被占用了。可以通过netstat查看:
sudo lsof -i :53 | grep LISTE
可以看到类似如下的输出:
dnsmasq 75746 dnsmasq 5u  IPv4 912512      0t0  TCP *:domain (LISTEN)
dnsmasq 75746 dnsmasq 7u  IPv6 912514      0t0  TCP *:domain (LISTEN)
可以看到dnsmasq占用了53端口。一般可以通过systemctl停止dnsmasq:
sudo systemctl stop dnsmasq
sudo systemctl disable dnsmasq
如果确实需要dnsmasq,可以编辑/etc/dnsmasq.conf,将bind-interfaces和listen-address注释掉:
bind-interfaces
interface=[some physical interface name, e.g. eth0]
listen-address=[ip address of the interface you want, e.g. 192.168.1.1]
然后重启dnsmasq:
sudo systemctl restart dnsmasq
这样,libvirt的虚拟机就可以正常连接到外网了。
其他
启用ufw之后,笔者还遇到了KDE Connect无法连接的问题,同样可以设置ufw的规则:
sudo ufw allow 1714:1764/udp
sudo ufw allow 1714:1764/tcp
sudo ufw reload
这样,在同一局域网下,搭载KDE的电脑和装有KDE Connect APP的手机就可以正常连接了。