Write on the front: When you deploy a server, the first step should not be to deploy the application, security is the first task.
If one day you log on to the server and find commands like / bin/bash - i, Python - C'import pty; pty. spawn ("/bin/sh") appear on the server, then congratulations, the server has been hacked.
But intruders are smart. First, they execute the following commands.
unset HISTORY HISTFILE HISTSAVE HISTZONE HISTORY HISTLOG; export HISTFILE=/dev/null; export HISTSIZE=0; export HISTFILESIZE=0
Then access through the springboard
ssh -o UserKnownHostsFile=/dev/null -T user@host /bin/bash –i
Establishing ttyshell
python -c 'import pty; pty.spawn("/bin/sh")'
Then clear the access record
shred -n 31337 -z -u file_to_delete
Wait... A series of operations
Then you can see that the server will leave more clues, so how can we prevent it?
1. System user optimization
Users are the first barrier of security reinforcement in Linux. If there are users with security risks in the system itself, then no security strategy can play a reinforcement effect.
cat /etc/passwd | awk -F: '$3==0' //List users with super privileges cat /etc/passwd | grep '/bin/bash' //List users with a login shell
If there are other superusers besides root, be very careful.
Deleted users, such as adm,lp,sync,shutdown,halt,news,uucp,operator,games,gopher
Deleted groups, such as adm,lp,news,uucp,games,dip,pppusers,popusers,slipusers
1.2 or lock users who do not need to log inFor example: 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 Limits users who can su to root#Add: auth required /lib/security/pam_wheel.so group=wheel
In this way, only users of the wheel group can su to root
1.4 Check shadow Hollow Password Accountawk -F: '( $2== "") { print }' /etc/shadow
Lock an empty password account or ask for an additional password
1.5 Privilege Control of Key Directories in SystemAccording to security requirements, configure the minimum permissions required for some key directories, password file, shadow file, group file permissions.
/ etc/passwd is readable by all users, and root user writes rw-r-r____________
chmod 644 /etc/passwd
/ etc/shadow is only root readable r _____________
chmod 600 /etc/shadow
/ etc/group must be readable by all users, and root user writes 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 commands to view the system services currently running by default:
chkconfig --list | grep "3:on"
If we only provide web services, then we can shut down unnecessary services such as sendmail, nfs, postfix, ftp, etc.
For key services, we need to ensure that they run, such as iptables, sshd, syslog, httpd, nginx, mysql, php-fpm, etc.
3. ssh access policy
ssh access is almost the only means of control system in our daily work. So the security of ssh is very important. Generally speaking, the higher security strategy of ssh follows the following principles.
-
Prohibit root user ssh login.
-
Prohibit password verification.
-
Only one user is allowed full permissions for sudo.
-
Private key files are not allowed to be stored in the system unless it is a fortress.
-
Use a random port instead of port 22.
Edit / etc/sudoers, add one:
test ALL=(ALL) NOPASSWD: ALL
Here's an example: give test full sudo privileges, and you don't need to validate passwords when sudo privileges are raised.
sed -i 's/\(PasswordAuthentication\) yes/\1 no/' /etc/ssh/sshd_config //No Passwords, Use Certificates sed -i 's/\(PermitRootLogin\) yes/\1 no/' /etc/ssh/sshd_config //Prohibit root user ssh login
Now let's look at ssh's access effects:
-
All users cannot authenticate login with password.
-
Root users can't log in directly. Even if they have root password, the only way to get root is to use test user privilege.
-
test users can only log in with certificates.
-
ssh no longer uses the default port 22
4. Internal Security Configuration of the System
4.1. Protection and Guidance Process//User startup needs to enter 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-delete4.2. Kernel modification
/ Change etc/sysctl.conf to the following
kernel.shmall = 268435456 net.ipv4.tcp_syncookies = 1 net.ipv4.tcp_tw_reuse = 1 net.ipv4.tcp_tw_recycle = 1 net.ipv4.tcp_fin_timeout = 30 net.ipv4.tcp_keepalive_time = 1200 net.ipv4.ip_local_port_range = 1024 65000 net.ipv4.tcp_max_tw_buckets = 5000 net.ipv4.tcp_max_tw_buckets = 5000 net.ipv4.tcp_fin_timeout = 30 net.ipv4.tcp_keepalive_time = 300 net.ipv4.tcp_tw_reuse = 1 net.ipv4.tcp_tw_recycle = 1 net.ipv4.ip_local_port_range = 5000 65000 net.ipv4.tcp_mem = 786432 1048576 1572864 net.core.wmem_max = 873200 net.core.rmem_max = 873200 net.ipv4.tcp_wmem = 8192 436600 873200 net.ipv4.tcp_rmem = 32768 436600 873200 net.core.somaxconn = 256 net.core.netdev_max_backlog = 1000 net.ipv4.tcp_max_syn_backlog = 2048 net.ipv4.tcp_retries2 = 5 net.ipv4.tcp_keepalive_time = 500 net.ipv4.tcp_keepalive_intvl = 30 net.ipv4.tcp_keepalive_probes = 3 net.ipv4.conf.lo.arp_ignore = 0 net.ipv4.conf.lo.arp_announce = 0 net.ipv4.conf.all.arp_ignore = 0 net.ipv4.conf.all.arp_announce = 0
/ Change etc/security/limits.conf to the following
* soft nofile 655360 * hard nofile 655360
explain
net.ipv4.tcp_syncookies = 1 #Represents opening SYN Cookies. When SYN waiting queue overflow occurs, cookies are enabled to deal with it, which can prevent a small number of SYN attacks, defaulting to 0, indicating closure. net.ipv4.tcp_tw_reuse = 1 #Represents open reuse. TIME-WAIT sockets are allowed to be reused for new TCP connections by default of 0, indicating closure. net.ipv4.tcp_tw_recycle = 1 #Represents the quick recovery of TIME-WAIT sockets in open TCP connections, defaulting to 0, indicating closure. net.ipv4.tcp_fin_timeout = 30 #Represents that if the socket is shut down by the local end, this parameter determines the time it will remain in FIN-WAIT-2 state. net.ipv4.tcp_keepalive_time = 1200 #Represents how often TCP sends keepalive messages when keepalive is used. The default is 2 hours, instead of 20 minutes. net.ipv4.ip_local_port_range = 1024 65000 #Represents the port range for outward connections. The default is very small: 32768 to 61000, instead of 1024 to 65000. net.ipv4.tcp_max_tw_buckets = 5000 #Represents that the system maintains the maximum number of TIME_WAIT sockets at the same time, if this number exceeds, #The TIME_WAIT socket will be cleared immediately and a warning message printed. The default is 18000, changed to 5000. #For servers such as Apache and Nginx, the parameters in the last few lines can reduce the number of TIME_WAIT sockets very well. #But for Squid, the effect is not great. This parameter controls the maximum number of TIME_WAIT sockets and prevents Squid servers from being dragged by a large number of TIME_WAIT sockets.4.3 Password Password Policy Modification
cat /etc/login.defs|grep PASS PASS_MAX_DAYS 90 #Maximum number of days of password usage for new users PASS_MIN_DAYS 0 #Minimum number of days of password usage for new users PASS_WARN_AGE 7 #Number of days in advance to remind new users of password expiration PASS_MIN_LEN 9 #Minimum password length 94.4 Retention of historical commands and modification of common service ports vim /etc/profile Modify HISTSIZE=5 and HISTFILESIZE=5 to retain the latest five commands executed Common services into SSH,FTP,MYSQL, etc., do not use the default port 4.5. Banner camouflage
Can disrupt the intruder's judgment of 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 to hide some apache information. If you want to block all information, you need to modify the source file and recompile it.
httpd-2.2.25/include/ap_release.h
httpd-2.2.25/os/unix/os.h
c, Nginx banner camouflage
Add server_tokens off to the http block of nginx.conf.
To completely shield, you need to modify the source code and reinstall it
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 = 128 >> /etc/sysctl.conf
/sbin/sysctl –p
f. Using iptables, transfer the TCP 3389 port of this machine to other computers with 3389 ports, disguise a TCP 3389 port providing services to Linux system.
echo 1 > /proc/sys/net/ipv4/ip_forward iptables -t nat -I PREROUTING -p tcp --dport 3389 -j DNAT --to xx.xx.xx.xx iptables -t nat -I POSTROUTING -p tcp --dport 3389 -j MASQUERADE4.6. Firewall IPtables settings
Here are the rules that linux needs for some common services. (Change according to the actual situation)
vim /etc/sysconfig/iptables # Generated by iptables-save v1.3.5 on Thu Oct 31 19:38:46 2013 *filter :INPUT ACCEPT [782:100478] :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 tcp --dport 3306 -j ACCEPT -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT (You can use the back guard CC Rule substitution) -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-unreachable -A FORWARD -j REJECT --reject-with icmp-port-unreachable -A OUTPUT -j ACCEPT COMMIT # Completed on Thu Oct 31 19:38:46 2013 service iptables save service iptables restart
(1) Rules for iptables to prevent CC attacks
Install kernel-smp-modules-connlimit, receive kernel modules
modprobe ipt_connlimit
If you do not have this file, you need to create the following file
# cat /etc/modprobe.d/ipt.conf options ipt_recent ip_pkt_list_tot=200 modprobe –r ipt_recent
Controlling the maximum number of concurrent connections for a single IP
iptables -I INPUT -p tcp --dport 80 -m connlimit --connlimit-above 50 -j REJECT #Maximum number of connections allowed for a single IP is 30 //Control the number of new connections that a single IP can allow for a certain period of time (such as 60 seconds) iptables -A INPUT -p tcp --dport 80 -m recent --name BAD_HTTP_ACCESS --update --seconds 60 --hitcount 30 -j REJECT iptables -A INPUT -p tcp --dport 80 -m recent --name BAD_HTTP_ACCESS --set -j ACCEPT #A single IP can only allow up to 30 new connections in 60 seconds
(2)iptables rules restricting host login
//Limit each host to five connections per hour (ACCEPT is the default rule for INPUT chain) 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 SSHPOOL --set -j ACCEPT4.7. Preventing violent login
ftp, ssh violent login, script implementation.
4.8. Monitor all end-user operationsRecord all logged-in user terminal operation command records
vim /etc/profile PS1="`whoami`@`hostname`:"'[$PWD]' history USER_IP=`who -u am i 2>/dev/null| awk ''|sed -e 's/[()]//g'` if [ "$USER_IP" = "" ] then USER_IP=`hostname` fi if [ ! -d /tmp/csi ] then mkdir /tmp/csi chmod 777 /tmp/csi fi if [ ! -d /tmp/csi/$ ] then mkdir /tmp/csi/$ chmod 300 /tmp/csi/$ fi export HISTSIZE=4096 DT=`date "+%Y-%m-%d_%H:%M:%S"` export HISTFILE="/tmp/csi/$/$ csi.$DT" chmod 600 /tmp/csi/$/*csi* 2>/dev/null source /etc/profile4.9 Log Audit
Unified remote log server configuration, the current system should configure the remote log function, will need to focus on the log content transmission to the log server for backup.
Modify the configuration file/etc/rsyslog.conf
Add this line: authpriv. *@x.x.x.x
Restart the syslog service and execute the following commands: services syslogd restart
4.10. Change the permissions of dangerous files (commands)Only root users can use a command
chmod 700 /bin/ping chmod 700 /usr/bin/finger chmod 700 /usr/bin/who chmod 700 /usr/bin/w chmod 700 /usr/bin/locate chmod 700 /usr/bin/whereis chmod 700 /sbin/ifconfig chmod 700 /usr/bin/pico chmod 700 /usr/bin/vi chmod 700 /usr/bin/which chmod 700 /usr/bin/gcc chmod 700 /usr/bin/make chmod 700 /bin/rpm4.11. Antivirus 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 detectionRkhunter 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 filesMonitoring command
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 will report errors when monitoring larger directories, and the value of / proc/sys/fs/inotify/max_user_watches needs to be modified
It is recommended to write sysctl.conf: fs.inotify.max_user_watches=8192000
5. System Application Security Configuration
5.1. Security Configuration of Middleware(1) apache security configuration
//Apache prohibits data directories from executing script files such as php <Directory "/path/directory"> <FilesMatch ".(php|asp|jsp)$"> Deny from all </FilesMatch> </Directory> //Apache disables directory browsing and symbolic link tracking <Directory "/usr/local/apache/htdocs"> Options Indexes FollowSymLinks #Ban these two items AllowOverrride None Order allow,deny Allow from all </Directory>
(2) nginx security configuration
//Nginx prohibits data directories from executing script files such as php (configured in the nginx.conf server section) //Single directory location ~* ^ /attachments/.*\.(php|php5)$ { deny all; } //Multiple directories location ~* ^/(image|upload)/.*\.(php|php5)$ { deny all; } //Restricted Connection Modules limit_zone and limit_req_zone of nginx //limit_zone configuration http{ limit_conn_zone $binary_remote_addr zone=one:10m; #one is the name of zone and 10m is the session state storage space. server{ limit_zone one 1; #Limit links once per second } } //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 to say, according to the leaky bucket principle burst=120, there are 120 tokens in total, and only one token per second 120 tokens are added, and the additional requests after issuance will return 503. server{ limit_req zone=req_one burst=120; } }5.2. php security configuration
open_basedir = .:/tmp/ #It's important to prevent php Trojan Horse from crossing the station!! _________ 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 acquisition, unlink and fopen, file_get_contents, fput, fwrite, dir need to be enabled. //Functions mkdir, file, file_get_contents, fput, fwrite, dir used to upload pictures in the background magic_quotes_gpc = Off //Open magic_quotes_gpc to prevent SQL injection magic_quotes_gpc = On //If it opens, it will automatically convert the queries submitted by users to sql, such as converting'to', which will play an important role in preventing SQL injection. So we recommend setting it as: register_globals = Off //Close registered global variables safe_mode = on //The security mode of PHP is a very important embedded security mechanism, which can control some functions in php, such as system(), and control the privileges of many file operation functions. It also does not allow files of some key files, such as / etc/passwd. But the default php.ini does not open the security mode. We open it: safe_mode_gid = off //User group security. When safe_mode is opened and safe_mode_gid is closed, php scripts can access files, and users of the same group can access files. safe_mode_exec_dir = /usr/www display_errors = Off error_reporting = E_WARNING & E_ERROR log_errors = On error_log = D:/usr/local/apache2/logs/php_error.log //Note: Papers must be allowed to write to apache users and groups
Reference article
http://m.jb51.net/hack/55784.html
https://blog.slogra.com/post-684.html
http://blog.chinaunix.net/uid-25723371-id-4542221.html