怎么尽量消除Linux服务器系统安全风险,预防攻击

原文链接

一个系统有很多功能,易遭攻击点也很多。原则上讲单一功能的系统比多功能的系统更安全。减少可用攻击点,典型的包括卸载不必要的软件,不必要的登录用户名,关闭或移除不必要的服务。其他的还有给kernel打补丁,重编译kernel,关闭打开的网络接口,安装侵入侦察系统,防火墙,入侵预防系统。

第一步,通过服务器的想要功能来决定安装什么服务。例如,如果要搭建web服务器你应该安装Linux, Apache, MySQL, 和 Perl/ PHP/ Python (LAMP)服务,其他的东西都不要安装,因为安装额外的软件或运行额外的服务创造了不必要的易攻击点。

你需要决定你是否需要图形用户界面。Linux管理员可以通过命令行管理网络和服务,但是一些新手管理员倾向于用GUI,GUI占用了大量系统资源,运行不必要的服务。如果要用,在用完之后可以杀掉GUI进程。

一些通用安全优化步骤:

  • 数据加密通讯
  • 避免用不安全的协议发送明文信息或密码
  • 最小化服务器中不必要的软件
  • 关闭不需要的 SUID 和 SGID 的特殊权限
  • 保持系统为最新,尤其是安全补丁
  • 使用安全扩展
  • 考虑用SELinux
  • 提要用户密码复杂度
  • 定期更改密码,避免重复使用同一个密码
  • 当用户登录错误次数太多时,锁定用户
  • 不允许使用空密码
  • SSH
  • 关闭不必要的服务
  • 提高 /tmp /var/tmp /dev/shm 目录的安全性
  • 隐藏 BIND DNS 服务版本和 apache 版本
  • 提高 sysctl.conf 安全
  • 安装 Root Kit Hunter and ChrootKit Hunter
  • 最小化开放网络端口
  • 配置系统防火墙
  • 更安全合理的分区
  • 关闭不需要的文件权限
  • 维护系统日志,把日志镜像到分离的日志服务器
  • 安装Logwatch并每天查看Logwatch emails
  • 使用侵入侦察系统
  • 安装linux Socket 监控
  • 安装Mod_security
  • 限制用户权限
  • 备份
  • 服务器物理安全
  • 服务器物理安全
  • 配置 BIOS,关闭从CD/DVD和外部设备启动。启用 BIOS 密码和GRUB密码防治在物理上访问你的系统。

保持系统最新

# apt-get update
# apt-get upgrade

无人看管的升级

系统自动更新,你需要安装几个软件包,用root运行:

# apt-get install unattended-upgrades apt-listchanges

unattended-upgrades 软件的默认配置文件是 /etc/apt/apt.conf.d/50unattended-upgrades,默认配置可以很好的工作,但是你可以根据需要做些修改。

$ vi /etc/apt/apt.conf.d/50unattended-upgrades

设置哪些软件包需要升级:

Unattended-Upgrade::Origins-Pattern {
    // ...
};

取消注释下面这行:

Unattended-Upgrade::Mail "root";

为了激活unattended-upgrades,你需要确认/etc/apt/apt.conf.d/20auto-upgrades 包含如下行:

$ vi /etc/apt/apt.conf.d/20auto-upgrades

$ APT::Periodic::Update-Package-Lists "1";
$ APT::Periodic::Unattended-Upgrade "1";

/etc/apt/apt.conf.d/20auto-upgrades 文件可以手动创建或root执行如下命令:

# dpkg-reconfigure -plow unattended-upgrades

最小化服务器中不必要的软件

$ dpkg --list
$ dpkg --info packageName
$ apt-get remove packageName

su

确保只有在 sudo 组里的用户可以运行su

$ dpkg-statoverride --update --add root sudo 4750 /bin/su

关闭root用户

出于安全原因,可以在不需要root用户操作服务器时将其关闭

$ passwd -l root  //锁定

$ passwd -u root  //解锁

关闭 Shell 用户

查看激活的用户:

$ cat /etc/passwd | egrep -v '/false|/nologin|/shutdown|/halt' | cut -d':' -f 1,7

关闭用户命令:

$ usermod -s /usr/sbin/nologin "username"       //注意  没有引号

控制台(console)

在默认下,许多终端都是激活的,如下

$ vi /etc/securetty

注释掉不需要的终端

tty1
#tty2
#tty3
#tty4
#  ...

securetty文件

确保只有root用户可以修改 /etc/securetty 文件

$ chown root:root /etc/securetty
$ chmod 0600 /etc/securetty

共享内存(Shared memory)

共享内存可以用来攻击运行的服务 如apahce2

$ vi /etc/fstab

