当日志前缀中存在空格字符时,以编程方式使用 iptables-restore

问题描述 投票:0回答:1

我正在编写一个程序来拍摄 iptable 规则的快照,以便以后可以恢复它们。我不想将规则写入文件;我将它们作为字符串存储在我的代码中。

调用

iptables-save
并将输出捕获到字符串中,然后调用
iptables-restore
与 bash 进程替换相结合,将规则字符串反馈回 iptables,例如
iptables-restore <(echo "<rules here>")
(稍后必须更改此设置以使用管道,因为 Ubuntu 不支持)

我遇到过一个案例,其中一个

log-prefix
选项在其中一条规则上有一个空格导致恢复步骤中断。例如:

[root@host ~]# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination         
LOG        all  --  anywhere             anywhere             limit: avg 3/min burst 10 LOG level warning prefix "[UFW BLOCK] "

iptables-save
的输出:

[root@host ~]# iptables-save
# Generated by iptables-save v1.8.8 (nf_tables) on Wed May  3 21:45:25 2023
*filter
:INPUT ACCEPT [101:5876]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [84:34334]
-A OUTPUT -m limit --limit 3/min --limit-burst 10 -j LOG --log-prefix "[UFW BLOCK] "
COMMIT
# Completed on Wed May  3 21:45:25 2023

这是代码运行的命令:

/bin/sh -c /sbin/iptables-restore <(echo "# Generated by iptables-save v1.8.8 (nf_tables) on Wed May  3 21:45:25 2023
*filter
:INPUT ACCEPT [1936:94741]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [612:2005831]
-A OUTPUT -m limit --limit 3/min --limit-burst 10 -j LOG --log-prefix "[UFW BLOCK] "
COMMIT
# Completed on Wed May  3 21:45:25 2023
")
Bad argument `BLOCK]'
Error occurred at line: 6
Try `iptables-restore -h' or 'iptables-restore --help' for more information.

如果我删除

UFW
BLOCK
之间的空格,它就可以了。

我也试过转义字符串中的引号,但仍然是同样的问题。

有什么技巧可以让它发挥作用吗?此外,我无法控制规则中可能包含的内容,它们需要完全按照从快照中获取的内容进行替换,因此在调用恢复之前预处理字符串对我来说不起作用。

linux iptables
1个回答
0
投票

所以看起来在办公室里的几个人反映这个问题后我实际上已经开始工作了。转义引号的解决方案是正确的,例如

\"[UFW BLOCK] \"
。我以为它不起作用,因为我正在监视命令的输出:

/bin/sh -c /sbin/iptables-restore <(echo "# Generated by iptables-save v1.8.8 (nf_tables) on Wed May  3 22:15:05 2023
*filter
:INPUT ACCEPT [258:20165]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [210:104923]
-A OUTPUT -m limit --limit 3/min --limit-burst 10 -j LOG --log-prefix \"[UFW BLOCK] \"
COMMIT
# Completed on Wed May  3 22:15:05 2023
")

其中存在转义字符,但在运行 iptables list 时我发现它们不存在:

[root@host ~]# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination         
LOG        all  --  anywhere             anywhere             limit: avg 3/min burst 10 LOG level warning prefix "[UFW BLOCK] "

为愚蠢的时刻道歉!

© www.soinside.com 2019 - 2024. All rights reserved.