标签 Linux系统安全 下的文章

Server Shield是一款轻量级的系统保护和强化工具

它的功能包括:

Firewall Hardening 防火墙强化
TCP Hardening TCP强化
Data Leakage Protection 防泄保护
ICMP/Ping Flood Protection ICMP/Ping攻击保护
Rootkit Protection Rootkit保护
DoS Protection DDOS保护
Spoof Protection Spoof保护
Bogus TCP Protection Bogus TCP保护
SYN Flood Protection 洪水攻击保护
FTP/SSH 暴力破解保护
等……

依赖软件

yum-security
iptables
net-tools
sed
gawk
git

安装

git clone https://github.com/bluedragonz/server-shield

cd server-shield;chmod +x sshield;mv sshield /etc/init.d

/etc/init.d/sshield start    

项目地址:https://github.com/bluedragonz/server-shield

安装教程

cd /usr/local/src
wget http://techsware.in/downloads/harden.sh
chmod 755 harden.sh
./harden.sh 

1:什么是KalluscPHarden?
答:KalluscPHarden是一个shell脚本,基于cPanel服务器安全加固、检查。

2:会为cPanel做什么?
答:改变调整设置,密码修改强度,后台进程检查,编译器的访问安全,Shell Bomb Fork保护等设置....

3:有什么额外的应用程序将安装到服务器?
答:CSF,CMM,CMQ,CMC,Maldet,Rkhunter,Linux Socket 监控,Linux的环境安全等

4:服务器会有哪些地方被调整/加固?
答:Apache,cPanel,FTP,SSH,MySQL,CSF,PHP等

5: What additional hardening steps it does ?
Ans : TMP hardening, Logrotate hardening, Daily Rkhunter scanning, rDNS Check, Disable unwanted processes, SYN FLOOD Kernel Tweak, etc

6: How to recover the old configuration, before running this tool?
Ans : All configurations will be backup as conf_file.beforetweak before making changes to it. So you can compare the configurations in you want to check anything.

7: Any more tweaks it do ?
Ans : Check change log for recent changes to the script

8:这个脚本多少钱?
答:它是完全免费的。

9:想知道更多?
Ans : Please feel free to reach me at kallu[at]techsware.in

官方主页:http://techsware.in/kcpharden.html

SYNFLOOD is disabled by default. If you are not receiving any sort of attack, there is no need to enable it. If you are expecting an attack, enable it and set the rules a bit strict, like

SYNFLOOD_RATE = "5/s"
SYNFLOOD_BURST = "3"

i.e. if 5 connections are received from an IP/sec for 3 times, block it. Make sure don't keep it too strict if you are not receiving an attack else it will generate false positives and will block legit connections.

摘自:http://www.webhostingtalk.com/showthread.php?t=892958

ELS stands for Easy Linux Security. ELS was created by Richard Gannon, Martynas Bendorius and Wael Isa. ELS takes many of the tasks performed by our Administrators and puts it into an easy to use program for anyone to use. It is released under the GNU/GPL so it is free to use.

This program is always being improved with new features and bugfixes, so be sure to keep it up to date. If you found a bug or would like an improvement, please let us know! If you really like this program, donations are welcome!

支持的操作系统 :

* Red Hat Linux
* Red Hat Enterprise Linux
* Fedora Core
* CentOS
* Debian

ELS 有哪些功能:

* Install RKHunter
* Install RKHunter Cronjob which emails a user-set email address nightly
* Install/update APF
* Install/update BFD
* Install CHKROOTKIT
* Install CHKROOTKIT Cronjob which emails a user-set email address nightly
* Disable Telnet
* Force SSH Protocol 2
* Secure /tmp
* Secure /var/tmp
* Secure /dev/shm
* 安装/升级 Zend Optimizer
* 安装/升级 eAccelerator
* MySQL 4.1 and 5.0 Configuration Optimization
* Upgrade MySQL to 5.0
* Tweak WHM Settings for security and stability
* Configure RNDC if not already done (cPanel only)
* Change SSH port (also configure APF as necessary)
* Add wheel user and disable direct root login over SSH
* 优化 MySQL tables
* 安装/升级 Libsafe
* 安装/升级 ImageMagick (from latest source)
* Uninstall LAuS
* Harden sysctl.conf
* Install Chirpy’s Free Exim Dictionary Attack ACL (cPanel only)
* 更多!