加入行如下

#secure shared memory
tmpfs     /run/shm    tmpfs	defaults,noexec,nosuid	0	0

重启生效

$ mount -a

提高IP安全

在 /etc/sysctl.conf 文件中加入

# Ignore ICMP broadcast requests
net.ipv4.icmp_echo_ignore_broadcasts = 1

# Disable source packet routing
net.ipv4.conf.all.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv6.conf.default.accept_source_route = 0

# Ignore send redirects
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0

# Block SYN attacks
net.ipv4.tcp_max_syn_backlog = 2048
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 5

# Log Martians
net.ipv4.conf.all.log_martians = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1

# Ignore ICMP redirects
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0

# Ignore Directed pings
net.ipv4.icmp_echo_ignore_all = 1

关闭 Open DNS Recursion 和版本信息

终端中执行:

$ vi /etc/bind/named.conf.options

在Options段中加入:

recursion no;
version "Not Disclosed";

重启 BIND DNS 服务

$ /etc/init.d/bind9 restart

关闭IPv6

如果你不需要IPv6,建议关闭

$ vi /etc/sysctl.conf

增加或修改以下行:

#disable ipv6
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1

重新加载配置

$ sysctl -p

关闭IPv6 Bind9 监听

$ vi /etc/default/bind9

增加或修改以下行:

# run resolvconf?
RESOLVCONF=yes
# startup options for the server
OPTIONS="-4 -u bind" -

关闭IRQ平衡(Balance)

irq balance用于优化中断分配,它会自动收集系统数据以分析使用模式,并依据系统负载状况将工作状态置于 Performance mode 或 Power-save mode。处于Performance mode 时,irqbalance 会将中断尽可能均匀地分发给各个 CPU core,以充分利用 CPU 多核,提升性能。

$ vi /etc/default/irqbalance

把ENABLED改为0

ENABLED=0

TCP Wrapper

TCP Wrapper是基于规则的访问列表,包含以下2个文件

  • /etc/hosts.allow
  • /etc/hosts.deny

两个文件的语法相似定义如下

daemon : client [:option1:option2:...]

例如,如果你想允许指定IP(或IP范围)而拒绝其他IP通过SSH访问

在 /etc/hosts.allow 文件中加入

shd : 111.111, 222.222.222.222

在/etc/hosts.deny 文件中加入

sshd : ALL

注意

  • 每个服务在hosts.allow和hosts.deny只能有一个规则
  • 在hosts.allow和hosts.deny的设置立即生效
  • 在两个文件中的最后一行必须以新的一行结束

/tmp 和 /var/tmp临时存储目录

临时存储目录/tmp, /var/tmp 和 /dev/shm 给攻击者提供了存储空间。

/tmp

给/tmp分区提供一个1G的文件系统

$ dd if=/dev/zero of=/usr/tmpDSK bs=1024 count=1024000

创建一个当前/tmp的备份

$ cp -Rpfv /tmp /tmpbackup

挂载/tmp分区并设置正确的访问权限

$ mount -t tmpfs -o loop,noexec,nosuid,rw /usr/tmpDSK /tmp
$ chmod 1777 /tmp

恢复备份文件 并 删除备份文件:

