美文网首页Amazing Archlinux tools
linux普通用户使用1024以下的端口(80)

linux普通用户使用1024以下的端口(80)

作者: 天天向上卡索 | 来源:发表于2019-02-27 23:21 被阅读21次

linux普通用户使用1024以下的端口(80)

Intro

linux对于非root权限用户不能使用1024以下的端口,对于一些服务,过高的权限,会带来一定的风险。那么对于低权限的用户如何对外开放1024以下的端口。我这里找到几种办法并且亲测可行

首先搭建环境 centos7 账户 tengine 没有 sudo 权限

nginx 等软件做反向代理

利用 nginx 做反向代理,nginx 监听 80 端口,将请求转发到实际监听的端口,示例:

nginx

iptables端口转发

首先程序绑定1024以上的端口,然后root权限下做转发注意有些系统需要手动开启IP FORWARD功能

sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080

setuid

root账户下执行

chown root:root nginx
chmod 4755 nginx

从图片可以看出来nginx可以运行,但是主进程仍然是以root权限运行,这样并不安全。

CAP_NET_BIND_SERVICE

从 2.1 版本开始,Linux 内核有了能力的概念,这使得普通用户也能够做只有超级用户才能完成的工作,这包括使用端口。

获取 CAP_NET_BIND_SERVICE 能力,即使服务程序运行在非root帐户下,也能够 binding 到低端口。使用的方法:

sudo setcap cap_net_bind_service=+eip /home/tengine/nginx/tengine/sbin/nginx

切换到 tengine 账户下,信息如下:

[root@centos7 sbin]# setcap cap_net_bind_service=+eip /home/tengine/nginx/tengine/sbin/nginx
[root@centos7 sbin]# su tengine
[tengine@centos7 sbin]$ stat nginx
  文件:"nginx"
  大小:6054330         块:11832      IO 块:4096   普通文件
设备:fd00h/64768d      Inode:397136      硬链接:1
权限:(0755/-rwxr-xr-x)  Uid:( 1001/ tengine)   Gid:( 1001/ tengine)
最近访问:2016-10-11 18:43:05.402239835 +0800
最近更改:2016-10-11 18:25:47.273183401 +0800
最近改动:2016-10-11 18:48:23.084257104 +0800
创建时间:-
[tengine@centos7 sbin]$ ./nginx
[tengine@centos7 sbin]$ ps -aux| grep nginx
tengine  18014  0.0  0.1  45500  1124 ?        Ss   18:49   0:00 nginx: master process ./nginx
tengine  18015  0.0  0.1  45960  1596 ?        S    18:49   0:00 nginx: worker process
tengine  18017  0.0  0.0 112664   984 pts/0    R+   18:49   0:00 grep --color=auto nginx
[tengine@centoshttps://superuser.com/questions/710253/allow-non-root-process-to-bind-to-port-80-and-4437 sbin]$

最后别忘记怎么清除这个能力

 setcap -r nginx

Reference

相关文章

网友评论

    本文标题:linux普通用户使用1024以下的端口(80)

    本文链接:https://www.haomeiwen.com/subject/hrtcuqtx.html