安装 ELS, 以ROOT身份运行以下命令:

wget -O installer.sh http://els.web4host.net/installer.sh
chmod +x installer.sh
sh installer.sh

官方网站:http://www.web4host.net/easy-linux-security/

netstat 工具来检测SYN攻击

# netstat -n -p -t
tcp0 0 10.11.11.11:23124.173.152.8:25882 SYN_RECV-
tcp0 0 10.11.11.11:23236.15.133.204:2577 SYN_RECV-
tcp0 0 10.11.11.11:23127.160.6.129:51748 SYN_RECV-

LINUX系统中看到的,很多连接处于SYN_RECV状态(在WINDOWS系统中是SYN_RECEIVED状态), 源IP地址都是随机的,表明这是一种带有IP欺骗的SYN攻击。

# netstat -n -p -t | grep SYN_RECV | grep :80 | wc -l
324

查看在LINUX环境下某个端囗的未连接队列的条目数,显示TCP端囗22的未连接数有324个,虽然还远达不到系统极限,但应该引起管理员的注意。

[root@pub wxjsr]# netstat -na | grep SYN_RECV
tcp 0 0 58.193.192.20:80 221.0.108.162:32383 SYN_RECV
tcp 0 0 58.193.192.20:80 125.85.118.231:2601 SYN_RECV
tcp 0 0 58.193.192.20:80 222.242.171.215:2696 SYN_RECV
tcp 0 0 58.193.192.20:80 116.52.10.51:2629 SYN_RECV
tcp 0 0 58.193.192.20:80 218.171.175.157:1117
[root@pub wxjsr]# netstat -na | grep SYN_RECV |wc
11 66 979

查看系统SYN相关的配置

Linux内核提供了若干SYN相关的配置,用命令: sysctl -a | grep syn

[root@metc apache2]# /sbin/sysctl -a | grep syn
net.ipv6.conf.default.max_desync_factor = 600
net.ipv6.conf.all.max_desync_factor = 600
net.ipv6.conf.eth0.max_desync_factor = 600
net.ipv6.conf.lo.max_desync_factor = 600
net.ipv4.netfilter.ip_conntrack_tcp_timeout_syn_recv = 60
net.ipv4.netfilter.ip_conntrack_tcp_timeout_syn_sent = 120
net.ipv4.tcp_max_syn_backlog = 1280
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 5
fs.quota.syncs = 18

防范SYN攻击设置

#缩短SYN- Timeout时间:

iptables -A FORWARD -p tcp --syn -m limit --limit 1/s -j ACCEPT
iptables -A INPUT -i eth0 -m limit --limit 1/sec --limit-burst 5 -j ACCEPT

#每秒 最多3个 syn 封包 进入 表达为 :

iptables -N syn-flood
iptables -A INPUT -p tcp --syn -j syn-flood
iptables -A syn-flood -p tcp --syn -m limit --limit 1/s --limit-burst 3 -j RETURN
iptables -A syn-flood -j REJECT

#设置syncookies:

sysctl -w net.ipv4.tcp_syncookies=1
/sbin/sysctl -w net.ipv4.tcp_max_syn_backlog=3000
/sbin/sysctl -w net.ipv4.tcp_synack_retries=1
/sbin/sysctl -w net.ipv4.tcp_syn_retries=1
sysctl -w net.ipv4.conf.all.send_redirects=0
sysctl -w net.ipv4.conf.all.accept_redirects=0
sysctl -w net.ipv4.conf.all.forwarding=0
/sbin/sysctl -w net.ipv4.icmp_echo_ignore_broadcasts=1
/sbin/sysctl -w net.ipv4.conf.default.accept_source_route=0 # 禁用icmp源路由选项
/sbin/sysctl -w net.ipv4.icmp_echo_ignore_broadcasts=1 # 忽略icmp ping广播包,应开启
/sbin/sysctl -w net.ipv4.icmp_echo_ignore_all=1 # 忽略所有icmp ping数据,覆盖上一项