$ cp -Rpf /tmpbackup/* /tmp/
$ rm -rf /tmpbackup/*

在fbtab文件中设置/tmp

$ /usr/tmpDSK /tmp tmpfs loop,nosuid,noexec,rw 0 0

检测fbtab

$ mount -o remount /tmp

如果你想在/tmp中执行脚本或可执行文件,你会得到一个permission denied

/var/tmp

$ mv /var/tmp /var/tmpold
$ ln -s /tmp /var/tmp
$ cp -prfv /var/tmpold/* /tmp/

关闭autofs

阻止自动挂载可移动媒体和NFS文件系统,你可以写一条udev规则关闭autofs,首先创建/etc/udev/rules.d/85-no-automount.rules文件

$ vi /etc/udev/rules.d/85-no-automount.rules

写入

SUBSYSTEM=="usb", ENV{UDISKS_AUTO}="0"

重启服务

$ service udev restart

设置security limits

设置进程限制防止fork炸弹攻击

$ vi /etc/security/limits.conf

例子:

cyberpunk hard nproc 100
@cybergroup hard nproc 20

关闭不需要的服务

Linux系统安装了很多服务,服务过多将导致资源耗尽。为了提高性能和安全,关闭无用服务。

查看正在运行的服务

$ initctl list | grep running

你可以移除启动脚本来关闭服务,或者彻底移除它。大部分的服务都可以用下面的命令来关闭。

$ echo "manual" > /etc/init/service.override
$ update-rc.d -f service_name remove

卸载命令

$ apt-get purge service_name

关闭anacron

anacron子系统设计用来为系统提供cron自动任务功能,这是非常有用的功能,但是如果你没打算用,你可以关闭此服务。

如果你想关闭anacron服务,简单的注释掉 /etc/crontab 文件的以下行

#  25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
#  47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
#  52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )

锁定Cronjobs

Cron有一个内建功能,可以允许谁可以执行任务,谁不可以。这个功能由两个文件控制/etc/cron.allow 和 /etc/cron.deny。为了禁止一个用户使用cron,在cron.deny加入此用户名。如果想禁止所有用户运行cron,在cron.deny文件中加入‘ALL’

$ echo ALL >>/etc/cron.deny

关闭Apport

Apport是内部错误报告程序,它收集系统崩溃信息。关闭方法如下:

$ vi /etc/default/apport

把enabled改为0

# set this to 0 to disable apport, or to 1 to enable it
# you can temporarily override this with
# sudo service apport start force_start=1
enabled=0

移除Apport

$ apt-get purge apport

关闭atd

at命令用来定时执行命令,但是不同于cron,at任务只执行一次。如果你用cron,你也许不需要这个服务。

$ echo 'manual' > /etc/init/atd.override

移除at

$ apt-get purge at

关闭Avahi

Avahi 是 zeroconf 协议的实现。它可以在没有 DNS 服务的局域网里发现基于 zeroconf 协议的设备和服务。它跟mDNS 一样。

$ cd /etc/init
$ touch avahi-daemon.override
$ echo "manual" > avahi-daemon.override

移除Avahi

$ apt-get remove avahi-daemon avahi-utils

关闭蓝牙(Bluetooth)

  • 第一种关闭方法

      $ vi /etc/rc.local
    

    在exit 0之前加入

      $ rfkill block bluetooth
    
  • 第二种关闭方法

      $ vi /etc/bluetooth/main.conf
    

    设置InitiallyPowered为false

      InitiallyPowered = false
    

禁用Ctrl+Alt+Delete

你不想以外重启服务器,编辑control-alt-delete.conf关闭

$ vi /etc/init/control-alt-delete.conf

删除或注释掉下面一行

#exec shutdown -r now "Control-Alt-Delete pressed"

关闭Cups

CUPS给Unix/Linux用户提供了一种可靠有效的方法来管理打印。它支持IPP,并提供了LPD,SMB(服务消息块,如配置为微软WINDOWS的打印机)、JetDirect等接口。CUPS还可以浏览网络打印机。

$ echo "manual" > /etc/init/cups.override

卸载Cups

$ capt-get remove cups

关闭Dovecot

Dovecot 是一个开源的 IMAP 和 POP3 邮件服务器,支持 Linux/Unix 系统。 POP / IMAP 是 MUA 从邮件服务器中读取邮件时使用的协议。

$ apt-get purge dovecot-*

关闭NFS

NFS是Unix/Linux/BSD操作系统的网络文件分享程序。无用的服务

NFS服务包含如下几个包:

  • nfs-kernel-server

  • nfs-common

  • portmap

  • rpcbind

  • autofs

      $ apt-get purge nfs-kernel-server nfs-common portmap rpcbind autofs
    

关闭SNMP服务

简单网络管理协议(SNMP),由一组网络管理的标准组成,包含一个应用层协议(application layer protocol)、数据库模型(database schema)和一组资源对象。该协议能够支持网络管理系统。如果你不需要这个服务,你可以移除它:

$ apt-get purge --auto-remove snmp

关闭Telnet

Telnet默认没有安装,最好不要安装。

$ apt-get purge telnetd inetutils-telnetd telnetd-ssl

关闭Whoopsie

Whoopsie这个服务使用来发送崩溃log到ubuntu。为了关闭它,编辑文件:

$  vi /etc/default/whoopsie

把report_crashes参数改为false

report_crashes=false

卸载Whoopsie

$ apt-get purge whoopsie

关闭Wireless

现在主流的主板都集成了Wireless适配器,在服务器环境中是没有用的。

$ vi /etc/network/interfaces

加入下面一行

iface wlan0 inet manual

$ service network-manager restart

关闭 Zeitgeist

Zeitgeist 是 Ubuntu 上用来记录用户行为和事件的服务,包括文件打开、网站访问、对话等等,其他应用程序可访问这些记录下来的信息。

$ apt-get purge zeitgeist-core zeitgeist-datahub python-zeitgeist rhythmbox-plugin-zeitgeist zeitgeist

禁用编译器

编译器可以被攻击者用来编译攻击你服务器的恶意软件。生产环境通常不需要它。

chmod 000 /usr/bin/byacc
chmod 000 /usr/bin/yacc
chmod 000 /usr/bin/bcc
chmod 000 /usr/bin/kgcc
chmod 000 /usr/bin/cc
chmod 000 /usr/bin/gcc
chmod 000 /usr/bin/*c++
chmod 000 /usr/bin/*g++

如果你需要使用编译器,执行:

chmod 755 /usr/bin/byacc
chmod 755 /usr/bin/yacc
chmod 755 /usr/bin/bcc
chmod 755 /usr/bin/kgcc
chmod 755 /usr/bin/cc
chmod 755 /usr/bin/gcc
chmod 755 /usr/bin/*c++
chmod 755 /usr/bin/*g++

实现IP检测

如果有人hack进入到你的账户,确保你可以得到通知信息,并得到黑客的地址。

为了实现这个,简单的编辑.bash_profile 或 .profile:

$ vi .bash_profile

加入以下文本:

$ echo 'ALERT - ACCESS GRANTED on:' `date` `who` | mail -s "ALERT - ACCESS GRANTED from `who | awk '{print $6}'`" admin@domain.com

安装Fail2Ban

带有最基本的SSH配置是不安全的。Fail2Ban提供了一个方法自动检测和保护服务器被攻击者攻击。这个程序通过扫描log文件并对不信任的行为作出反应,想登录尝试失败。

安装Fail2Ban

$ apt-get install fail2ban

创建config配置文件

Fail2Ban运行需要正确的配置文件,默认配置文件在/etc/fail2ban/jail.conf,但是这个文件并不是你需要的。你应该自己创建 .local文件。

$ cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

$ vi /etc/fail2ban/jail.local

Fail2Ban SSH 配置

[ssh]

enabled  = true
port     = your port number or ssh
filter   = sshd
logpath  = /var/log/auth.log
maxretry = 2

[ssh-ddos]

enabled  = true
port     = your port number or ssh
filter   = sshd-ddos
logpath  = /var/log/auth.log
maxretry = 2

邮件通知

destemail = admin@domain.com
action = %(action_mwl)s

重启Fail2Ban

$ service fail2ban restart

检查状态

$ fail2ban-client status

检查iptables规则

$ iptables -L

安装PSAD

端口扫描攻击检测(psad)是一个很好的可以检测很多扫描攻击的软件。它分析iptables log信息检测端口扫描和其他可疑流量。

安装PSAD

$ apt-get install psad

编辑配置文件

$ vi /etc/psad/psad.conf

在你做任何改变之前,确保HOSTNAME参数设置正确。然后更新下面参数:

  • EMAIL_ADDRESSES: 你的email地址
  • HOSTNAME: 你的hostname
  • ENABLE_AUTO_IDS:改成Y,如果你想让PSAD自己做决定
  • ENABLE_AUTO_IDS_EMAILS:Y,接收邮件

加入iptables规则

iptables -A INPUT -j LOG
iptables -A FORWARD -j LOG

重启psad

$ psad -R
$ psad --sig-update
$ psad -H

查看psad状态

$ psad --Status

Postfix

确保Postfix以非root用户运行

$ ps aux | grep postfix | grep -v '^root'

改变权限和所有者

$ chmod 755 /etc/postfix
$ chmod 644 /etc/postfix/*.cf
$ chmod 755 /etc/postfix/postfix-script*
$ chmod 755 /var/spool/postfix
$ chown root:root /var/log/mail*
$ chmod 600 /var/log/mail*

配置更新

$ vi /etc/postfix/main.cf

修改myhostname

myhostname = server.domain.com

配置Postfix接口监听地址

mydestination = $myhostname, localhost.$mydomain, localhost
inet_interfaces = localhost

配置网络

mynetworks = 10.0.0.0/16, 192.168.1.0/24, 127.0.0.1

配合SMTP服务

mydomain = domain.com

myorigin = domain.com

relay_domains = domain.com

smtpd_banner = $myhostname

限制拒绝服务攻击 Limit Denial of Service Attacks:

default_process_limit = 100
smtpd_client_connection_count_limit = 10
smtpd_client_connection_rate_limit = 30
queue_minfree = 20971520
header_size_limit = 51200
message_size_limit = 10485760
smtpd_recipient_limit = 100

关闭 SMTP VRFY 命令

disable_vrfy_command = yes

smtpd_delay_reject = yes
smtpd_helo_required = yes
smtpd_helo_restrictions = permit_mynetworks, reject_non_fqdn_hostname
smtpd_helo_restrictions = reject_invalid_hostname

限制 Postfix SMTP 服务申请 RCPT TO 命令

smtpd_recipient_restrictions =
reject_invalid_hostname, 		// Reject email if it not valid hostname
reject_non_fqdn_hostname, 		// Reject email if it not valid FQDN
reject_non_fqdn_sender, 		// Reject the request when the MAIL FROM address is not in fully-qualified domain form. For example email send from xyz or abc is rejected.
reject_non_fqdn_recipient, 		// Reject the request when the RCPT TO address is not in fully-qualified domain form
reject_unknown_sender_domain,		// Reject email, if sender domain does not exists
reject_unknown_recipient_domain,	// Reject email, if recipient domain does not exists
permit_mynetworks,
reject_rbl_client list.dsbl.org, 	// Configure spam black lists
reject_rbl_client sbl.spamhaus.org,
reject_rbl_client cbl.abuseat.org,
reject_rbl_client dul.dnsbl.sorbs.net,
permit

设置错误睡眠时间,软硬错误限制

smtpd_error_sleep_time = 1s
smtpd_soft_error_limit = 10
smtpd_hard_error_limit = 20

Forward emails

$ vi /etc/postfix/virtual

一行中两个email地址

email1@domain.com	email2@domain.com

email1@domain.com的所有邮件转到email2@domain.com

重启Postfix

$ service postfix restart

Apache

用户和组

$ groupadd webuser
$ useradd -d /var/www/ -g webuser -s /bin/nologin webuser

编辑 etc/apache2/envvars

$ vi etc/apache2/envvars

User webuser
Group webuser

限制本地访问

$ chown -R 750 /etc/apache2/bin /etc/apache2/conf
$ chmod 511 /usr/sbin/apache2
$ chmod 750 /var/log/apache2/
$ chmod 750 /etc/apache2/conf/
$ chmod 640 /etc/apache2/conf/*
$ chgrp -R <MyApacheUser> /etc/apache2/conf

限制目录访问

$ vi /etc/apache2/apache2.conf

增加

<Directory />
Options None
Order deny,allow
Deny from all
</Directory>

重启apache

$ /etc/init.d/apache2 restart

关闭目录清单

<Directory /var/www/html>
    Options -Indexes
</Directory>

XSS 保护

$ vi /etc/apache2/apache2.conf

<IfModule mod_headers.c>
Header set X-XSS-Protection "1; mode=block"
</IfModule>

重启Apache

$ /etc/init.d/apache2 restart

点击劫持攻击

点击劫持是一种视觉上的欺骗手段。攻击者使用一个透明的、不可见的iframe,覆盖在一个网页上,然后诱使用户在该网页上进行操作,此时用户将在不知情 的情况下点击透明的iframe页面。通过调整iframe页面的位置,可以诱使用户恰好点击在iframe页面的一些功能性按钮上。

$ vi /etc/apache2/apache2.conf

<IfModule mod_headers.c>
Header always append X-Frame-Options SAMEORIGIN
</IfModule>

关闭 Etag

Etag 允许远程攻击者获取敏感信息

FileETag None

关闭老协议

RewriteEngine On
RewriteCond %{THE_REQUEST} !HTTP/1.1$
RewriteRule .* - [F]

关闭SSI

SSI是英文Server Side Includes的缩写,翻译成中文就是服务器端包含的意思。从技术角度上说,SSI就是在HTML文件中,可以通过注释行调用的命令或指针。SSI允许攻击者远程注入恶意脚本。

<Directory /path/to/htdocs>
Options -Indexes -Includes
Order allow,deny
Allow from all
</Directory>

关闭CGI

<Directory /path/to/htdocs>
Options -Indexes -Includes -ExecCGI
Order allow,deny
Allow from all
</Directory>

关闭追踪HTTP请求

$ vi /etc/apache2/apache2.conf

TraceEnable off

关闭不需要的模块

列出所有打开的模块命令

$ apache2 -l

关闭模块可以用 a2dismod 命令,打开用a2enmod命令

a2dismod <module>

关闭apache的符号链接

<Directory /path/to/www>
Options -FollowSymLinks
</Directory>l;

如果你想在特定的网站打开符号链接,在网站的.htaccess写入:

<Directory /path/to/some_www>
Options +FollowSymLinks
</Directory>l;

限制http请求大小

apache没有限制http请求大小,这就是说,无限大的数据可以发送给apache服务器。hacker可以用这个实现拒绝服务攻击。

<Directory "/path/to/www/">
LimitRequestBody 512000
</Directory>

配置超时时间(Timeout)

默认300秒,可以适当减少

Timeout 45

隐藏Apache信息

$ vi /etc/apache2/apache2.conf

ServerTokens Prod
ServerSignature Off
<IfModule mod_headers.c>
Header unset Server
Header unset X-Powered-By
</IfModule>

重启apache

$ /etc/init.d/apache2 restart

HTTP请求方法

$ vi /etc/apache2/apache2.conf

<LimitExcept GET POST HEAD>
deny from all
</LimitExcept>

例如:

<Location />
Order allow,deny
Allow from all
<LimitExcept HEAD POST GET>
Deny from all
</LimitExcept>
</Location>

重启;

HTTPOnly Cookie

$ vi /etc/apache2/apache2.conf

<IfModule mod_headers.c>
Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure
</IfModule>

重启;

屏蔽IP地址

<Limit GET POST PUT>
Order Allow,Deny
Allow from all
Deny from 1.1.1.1
</Limit>

ModSecurity

ModSecurity是一个开源的网络应用防火墙。它可以嵌入到web服务或做为独立的网络应用工作,检测并阻止攻击者攻击web服务。

在安装 ModSecurity 之前,先要安装依赖:

32位:

$ apt-get install libxml2 libxml2-dev libxml2-utils
$ apt-get install libaprutil1 libaprutil1-dev

64位:

$ ln -s /usr/lib/x86_64-linux-gnu/libxml2.so.2 /usr/lib/libxml2.so.2
$ apt-get install libapache-mod-security

配置 ModSecurity 规则

激活默认规则:

$ mv /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf

你可以根据需要配置规则,ModSecurity的规则目录在/etc/modsecurity/。

$ vi /etc/modsecurity/modsecurity.conf

SecRuleEngine On
SecRequestBodyAccess On
SecRequestBodyLimit 131072
SecRequestBodyNoFilesLimit 131072
SecRequestBodyInMemoryLimit 131072
SecRequestBodyLimitAction ProcessPartial

SecResponseBodyAccess Off

下载安装 OWASP Core Rule Set

$ cd /tmp
$ wget -O SpiderLabs-owasp-modsecurity-crs.tar.gz https://github.com/SpiderLabs/owasp-modsecurity-crs/tarball/master
$ tar -zxvf SpiderLabs-owasp-modsecurity-crs.tar.gz
$ cp -R SpiderLabs-owasp-modsecurity-crs-*/* /etc/modsecurity/
$ rm SpiderLabs-owasp-modsecurity-crs.tar.gz
$ rm -R SpiderLabs-owasp-modsecurity-crs-*
$ mv /etc/modsecurity/modsecurity_crs_10_setup.conf.example /etc/modsecurity/modsecurity_crs_10_setup.conf

