linux普通用户使用1024以下的端口(80)
linux
对于非root
权限用户不能使用1024
以下的端口,对于一些服务,过高的权限,会带来一定的风险。那么对于低权限的用户如何对外开放1024
以下的端口。我这里找到几种办法并且亲测可行
首先搭建环境centos7
账户prod
没有sudo
权限
1. nginx 等软件做反向代理
使用nginx启动80端口反向代理后台服务,后台服务可以写1024之后的端口
2. iptables端口转发
首先程序绑定1024
以上的端口,然后root
权限下做转发注意有些系统需要手动开启IP FORWARD
功能
临时修改
sysctl -w net.ipv4.ip_forward=1
或:修改文件sysctl.conf
vi /etc/sysctl.conf
#修改
net.ipv4.ip_forward = 1
#重新加载
sysctl -p /etc/sysctl.conf
使用root配置端口转发,把80端口转发到本机的后台服务6666端口上
iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 6666
3. setuid
root账户下执行
##正常情况下是不能监听80端口的
[test@test nginx]$ sbin/nginx -c conf/nginx.conf
nginx: [emerg] bind() to 0.0.0.0:80 failed (13: Permission denied)
##下面给nginx授权suid权限
[root@test nginx]# chown root:root sbin/nginx
[root@test nginx]# chmod 4755 sbin/nginx
You have new mail in /var/spool/mail/root
[root@test nginx]# ll sbin/nginx
-rwsr-xr-x. 1 root root 17675424 May 22 16:43 sbin/nginx
## 用普通用户运行nginx,监听80端口
[test@test nginx]$ sbin/nginx -c conf/nginx.conf
[test@test nginx]$ ps -ef |grep nginx
root 29988 1 0 13:15 ? 00:00:00 nginx: master process sbin/nginx -c conf/nginx.conf
nobody 29989 29988 0 13:15 ? 00:00:00 nginx: worker process
nobody 29990 29988 0 13:15 ? 00:00:00 nginx: worker process
nobody 29991 29988 0 13:15 ? 00:00:00 nginx: worker process
nobody 29992 29988 0 13:15 ? 00:00:00 nginx: worker process
test 30699 23722 0 13:16 pts/1 00:00:00 grep --color=auto nginx
从上面可以看出来nginx可以运行,
但是主进程仍然是以root权限运行,这样并不安全。
4. CAP_NET_BIND_SERVICE
从 2.1
版本开始,Linux
内核有了能力的概念,这使得普通用户也能够做只有超级用户才能完成的工作,这包括使用端口。
获取CAP_NET_BIND_SERVICE
能力,即使服务程序运行在非root帐户下,也能够binding
到低端口。使用的方法:root
账户下执行
setcap cap_net_bind_service=+eip nginx/sbin/nginx
切换到test账户下
信息如下
[root@centos7 sbin]# setcap cap_net_bind_service=+eip nginx
[root@centos7 sbin]# su test
[test@centos7 sbin]$ ./nginx
[test@centos7 sbin]$ ps -aux| grep nginx
test 18014 0.0 0.1 45500 1124 ? Ss 18:49 0:00 nginx: master process ./nginx
test 18015 0.0 0.1 45960 1596 ? S 18:49 0:00 nginx: worker process
test 18017 0.0 0.0 112664 984 pts/0 R+ 18:49 0:00 grep --color=auto nginx
[test@centos7 sbin]$
cap_net_bind_service
最后别忘记怎么清除这个能力