Write in front: When you deploy a server, the first step should not be to deploy the application, security is the first task
If one day when you log on to the server discover /bin/bash–i, python-c ' Import pty; Pty.spawn ("/bin/sh") command appears on the server, so congratulations, the server is compromised.
But intruders are very smart, first execute the following command
unset history histfile Histsave histzone history histlog; Export Histfile=/dev/null; Export histsize=0; Export histfilesize=0
And then access it through a springboard.
Ssh-o userknownhostsfile=/dev/null-t [email protected]/bin/bash–i
Establish Ttyshell
Python-c ' Import pty; Pty.spawn ("/bin/sh") '
Then clear the Access record
Shred-n 31337-z-U file_to_delete
Wait a minute... A series of operations
Then you can see that the server will leave the above clues, then how can we prevent it?
1, System User optimization
The user is the first level of security hardening in Linux, if there is a security risk in the system itself, then the security policy can not play a reinforcing effect
cat/etc/passwd | Awk-f: ' $3==0 ' //List of users with super privileges CAT/ETC/PASSWD | grep '/bin/bash ' //List of users with login shell
If there are other super users besides Root, then be very careful.
1.1 Remove the user and user groups from the system
Delete the user, such as Adm,lp,sync,shutdown,halt,news,uucp,operator,games,gopher
Delete a group, such as Adm,lp,news,uucp,games,dip,pppusers,popusers,slipusers
1.2 or lock users who do not need to sign in
such as: XFS,NEWS,NSCD,DBUS,VCSA,GAMES,NOBODY,AVAHI,HALDAEMON,GOPHER,FTP,MAILNULL,PCAP,MAIL,SHUTDOWN,HALT,UUCP, Operator,sync,adm,lp,bin,sys,nuucp,hpdb,www,daemon
1.3 Restrict users who can be su to root
#在/etc/pam.d/su head add: Auth required/lib/security/pam_wheel.so group=wheel
This way, only users of the wheel group can su to root
1.4 Check Shadow Hollow password account
Awk-f: ' ($2== "") {print} '/etc/shadow
Lock an empty password account, or ask for an additional password
1.5 System critical Directory permission control
Depending on your security needs, configure some critical directories with the minimum permissions required, password files, shadow files, and group file permissions.
/ETC/PASSWD All users can read, root user can write –rw-r-r-
chmod 644/etc/passwd
/etc/shadow only Root readable –r--–
chmod 600/etc/shadow
/etc/group must be readable by all users and the root user can write –rw-r-r-
chmod 644/etc/group
2. System service Optimization
In general, the system may automatically run some unnecessary services, we can use the following command to view the current default open System services:
Chkconfig--list | grep "3:on"
If we only provide Web services, then for SendMail, NFS, Postfix, FTP and other services that are not needed can be closed
For the key services, we need to ensure that they operate, such as: Iptables, sshd, Syslog, httpd, Nginx, MySQL, php-fpm and so on.
3. SSH Access Policy
SSH access is a means of almost the only control system in our daily work. So the security of SSH is very important, generally high SSH security policy adhering to the following several principles.
Disable root user ssh login.
Disables the way the password is validated.
Only one user is allowed to have sudo full permissions.
The private key file is not allowed in the system unless it is a bastion machine.
Use a random port instead of Port 22.
To edit the/etc/sudoers, add an article:
Test all= (All) Nopasswd:all
The example here shows that the test gives full sudo permission and does not require a password to be validated when Sudo is raised .
Sed-i ' s/\ (passwordauthentication\) yes/\1 no/'/etc/ssh/sshd_config //Forbidden Password, using certificate sed-i ' s/\ (permitrootlogin\) Yes /\1 no/'/etc/ssh/sshd_config//disable root user ssh login
Now let's look at the effect of SSH access:
All users cannot use password authentication to sign in.
The root user is not allowed to log in directly, even with the root password, the only way to get root is to use the test user to raise the power.
The test user can only log on with a certificate.
SSH no longer uses the default 22 port
4, the system internal Security Configuration 4.1, the protection boot process
User-initiated need to enter the host password echo "Sp:s:respawn:/sbin/sulogin" >>/etc/inittab//edit/etc/init/control-alt-delete.conf, Disable Ctrlaltdel start on Control-alt-delete change to #start on Control-alt-delete
4.2. Kernel modification
/etc/sysctl.conf change to the following content
kernel.shmall = 268435456net.ipv4.tcp_syncookies = 1net.ipv4.tcp_tw_reuse = 1net.ipv4.tcp_tw_recycle = 1net.ipv4.tcp_fin_timeout = 30net.ipv4.tcp_keepalive_time = 1200net.ipv4.ip_local_port_ Range = 1024x768 65000net.ipv4.tcp_max_tw_buckets = 5000net.ipv4.tcp_max_tw_buckets = 5000net.ipv4.tcp_fin_timeout = 30net.ipv4.tcp_keepalive_time = 300net.ipv4.tcp_tw_reuse = 1net.ipv4.tcp_tw_recycle = 1net.ipv4.ip_local_port_range = 65000net.ipv4.tcp_mem = 786432 1048576 1572864net.core.wmem_max = 873200net.core.rmem_max = 873200net.ipv4.tcp_ Wmem = 8192 436600 873200net.ipv4.tcp_rmem = 32768 436600 873200net.core.somaxconn = 256net.core.netdev_max_backlog = 1000 Net.ipv4.tcp_max_syn_backlog = 2048net.ipv4.tcp_retries2 = 5net.ipv4.tcp_keepalive_time = 500net.ipv4.tcp_keepalive_ INTVL = 30net.ipv4.tcp_keepalive_probes = 3net.ipv4.conf.lo.arp_ignore = 0net.ipv4.conf.lo.arp_announce = 0net.ipv4.conf.all.arp_ignore = 0net.ipv4.conf.all.arp_announce = 0
/etc/security/limits.conf change to the following content
* Soft nofile 655360* hard Nofile 655360
Explain
Net.ipv4.tcp_syncookies = # means to open syn Cookies. When a SYN wait queue overflow occurs, cookies are enabled to protect against a small number of SYN attacks, the default is 0, which means close; Net.ipv4.tcp_tw_reuse = # means turn on reuse. Allows the time-wait sockets to be reused for new TCP connections, which defaults to 0, which means close, Net.ipv4.tcp_tw_recycle = # indicates a fast recycle of time-wait sockets on a TCP connection, and the default is 0, which means shutdown. Net.ipv4.tcp_fin_timeout = 30# means that if the socket is closed by the local side, this parameter determines how long it remains in the fin-wait-2 state. Net.ipv4.tcp_keepalive_time = #表示当keepalive起用的时候, the frequency at which TCP sends keepalive messages. The default is 2 hours, which is changed to 20 minutes. Net.ipv4.ip_local_port_range = 1024x768 65000 #表示用于向外连接的端口范围. Small by default: 32768 to 61000, 1024 to 65000. Net.ipv4.tcp_max_tw_buckets = 5000# indicates that the system maintains the maximum number of time_wait sockets at the same time, if this number is exceeded, #TIME_WAIT套接字将立刻被清除并打印警告信息. The default is 180000, which changes to 5000. #对于Apache, Nginx and other servers, the parameters of the last few lines can be a good way to reduce the number of time_wait sockets, #但是对于Squid, the effect is small. This parameter controls the maximum number of time_wait sockets, preventing squid servers from being dragged to death by a large number of time_wait sockets
4.3 Passwords password Policy modification
Cat/etc/login.defs|grep passpass_max_days #新建用户的密码最长使用天数PASS_MIN_DAYS 0 #新建用户的密码最短使用天数PASS_WARN_AGE 7 # New user's password expires in advance reminder days Pass_min_len 9 #最小密码长度9
4.4 Historical Command retention and common service port modifications
Vim/etc/profile Modify histsize=5 and histfilesize=5 to keep the most recently executed 5 commands common service into SSH,FTP,MYSQL, etc., do not use the default port
4.5, Banner Camouflage
Can disrupt the intruder. This judgment of the server information
A, Vsftpd banner camouflage
Modify Vsftpd.conf
Ftpd_banner=welcome to Microsoft FTP service.
b, Apache banner camouflage
Modify the/usr/local/apache/conf/httpd.conf file, you can hide some Apache information, if you want to block out all the information, need to modify the source file to recompile
Httpd-2.2.25/include/ap_release.h
Httpd-2.2.25/os/unix/os.h
C, Nginx Banner camouflage
Add server_tokens off in the HTTP block of nginx.conf;
To completely block, you need to modify the source code, reinstall
Src/core/nginx.h
D, PHP Banner modification
php.ini Modify expose_php on-> expose_php = Off
PHP eggs, php source/ext/standard/info.h
E, TTL value modification
echo Net.ipv4.ip_default_ttl = >>/etc/sysctl.conf
/sbin/sysctl–p
F, the use of iptables, the local TCP 3389 port to the other 3389 ports on the computer, to the Linux system masquerading as a service TCP 3389 port
echo 1 >/proc/sys/net/ipv4/ip_forwardiptables-t nat-i prerouting-p tcp--dport 3389-j DNAT--to xx.xx.xx.xxiptable S-t nat-i postrouting-p TCP--dport 3389-j Masquerade
4.6. Firewall iptables Settings
Here are the rules required for some of the common Linux services. (change according to the actual situation)
Vim /etc/sysconfig/iptables# Generated by Iptables-save v1.3.5 on Thu Oct 19:38:46 2013*filter:input ACCEPT [782:10 0478]:forward Accept [0:0]:output Accept [227493:21979253]-a input-s 127.0.0.1-d 127.0.0.1-j accept-a input-p tcp-m t CP--dport 3306-j accept-a input-m State--state related,established-j accept-a input-p tcp-m tcp--dport 22-j ACCEP T-a input-p tcp-m TCP--dport 80-j ACCEPT (can be replaced with the following anti-CC rules)-A input-p tcp-m tcp--dport 21-j accept-a input-p tcp-m TCP--dport 20-j accept-a input–p tcp-j reject–reject-with tcp-reset-a input-j REJECT--reject-with ICMP-PORT-UNREAC Hable-a forward-j REJECT--reject-with icmp-port-unreachable-a output-j acceptcommit# completed on Thu Oct 31 19:38:46 2 013service iptables saveservice iptables restart
(1) Iptables rules to prevent CC attacks
Installing the Kernel-smp-modules-connlimit, recent kernel modules
Modprobe Ipt_connlimit
If you do not have this file, create the following file
# cat/etc/modprobe.d/ipt.confoptions Ipt_recent ip_pkt_list_tot=200modprobe–r ipt_recent
Control the maximum number of concurrent connections for a single IP
Iptables-i input-p TCP--dport 80-m connlimit--connlimit-above 50-j REJECT #允许单个IP的最大连接数为 30//control a single IP within a certain time (for example, 60 seconds) allow new Number of connections established iptables-a input-p TCP--dport 80-m recent--name bad_http_access--update--seconds--hitcount 30-j REJECTi Ptables-a input-p TCP--dport 80-m recent--name bad_http_access--set-j ACCEPT #单个IP在60秒内只允许最多新建30个连接
(2) iptables limit host login rules
Limit each host to 5 hosts per hour (default rule for INPUT chain is accept) iptables-a input-p TCP--dport 22-m State--state new-m Recent--name Sshpool-- rcheck --seconds 3600 --hitcount 5 -j DROP iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --name SSHPO OL--set-j ACCEPT
4.7. Prevent Violent login
Ftp,ssh Brute Force login, script implementation.
4.8. Monitor all end-user operations
Log all logged-in user Terminal Operations Command records
vim/etc/profileps1= "' WhoAmI ' @ ' hostname ':" ' [$PWD] ' historyuser_ip= ' who-u am I 2>/dev/null| awk ' {print $NF} ' |sed-e ' s/[()]//g "if [" $USER _ip "="]then user_ip= ' hostname ' FIIF [! -D/TMP/CSI]then mkdir/tmp/csi chmod 777/tmp/csifiif [!-d/tmp/csi/${logname}]then Mkdir/tmp/csi/${log NAME} chmod 300/tmp/csi/${logname}fiexport histsize=4096dt= ' date ' +%y-%m-%d_%h:%m:%s ' ' Export histfile= '/tmp/ CSI/${LOGNAME}/${USER_IP} CSI. $DT "chmod 600/tmp/csi/${logname}/*csi* 2>/dev/nullsource/etc/profile
4.9 Log Audits
Unified Remote Log server configuration, the current system should configure the remote logging function, will need to focus on the log content transfer to the log server for backup.
Modifying a configuration file/etc/rsyslog.conf
Add this line: authpriv.* @x.x.x.x
Restart the Syslog service and execute the following command: Services syslogd restart
4.10. Change dangerous file (command) permissions
Only the root user can use the command
chmod 700/bin/pingchmod 700/usr/bin/fingerchmod 700/usr/bin/whochmod 700/usr/bin/wchmod 700/usr/bin/locatechmod 700/ Usr/bin/whereischmod 700/sbin/ifconfigchmod 700/usr/bin/picochmod 700/usr/bin/vichmod 700/usr/bin/whichchmod 700/ Usr/bin/gccchmod 700/usr/bin/makechmod 700/bin/rpm
4.11. Anti-virus software
Download http://www.clamav.net/lang/en/download/sources/
Direct download: http://downloads.sourceforge.net/clamav/clamav-0.98.1.tar.gz
4.12. Rootkit Virus Detection
Rkhunter Download: http://jaist.dl.sourceforge.net/project/rkhunter/rkhunter/1.4.2/rkhunter-1.4.2.tar.gz
Chkrootkit Download: ftp://ftp.pangeia.com.br/pub/seg/pac/chkrootkit.tar.gz
4.13, inotify monitoring System files
Monitoring commands
Inotifywait-m-d-o/tmp/inotify.log-r--timefmt "%F%T"--format '%T%w%f%:e '-e close_write,create, Modify,attrib/var /www/html
INotify monitor the larger directory when the error, you need to modify the value of/proc/sys/fs/inotify/max_user_watches
Recommended Write sysctl.conf:fs.inotify.max_user_watches=8192000
5. System Application Security Configuration 5.1, middleware security Configuration
(1) Apache Security Configuration
Apache prohibits the data directory from executing script files such as PHP <directory "/path/directory" ><filesmatch ". (php|asp|jsp) $ "> Deny from all</filesmatch> </directory>//apache disable directory Browsing and symbolic link tracking <directory"/ Usr/local/apache/htdocs "> Options Indexes followsymlinks #禁用这两项 allowoverrride None Order Allow,deny Allow from all </Directory>
(2) Nginx Security Configuration
Nginx prohibit data directory to execute script files such as PHP (in nginx.conf server segment configuration)//single directory location ~* ^/attachments/.*\. (PHP|PHP5) $ { deny all;} Multiple directory location ~* ^/(image|upload)/.*\. (PHP|PHP5) $ { deny all;}//nginx restricted connection module limit_zone with Limit_req_zone//limit_zone configuration http{ Limit_conn_zone $ Binary_remote_addr zone=one:10m; #one是zone的名字, 10m is a session-state storage space server{ limit_zone one 1; #1每秒限制链接1次 }}//limit_req_zone configuration http{ limit_ Req_zone $binary _remote_addr zone=req_one:10m rate=1r/s; # rate=1r/s means that each address can only be requested once per second, that is, according to the leaky bucket principle burst=120 there are altogether 120 tokens, and only add 1 tokens per second after the token 120 tokens sent out after the request will be returned 503 server{ Limit_req zone=req_one burst=120; }}
5.2. PHP Security Configuration
Open_basedir =.:/ tmp/#防止php木马跨站, Important!! Disable_funcation=chdir,dir,get_cwd,opendir,readdir,scandir,fopen,unlink,delete,copy,mkdir,rmdir,rename,file, File_get_contents,fputs,fwrite,chmod,phpinfo,passthru,exec,system,chroot,scandir,chgrp,chown,shell_exec,proc_ Open,proc_get_status,ini_alter,ini_alter,ini_restore,dl,openlog,syslog,readlink,symlink,popepassthru,stream_ Socket_server,escapeshellcmd,dll,popen,disk_free_space,checkdnsrr,checkdnsrr,getservbyname,getservbyport,disk_ Total_space,posix_ctermid,posix_get_last_error,posix_getcwd,posix_getegid,posix_geteuid,posix_getgid,osix_ 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_strerror,posix_times, posix_ttyname,posix_uname//If the server uses the acquisition, you need to enable unlink and fopen, file_get_contents,fputs,fwrite,dir//function MKDIR,FILE,FILE_GET_CONTENTS,FPUTS,FWRITE,DIRMAGIC_QUOTES_GPC = OFF//open MAGIC_QUOTES_GPC to prevent SQL injection MAGIC_ QUOTES_GPC = ON//If it is turned on, it will automatically convert the user to the SQL query, such as ' turn to \ ', which has a significant effect on preventing SQL injection. So we recommend setting to: Register_globals = off//OFF Register global variable Safe_mode = on//php Safe mode is a very important embedded security mechanism that can control some functions in PHP, such as System (), At the same time, a lot of file operation functions have permission control, also do not allow files for some key files, such as/etc/passwd, but the default php.ini is not open security mode, we opened it: Safe_mode_gid = off//user group security, when Safe_ When mode is turned on, Safe_mode_gid is turned off, and the PHP script can access the file, and the same group of users can access the file. Safe_mode_exec_dir =/usr/wwwdisplay_errors = offerror_reporting = e_warning & e_errorlog_errors = Onerror_log = D:/us R/local/apache2/logs/php_error.log//Note: Giving files must allow Apache users and groups to have write permissions
Reference articles
Http://m.jb51.net/hack/55784.html
Https://blog.slogra.com/post-684.html
Http://blog.chinaunix.net/uid-25723371-id-4542221.html
Some problems needing attention in Linux system security