$ cd /etc/modsecurity/base_rules
$ for f in * ; do ln -s /etc/modsecurity/base_rules/$f /etc/modsecurity/activated_rules/$f ; done
$ cd /etc/modsecurity/optional_rules
$ for f in * ; do ln -s /etc/modsecurity/optional_rules/$f /etc/modsecurity/activated_rules/$f ; done

$ vi /etc/apache2/mods-available/mod-security.conf

Include "/etc/modsecurity/activated_rules/*.conf"

检查 ModSecurity 是否开启并重启apache

a2enmod headers
a2enmod mod-security

$ /etc/init.d/apache2 restart

安装ModEvasive

$ apt-get install libapache2-mod-evasive

为 mod_evasive 创建log目录

$ mkdir /var/log/mod_evasive

改目录权限

$ chown www-data:www-data /var/log/mod_evasive/   //  www or user

配置ModEvasive

$ vi /etc/apache2/mods-available/mod-evasive.conf

<ifmodule mod_evasive20.c>
DOSHashTableSize 3097
DOSPageCount  2
DOSSiteCount  50
DOSPageInterval 1
DOSSiteInterval  1
DOSBlockingPeriod  10
DOSLogDir   /var/log/mod_evasive
DOSEmailNotify  email@domain.com
DOSWhitelist   127.0.0.1
</ifmodule>

