今天是: 收藏本站 设为主页
网站首页 >  技术专栏  >  linux  > 

Ubuntu 服务器版 Iptables 基本设置指南

日期:2011-03-16  点击率:3588



Allowing Incoming Traffic on Specific Ports 开放指定的端口
You could start by blocking traffic, but you might be working over SSH, where you would need to allow SSH before blocking everything else.

To allow incoming traffic on port 22 (traditionally used by SSH), you could tell iptables to allow all TCP traffic on port 22 of your network adapter.

刚开始时您不妨阻断所有通信,但考虑到您将来可能要使用SSH,那么您要让iptables在使用默认规则丢弃报文之前,允许SSH报文通过。

要开放端口22(SSH的默认端口),您要告诉iptables允许接受到的所有目标端口为22的TCP报文通过。

# iptables -A INPUT -p tcp -i eth0 --dport ssh -j ACCEPT
Specifically, this appends (-A) to the table INPUT the rule that any traffic to the interface (-i) eth0 on the destination port for ssh that iptables should jump (-j), or perform the action, ACCEPT.

执行上面的命令,一条规则会被追加到INPUT规则表的末尾(-A表示追加)。根据这条规则,对所有从接口eth0(-i指出对通过哪个接口的报文运用此规则)接收到的目标端口为22的报文,iptables要执行ACCEPT行动(-j指明当报文与规则相匹配时应采取的行动)。

Lets check the rules: (only the first few lines shown, you will see more)

我们来看看规则表中的情况:(这里只列出了开始的几行,您应该会看到更多内容)

# iptables -LChain INPUT (policy ACCEPT)target prot opt source destinationACCEPT all -- anywhere anywhere state RELATED,ESTABLISHEDACCEPT tcp -- anywhere anywhere tcp dpt:ssh
Now, let's allow all web traffic

现在我们开放端口80:

# iptables -A INPUT -p tcp -i eth0 --dport 80 -j ACCEPT
Checking our rules, we have

此时的规则表中的内容如下:

# iptables -LChain INPUT (policy ACCEPT)target prot opt source destinationACCEPT all -- anywhere anywhere state RELATED,ESTABLISHEDACCEPT tcp -- anywhere anywhere tcp dpt:sshACCEPT tcp -- anywhere anywhere tcp dpt:www
We have specifically allowed tcp traffic to the ssh and web ports, but as we have not blocked anything, all traffic can still come in.

通过上述命令,我们已经代开了SSH和web服务的相应的端口,但由于没有阻断任何通信,因此所有的报文都能通过。

Blocking Traffic 阻断通信
Once a decision is made about a packet, no more rules affect it. As our rules allowing ssh and web traffic come first, as long as our rule to block all traffic comes after them, we can still accept the traffic we want. All we need to do is put the rule to block all traffic at the end. The -A command tells iptables to append the rule at the end, so we'll use that again.

对每一个报文,iptables依次测试每一条规则,看报文与规则是否相匹配。一旦找到一条匹配的规则,就根据此规则中指定的行动,对报文进行处置,而对后面的规则不再进行测试。因此,如果我们在规则表的末尾添加一条规则,让iptables丢弃所有报文,但由于有了前面几条规则,ssh和web的正常通信不会受到影响。

# iptables -A INPUT -j DROP# iptables -LChain INPUT (policy ACCEPT)target prot opt source destinationACCEPT all -- anywhere anywhere state RELATED,ESTABLISHEDACCEPT tcp -- anywhere anywhere tcp dpt:sshACCEPT tcp -- anywhere anywhere tcp dpt:wwwDROP all -- anywhere anywhere
Because we didn't specify an interface or a protocol, any traffic for any port on any interface is blocked, except for web and ssh.

在上面的规则中,没有明确指出针对哪个接口或哪种协议使用此规则,所以从每个接口接收到的除ssh和web之外的所有报文都会被丢弃。




下一篇:谈PHP生成静态页面    上一篇:mysql套接字和tcpip连接方式