如何禁止用户绑定除某个地址以外的套接字?

我希望不允许该用户在Internet接口上绑定端口(有效地创build世界上可访问的服务器,尽pipe在端口上> 1024),但是允许在某些端口的环回接口中进行绑定。

有没有一个神奇的iptables技巧或什么来得到这个效果?

这台服务器不能运行SELinux,现在设置起来太浪费了,所以我更喜欢其他的解决scheme。

我没有看到强制套接字到某个端口的可能性,但可以防止其他端口被成功使用。 这可以通过iptables及其owner模块完成。 您可以从属于该用户的进程中删除来自不允许的地址的所有回复。

如果这是你的select,你不知道该怎么做,让我知道,我会另外提供一些代码。

编辑1

解决scheme是阻止来自该用户的所有数据包

  1. 对于这个用户已经打开的连接(即他根本不在端口上)
  2. 也不从一个允许的端口发送。

你是对的, owner不在INPUT中工作,但我们只需要OUTPUT。 为了使事情变得更容易(也更快),我们将所有允许的数据包(来自该用户)标记为42,全部不允许使用41.标记不允许的数据包就足够了。

它以这种方式工作:

  1. 所有来自该用户的数据包(连接)都被选中进行特殊处理
  2. 所有数据包都标有41(不允许)。 对于允许的连接,稍后将被覆盖。
  3. 所有与本地生成的第一个数据包连接都是允许的
  4. 剩下的一切都不是在本地创build的 放下一切,不要从低落
  5. 现在允许所有与允许的源端口连接(回复的本地端口)
  6. 最后一步:丢弃所有标有41的数据包。

编辑2

使用nat表的方法失败(对于传入连接,因为在nat仅检查连接的第一个数据包,而第一个是传入的连接,只有在owner模块不可用的情况下才会-t nat INPUT )。 因此,所有检查和标记现在都在默认表( filter )中完成。

剧本:

 #!/bin/bash # MODIFY NEXT LINE user=hl # iptables -F # iptables -t nat -F # iptables -t mangle -F iptables -N user_x &>/dev/null iptables -N user_x_ports &>/dev/null iptables -N user_x_allow &>/dev/null iptables -N user_x_block &>/dev/null # configure chain user_x_allow iptables -A user_x_allow -j CONNMARK --set-mark 42 iptables -A user_x_allow -j ACCEPT # configure chain user_x_block iptables -A user_x_block -j CONNMARK --set-mark 41 iptables -A user_x_block -j DROP # configure chain user_x_ports # one line for each allowed port iptables -A user_x_ports -p tcp --sport 1234 -j user_x_allow # configure chain user_x iptables -A user_x -m conntrack --ctstate NEW -j user_x_allow iptables -A user_x \! -o lo -j user_x_block iptables -A user_x -j user_x_ports iptables -A user_x -j user_x_block # the first two rules are just for checking what happens with "iptables -L -nv" # and can be commented out index=1 iptables -I OUTPUT "$index" -m owner --uid-owner $user; ((index++)) # just count iptables -I OUTPUT "$index" -m owner --uid-owner $user -m connmark --mark 0; ((index++)) # just count iptables -I OUTPUT "$index" -m connmark --mark 41 -j DROP # or reset ((index++)) iptables -I OUTPUT "$index" -m connmark --mark 42 -j ACCEPT ((index++)) # this matches non-marked (new) connections only iptables -I OUTPUT "$index" -m owner --uid-owner $user -j user_x ((index++))