修复Mod-Evasive 邮件bug

$ ln -s /etc/alternatives/mail /bin/mail/

检查ModEvasive状态

a2enmod mod-evasive

重启apache

$ /etc/init.d/apache2 restart

Ubuntu 防火墙

安装UFW:

$ apt-get install ufw

允许SSH和HTTP服务

$ ufw allow ssh
$ ufw allow http
$ ufw deny 23
$ ufw default deny

打开防火墙

$ ufw enable

查看防火墙状态

$ ufw status verbose

查看iptable设置

$ iptables -L

配置UFW:

$ vi /etc/ufw/before.rules

在 *filter 下加入

:ufw-http - [0:0]
:ufw-http-logdrop - [0:0]

在COMMIT之前加入

### Start HTTP ###

# Enter rule
-A ufw-before-input -p tcp --dport 80 -j ufw-http
-A ufw-before-input -p tcp --dport 443 -j ufw-http

# Limit connections per Class C
-A ufw-http -p tcp --syn -m connlimit --connlimit-above 50 --connlimit-mask 24 -j ufw-http-logdrop

# Limit connections per IP
-A ufw-http -m state --state NEW -m recent --name conn_per_ip --set
-A ufw-http -m state --state NEW -m recent --name conn_per_ip --update --seconds 10 --hitcount 20 -j ufw-http-logdrop