转载:http://www.tuicool.com/articles/m6nE3q

cat>>/home/cc.sh< #!/bin/sh
status=`netstat -na|awk '$5 ~ /[0-9]+:[0-9]+/ {print $5}' |awk -F ":" -- '{print $1}' |sort -n|uniq -c |sort -n|tail -n 1`
NUM=`echo $status|awk '{print $1}'`
IP=`echo $status|awk '{print $2}'`
result=`echo "$NUM > 150" | bc`
if [ $result = 1 ]
then
echo IP\:$IP is over $NUM, BAN IT!
echo $(date +"%y-%m-%d") `uptime`
/sbin/iptables -I INPUT -s $IP -j DROP
fi
EOF
ln -sf /usr/bin/apt-get /usr/bin/yum
yum install -y bc

执行/home/cc.sh即可! 也可以将执行脚本加入到Cron执行!

转载:http://www.jb4.net/archives/74.html

什么是HttpGuard

HttpGuard是基于openresty,以lua脚本语言开发的防cc攻击软件。而openresty是集成了高性能web服务器Nginx,以及一系列的Nginx模块,这其中最重要的,也是我们主要用到的nginx lua模块。HttpGuard基于nginx lua开发,继承了nginx高并发,高性能的特点,可以以非常小的性能损耗来防范大规模的cc攻击。
下面介绍HttpGuard防cc的一些特性。

  1. 限制访客在一定时间内的请求次数
  2. 向访客发送302转向响应头来识别恶意用户,并阻止其再次访问
  3. 向访客发送带有跳转功能的js代码来识别恶意用户,并阻止其再次访问
  4. 向访客发送cookie来识别恶意用户,并阻止其再次访问
  5. 支持向访客发送带有验证码的页面,来进一步识别,以免误伤
  6. 支持直接断开恶意访客的连接
  7. 支持结合iptables来阻止恶意访客再次连接
  8. 支持白名单功能
  9. 支持根据统计特定端口的连接数来自动开启或关闭防cc模式

github项目地址:https://github.com/centos-bz/HttpGuard
联系作者:admin#centos.bz
赞助作者持续开发:查看支付宝条码

开始部署HttpGuard

一、安装openresty或者nginx lua

假设我们把HttpGuard安装到/data/www/waf/,当然你可以选择安装在任意目录,nginx运行的用户为www。

cd /data/www
wget --no-check-certificate https://github.com/centos-bz/HttpGuard/archive/master.zip
unzip master.zip
mv HttpGuard-master waf
chown www waf/logs

三、生成验证码图片(可选)

为了支持验证码识别用户,我们需要先生成验证码图片。生成验证码图片需要系统安装有php,以及php-gd模块。

以命令行执行getImg.php文件

cd /data/www/waf/captcha/
/usr/local/php/bin/php getImg.php

大概要生成一万个图片,可能需要花几分钟的时间。

四、修改nginx.conf配置文件

向http区块输入如下代码:

lua_package_path "/data/www/waf/?.lua";
lua_shared_dict guard_dict 100m;
lua_shared_dict dict_captcha 70m;
init_by_lua_file '/data/www/waf/init.lua';
access_by_lua_file '/data/www/waf/runtime.lua';
lua_max_running_timers 1;

记得要修改相关的路径。

五、配置HttpGuard

HttpGuard全部的配置项都在config.lua文件中,请根据以下文章修改配置文件。

https://www.lxconfig.com/thread-121-1-1.html

wget http://www.rfxn.com/downloads/bfd-current.tar.gz
tar zxf bfd-current.tar.gz
./install.sh
执行程序 —> /usr/local/bfd/bfd
BFD配置文件 —> /usr/local/bfd/bfd/conf.bfd
BFD ftp 规则 —> /usr/local/bfd/rules/proftpd