# Limit packets per IP
-A ufw-http -m recent --name pack_per_ip --set
-A ufw-http -m recent --name pack_per_ip --update --seconds 1 --hitcount 20 -j ufw-http-logdrop

# Finally accept
-A ufw-http -j ACCEPT

# Log
-A ufw-http-logdrop -m limit --limit 3/min --limit-burst 10 -j LOG --log-prefix "[UFW HTTP DROP] "
-A ufw-http-logdrop -j DROP

### End HTTP ###

防止Ping Flood 攻击,在COMMIT之前加入

-A INPUT -p icmp -m limit --limit 6/s --limit-burst 1 -j ACCEPT
-A INPUT -p icmp -j DROP

关闭IPv6

$ vi /etc/default/ufw

IPV6=no

重新加载ufw配置

$ ufw reload

IP Spoofing

IP Spoofing技术是指一种获取对计算机未经许可的访问的技术,即攻击者通过伪 IP 地址向计算机发送信息,并显示该信息来自于真实主机。

为防止IP Spoofing,编辑

$ vi /etc/host.conf

增加

order bind,hosts
nospoof on

PHP

$ vi /etc/php5/apache2/php.ini

安全模式

safe_mode = On
safe_mode_gid = On
sql.safe_mode=On

如果你想限制可执行文件的目录,加入

safe_mode_include_dir = /path/to/dir
safe_mode_exec_dir = /path/to/exec/dir

关闭Globals

register_globals = Off

隐藏PHP信息

expose_php = Off
track_errors = Off
html_errors = Off

隐藏PHP的所有错误信息

display_errors = Off

关闭Functionalities:

disable_functions = php_uname, getmyuid, getmypid, passthru, leak, listen, diskfreespace, tmpfile, link, ignore_user_abord, shell_exec, dl, set_time_limit, exec, system, highlight_file, source, show_source, fpaththru, virtual, posix_ctermid, posix_getcwd, posix_getegid, posix_geteuid, posix_getgid, posix_getgrgid, posix_getgrnam, posix_getgroups, posix_getlogin, posix_getpgid, posix_getpgrp, posix_getpid, posix, _getppid, posix_getpwnam, posix_getpwuid, posix_getrlimit, posix_getsid, posix_getuid, posix_isatty, posix_kill, posix_mkfifo, posix_setegid, posix_seteuid, posix_setgid, posix_setpgid, posix_setsid, posix_setuid, posix_times, posix_ttyname, posix_uname, proc_open, proc_close, proc_get_status, proc_nice, proc_terminate, phpinfo

关闭远程文件包含

allow_url_fopen = Off
allow_url_include = Off

限制文件上传

file_uploads = Off

如果你需要这个上传功能,你应该限制文件大小和上传目录

upload_tmp_dir = /var/php_tmp
upload_max_filezize = 2M

资源控制

max_execution_time =  10
max_input_time = 30
memory_limit = 40M

控制POST大小

post_max_size=1K

保护Sessions

session.cookie_httponly = 1

session.referer_check = domain.com

magic_quotes_gpc

magic_quotes_gpc=Off

重启apache

Suhosin

Suhosin是php的保护系统。

安装suhosin

$ apt-get install php5-suhosin

配置suhosin

$ vi /etc/php5/conf.d/suhosin.ini

打开suhosin

extension=suhosin.so

关闭session加密

suhosin.session.encrypt = Off

日志所有错误

suhosin.log.syslog=511

最大traversal,设置最深路径

suhosin.executor.include.max_traversal=4

关闭eval

suhosin.executor.disable_eval=On

关闭 /e modifier

suhosin.executor.disable_emodifier=On

suhosin.mail.protect=2

sql错误静音

suhosin.sql.bailout_on_error=On

过滤选项

suhosin.cookie.max_vars = 2048
suhosin.get.max_array_index_length = 256
suhosin.post.max_array_index_length = 256
suhosin.post.max_totalname_length = 8192
suhosin.post.max_vars = 2048
suhosin.request.max_totalname_length = 8192
suhosin.request.max_varname_length = 256

iptables

限制SSH的接入连接

下面这个例子忽略22端口在60秒内尝试超过5次连接