接下来我们打开BFD的配置文件,对密码错误尝试次数进行限制和配置使用什么防火墙封锁IP。

一、登入失败尝试次数限制

# how many failure events must an address have before being blocked?
# you can override this on a per rule basis in /usr/local/bfd/rules/
TRIG="5"

该设置意思为,登入失败五次执行封锁命令

二、封锁执行程序

如果使用APF防火墙默认即可,如果我们使用CSF作为防火墙,修改为

BAN_COMMAND="/usr/sbin/csf -d $ATTACK_HOST {bfd.$MOD}"

如果使用Iptables则修改为

BAN_COMMAND= "iptables -A INPUT -s $ATTACK_HOST -j DROP"

使用系统 route 命令, 丢弃该IP数据,则

BAN_COMMAND="route add -host $ATTACK_HOST reject"

三、启动BFD

/usr/local/bfd/bfd -q —> (安静输出)

/usr/local/bfd/bfd -s —–> (标准输出)

/usr/local/bfd/bfd -a ——> (尝试错误列表输出)

最后,检查防火墙黑名单文件,检查穷举IP是否被正确封锁。

/etc/csf/csf.deny
/etc/apf/apf.deny

参考:http://corpocrat.com/2010/01/02/preventing-brute-force-attacks-on-ftp-server/

为了减少一些误报,我们需要把 Directadmin 的一些值得信赖的服务添加CSF/LFD例外。编辑/etc/csf/csf.pignore 输入以下内容:

cmd:spamd child
exe:/bin/dbus-daemon
exe:/sbin/ntpd
exe:/usr/bin/dbus-daemon
exe:/usr/bin/dbus-daemon-1
exe:/usr/bin/fetchmail
exe:/usr/bin/freshclam
exe:/usr/libexec/dovecot/anvil
exe:/usr/libexec/dovecot/imap
exe:/usr/libexec/dovecot/imap-login
exe:/usr/libexec/dovecot/managesieve
exe:/usr/libexec/dovecot/managesieve-login
exe:/usr/libexec/dovecot/pop3
exe:/usr/libexec/dovecot/pop3-login
exe:/usr/libexec/gam_server
exe:/usr/libexec/hald-addon-acpi
exe:/usr/libexec/hald-addon-keyboard
exe:/usr/local/bin/clamd
exe:/usr/local/bin/freshclam
exe:/usr/local/bin/pureftpd_uploadscan.sh
exe:/usr/local/directadmin/dataskq
exe:/usr/local/directadmin/directadmin
exe:/usr/local/libexec/dovecot/imap
exe:/usr/local/libexec/dovecot/imap-login
exe:/usr/local/libexec/dovecot/pop3
exe:/usr/local/libexec/dovecot/pop3-login
exe:/usr/local/mysql-5.1.54-linux-x86_64/bin/mysqld
exe:/usr/local/php53/bin/php53
exe:/usr/local/php53/bin/php-cgi53
exe:/usr/local/php53/bin/php_uploadscan.sh
exe:/usr/local/php53/sbin/php-fpm53
exe:/usr/local/php54/bin/php54
exe:/usr/local/php54/bin/php-cgi54
exe:/usr/local/php54/bin/php_uploadscan.sh
exe:/usr/local/php54/sbin/php-fpm54
exe:/usr/local/php55/bin/php55
exe:/usr/local/php55/bin/php-cgi55
exe:/usr/local/php55/bin/php_uploadscan.sh
exe:/usr/local/php55/sbin/php-fpm55
exe:/usr/local/php56/bin/php56
exe:/usr/local/php56/bin/php-cgi56
exe:/usr/local/php56/bin/php_uploadscan.sh
exe:/usr/local/php56/sbin/php-fpm56
exe:/usr/local/sbin/nginx
exe:/usr/sbin/exim
exe:/usr/sbin/hald
exe:/usr/sbin/httpd
exe:/usr/sbin/mysqld
exe:/usr/sbin/mysqld_safe
exe:/usr/sbin/named
exe:/usr/sbin/nginx
exe:/usr/sbin/ntpd
exe:/usr/sbin/proftpd
exe:/usr/sbin/pure-ftpd
exe:/usr/sbin/sshd

然后重启LFD:

/etc/init.d/lfd restart

来自:https://www.plugins-da.net/info/csf-lfd-exceptions-for-directadmin-csf.pignore
p.s. Based on this thread: http://forum.directadmin.com/showthread.php?t=49424

#!/usr/bin/env python
#-*- coding: utf-8 -*-
#=============================================================================
#     FileName:
#         Desc:
#       Author: 苦咖啡
#        Email: voilet@qq.com
#     HomePage: http://blog.kukafei520.net
#      Version: 0.0.1
#      History:
#=============================================================================

import os
import sys
import re
import smtplib

#设定邮件
fromaddr = "smtp.qq.com"
toaddrs = ["voilet@qq.com"]
username = "voilet"
password = "xxxxxx"

#设置白名单
pass_file = ["api_ucenter.php"]

#定义发送邮件函数
def sendmail(toaddrs,sub,content):
    '发送邮件模块'
    # Add the From: and To: headers at the start!
    msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n"
           % (fromaddr, ", ".join(toaddrs), sub))
    msg += content
    server = smtplib.SMTP('mail.funshion.com', 25,)
    server.login(username, password)
    server.sendmail(fromaddr, toaddrs, msg)
    server.quit()

#设置搜索特征码
rulelist = [
    '(\$_(GET|POST|REQUEST)\[.{0,15}\]\(\$_(GET|POST|REQUEST)\[.{0,15}\]\))',
    '(base64_decode\([\'"][\w\+/=]{200,}[\'"]\))',
    'eval\(base64_decode\(',
    '(eval\(\$_(POST|GET|REQUEST)\[.{0,15}\]\))',
    '(assert\(\$_(POST|GET|REQUEST)\[.{0,15}\]\))',
    '(\$[\w_]{0,15}\(\$_(POST|GET|REQUEST)\[.{0,15}\]\))',
    '(wscript\.shell)',
    '(gethostbyname\()',
    '(cmd\.exe)',
    '(shell\.application)',
    '(documents\s+and\s+settings)',
    '(system32)',
    '(serv-u)',
    '(提权)',
    '(phpspy)',
    '(后门)',
    '(webshell)',
    '(Program\s+Files)',
    'www.phpdp.com',
    'phpdp',
    'PHP神盾',
    'decryption',
    'Ca3tie1',
    'GIF89a',
    'IKFBILUvM0VCJD\/APDolOjtW0tgeKAwA',
    '\'e\'\.\'v\'\.\'a\'\.\'l\'',
]

def Scan(path):
    for root,dirs,files in os.walk(path):
        for filespath in files:
            isover = False
            if '.' in filespath:
                ext = filespath[(filespath.rindex('.')+1):]
                if ext=='php' and filespath not in pass_file:
                    file= open(os.path.join(root,filespath))
                    filestr = file.read()
                    file.close()
                    for rule in rulelist:
                        result = re.compile(rule).findall(filestr)
                        if result:
                            print '文件:'+os.path.join(root,filespath)
                            print '恶意代码:'+str(result[0])
                            print '\n\n'
                            sendmail(toaddrs,"增值发现恶意代码",'文件:'+os.path.join(root,filespath)+"\n" + '恶意代码:'+str(result[0]))
                            break

try:
    if os.path.lexists("/home/web_root/"):
        print('\n\n开始扫描:'+ "/home/web_root/")
        print('               可疑文件                 ')
        print('########################################')
        Scan("/home/web_root/")
        print('提示:扫描完成--~')
    else:
        print '提示:指定的扫描目录不存在--- '
except IndexError:
    print "请指定扫描文件目录"

来自:http://blog.kukafei520.net/html/2013/811.html