iptables -I INPUT -p tcp --dport 22 -i eth0 -m state --state NEW -m recent --set
iptables -I INPUT -p tcp --dport 22 -i eth0 -m state --state NEW -m recent --update --seconds 60 --hitcount 5 -j DROP

使用端口碰撞

iptables -N stage1
iptables -A stage1 -m recent --remove --name knock
iptables -A stage1 -p tcp --dport 3456 -m recent --set --name knock2
iptables
iptables -N stage2
iptables -A stage2 -m recent --remove --name knock2
iptables -A stage2 -p tcp --dport 2345 -m recent --set --name heaven
iptables
iptables -N door
iptables -A door -m recent --rcheck --seconds 5 --name knock2 -j stage2
iptables -A door -m recent --rcheck --seconds 5 --name knock -j stage1
iptables -A door -p tcp --dport 1234 -m recent --set --name knock
iptables
iptables -A INPUT -m --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -m recent --rcheck --seconds 5 --name heaven -j ACCEPT
iptables -A INPUT -p tcp --syn -j doo

阻止端口扫描

试图进行端口扫描的锁定一天

iptables -A INPUT   -m recent --name portscan --rcheck --seconds 86400 -j DROP
iptables -A FORWARD -m recent --name portscan --rcheck --seconds 86400 -j DROP

iptables -A INPUT   -m recent --name portscan --remove
iptables -A FORWARD -m recent --name portscan --remove

把扫描者加入扫描列表并log

iptables -A INPUT   -p tcp -m tcp --dport 139 -m recent --name portscan --set -j LOG --log-prefix "Portscan:"
iptables -A INPUT   -p tcp -m tcp --dport 139 -m recent --name portscan --set -j DROP

iptables -A FORWARD -p tcp -m tcp --dport 139 -m recent --name portscan --set -j LOG --log-prefix "Portscan:"
iptables -A FORWARD -p tcp -m tcp --dport 139 -m recent --name portscan --set -j DROP

强制SYN包检查

iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP

drop空包

iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP

drop ping

iptables -A OUTPUT -p icmp -o eth0 -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-reply -s 0/0 -i eth0 -j ACCEPT
iptables -A INPUT -p icmp --icmp-type destination-unreachable -s 0/0 -i eth0 -j ACCEPT
iptables -A INPUT -p icmp --icmp-type time-exceeded -s 0/0 -i eth0 -j ACCEPT
iptables -A INPUT -p icmp -i eth0 -j DROP

屏蔽IP

iptables -A INPUT -s 1.1.1.1 -j DROP
iptables -A INPUT -s 192.168.0.0/24 -j DROP

备份规则

iptables-save > /root/my.active.firewall.rules

修复规则

iptables-restore < /root/my.active.firewall.rules

获取(D)D0S更多信息

netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n

加固SSH

SSH加固是服务器安全重要一步,所有配置都在 /etc/ssh/sshd_config

$ vi /etc/ssh/sshd_config

限制用户访问

AllowUsers user1 user2   //允许

DenyUser user3 user_4    //拒绝

关闭root登录

PermitRootLogin no

在系统中所有空密码的用户禁止登录

PermitEmptyPasswords no

不允许用户设置环境变量

PermitUserEnvironment no

隐藏最后一次登录

PrintLastLog no

指定Ip可以用SSH访问

ListenAddress 1.1.1.1

只用协议2

Protocol 2

更改默认端口

Port 2345

关闭UseDNS

UseDNS no

设置空闲超时时间

ClientAliveInterval 300
ClientAliveCountMax 0

关闭 .rhosts 文件

IgnoreRhosts yes
RhostsAuthentication no
RhostsRSAAuthentication no
RSAAuthentication yes

关闭Host-Based Authentication

HostbasedAuthentication no

LoginGraceTime

LoginGraceTime 300

MaxStartups,防止暴力脚本攻击

MaxStartups 2

关闭Forwarding

AllowTcpForwarding no
X11Forwarding no

严厉模式

StrictModes yes

使用TCP Wrappers

sshd : 192.168.1.2 1.1.1.1

查看logs:一些重要的日志信息

  • /var/log/messages 系统主日志
  • /var/log/auth.log 验证日志
  • /var/log/kern.log 内核日志
  • /var/log/cron.log 计划任务日志
  • /var/log/maillog 邮件服务日志
  • /var/log/boot.log 系统启动日志
  • /var/log/mysqld.log mysql数据库服务日志
  • /var/log/secure 验证日志
  • /var/log/ufw.log 防火墙日志
  • /var/log/utmp 或 /var/log/wtmp 登录记录文件

用 LogWatch 分析日志

$ apt-get install logwatch libdate-manip-perl

查看报告

$ logwatch | less