#查看所有80端口的连接数
netstat -nat|grep -i "80"|wc -l
#对连接的IP按连接数量进行排序
netstat -anp | grep 'tcp\|udp' | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n
netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n
netstat -ntu | awk '{print $5}' | egrep -o "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" | sort | uniq -c | sort -nr
#查看TCP连接状态
netstat -nat |awk '{print $6}'|sort|uniq -c|sort -rn
netstat -n | awk '/^tcp/ {print $NF}'|sort|uniq -c|sort -rn
netstat -n | awk '/^tcp/ {++S[$NF]};END {for(a in S) print a, S[a]}'
netstat -n | awk '/^tcp/ {++state[$NF]}; END {for(key in state) print key,"\t",state[key]}'
netstat -n | awk '/^tcp/ {++arr[$NF]};END {for(k in arr) print k,"\t",arr[k]}'
netstat -ant | awk '{print $NF}' | grep -v '[a-z]' | sort | uniq -c
#查看80端口连接数最多的20个IP
cat /www/web_logs/waitalone.cn_access.log|awk '{print $1}'|sort|uniq -c|sort -nr|head -100
tail -n 10000 /www/web_logs/waitalone.cn_access.log|awk '{print $1}'|sort|uniq -c|sort -nr|head -100
cat /www/web_logs/waitalone.cn_access.log|awk '{print $1}'|sort|uniq -c|sort -nr|head -100
netstat -anlp|grep 80|grep tcp|awk '{print $5}'|awk -F: '{print $1}'|sort|uniq -c|sort -nr|head -n20
netstat -ant |awk '/:80/{split($5,ip,":");++A[ip[1]]}END{for(i in A) print A,i}' |sort -rn|head -n20
#用tcpdump嗅探80端口的访问看看谁最高
tcpdump -i eth0 -tnn dst port 80 -c 1000 | awk -F"." '{print $1"."$2"."$3"."$4}' | sort | uniq -c | sort -nr |head -20
#查找较多time_wait连接
netstat -n|grep TIME_WAIT|awk '{print $5}'|sort|uniq -c|sort -rn|head -n20
#查找较多的SYN连接
netstat -an | grep SYN | awk '{print $5}' | awk -F: '{print $1}' | sort | uniq -c | sort -nr | more
#linux下实用iptables封ip段的一些常见命令:
#封单个IP的命令是:
iptables -I INPUT -s 211.1.0.0 -j DROP
#封IP段的命令是:
iptables -I INPUT -s 211.1.0.0/16 -j DROP
iptables -I INPUT -s 211.2.0.0/16 -j DROP
iptables -I INPUT -s 211.3.0.0/16 -j DROP
#封整个段的命令是:
iptables -I INPUT -s 211.0.0.0/8 -j DROP
#封几个段的命令是:
iptables -I INPUT -s 61.37.80.0/24 -j DROP
iptables -I INPUT -s 61.37.81.0/24 -j DROP
#想在服务器启动自运行的话有三个方法:
#1、把它加到/etc/rc.local中
#2、iptables-save >/etc/sysconfig/iptables可以把你当前的iptables规则放到/etc/sysconfig/iptables中,系统启动iptables时自动执行。
#3、service iptables save 也可以把你当前的iptables规则放/etc/sysconfig/iptables中,系统启动iptables时#自动执行。
#后两种更好此,一般iptables服务会在network服务之前启来,更安全。
#解封的话:
iptables -D INPUT -s IP地址 -j REJECT
iptables -F #全清掉了

应用环境可以是安全要求比较高的VPS或者独立服务器,一般允许内网IP登入,或者VPN进去。

vi /etc/hosts.allow
sshd:192.168.0.100:allow          //允许IP 192.168.0.100 登录
sshd:192.168.0.:allow            //允许IP 192.168.0.  网段登录 
sshd:all:deny                     //禁止其他的所有IP登录
或者
sshd:223.227.223.*:allow              //允许IP 223.227.223.*   网段登录
sshd:192.168.0.*:allow                //允许IP 192.168.0.*  网段登录 
sshd:all:deny                                //禁止其他的所有IP