Precautions for Linux System Security:
Preface: When you deploy a server, the first step should not be to deploy applications. Security is the primary task.
If one day you log on to the server and find/bin/bash-I, python-c 'import pty; pty. when commands such as spawn ("/bin/sh") 'appear on the server, congratulations! The server has been intruded.
But intruders are very smart. First, they will execute the following command:
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
Create ttyshell
python -c ‘import pty; pty.spawn(“/bin/sh”)’
Then clear access records
shred -n 31337 -z -u file_to_delete
And so on... A series of operations
Then you will be able to see the above clues on the server. How can we prevent them?
1. System User Optimization
Users are the first level of security reinforcement in Linux. If the system itself has users with security risks, then security policies cannot reinforce the system.
Cat/etc/passwd | awk-F: '$3 = 0' // List users with super permissions cat/etc/passwd | grep'/bin/bash' // List users with shell Logon
If there are other Super Users besides root, you should be very careful.
1.1 Delete the built-in users and user groups.
Deleted users, such as adm, lp, sync, shutdown, halt, news, uucp, operator, games, and gopher
Deleted groups, such as adm, lp, news, uucp, games, dip, pppusers, popusers, and slipusers
1.2 or lock users that do not need to log on
Such as xfs, news, nscd, region, 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 that can be su root
# Add auth required/lib/security/pam_wheel.so group = wheel to the/etc/pam. d/su Header
In this way, only the user in the wheel group can su to the root user.
1.4 check the shadow empty password account
awk -F: '( $2== "") { print }' /etc/shadow
Locks an empty password account or requires a new password.
1.5 key directory permission CONTROL IN THE SYSTEM
According to security requirements, configure the minimum permissions required for some key directories, such as password files, shadow files, and group files.
/Etc/passwd all users can read, and root users can write-rw-r-
chmod 644 /etc/passwd
/Etc/shadow only supports root readable-r ---
chmod 600 /etc/shadow
/Etc/group must be read by all users, and root users can write-rw-r-
chmod 644 /etc/group
2. System Service Optimization
Generally, the system may automatically run unnecessary services. You can run the following command to view the system services that are currently enabled by default:
chkconfig --list | grep "3:on"
If we only provide web services, we can disable unnecessary services such as sendmail, nfs, postfix, and ftp.
For key services, we need to ensure their operation, such as iptables, sshd, syslog, httpd, nginx, mysql, and php-fpm.
3. ssh Access Policy
Ssh access is almost the only means of controlling the system in our daily work. Therefore, the security of ssh is very important. Generally, high ssh security policies adhere to the following principles.
Prohibit root user ssh logon.
Password verification is prohibited.
Only one user is allowed to have full sudo permissions.
Unless it is a bastion host, private key files cannot be stored in the system.
Use a random port instead of port 22.
Edit/etc/sudoers and add one:
test ALL=(ALL) NOPASSWD: ALL
In this example, test is granted with full sudo permissions and the password does not need to be verified when sudo elevation of permissions is performed.
Sed-I's/\ (PasswordAuthentication \) yes/\ 1 no/'/etc/ssh/sshd_config // forbidden password, use the certificate sed-I's/\ (PermitRootLogin \) yes/\ 1 no/'/etc/ssh/sshd_config // prohibit root user ssh Login
Now let's look at the ssh access effect:
All users cannot log on with password verification.
Root users cannot log on directly. Even if they have the root password, the only way to obtain the root is to use the test user to escalate permissions.
The test user can only log on with the certificate.
Ssh no longer uses the default port 22
4. System Security Configuration 4.1. Protection Guide Process
// The user needs 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 and change it to # start on control-alt-delete.
4.2 kernel Modification
Change/etc/sysctl. conf 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 = 1024 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 = 5000 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 = 1000net.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
Change/etc/security/limits. conf to the following content:
* soft nofile 655360* hard nofile 655360
Explanation
Net. ipv4.tcp _ syncookies = 1 # indicates enabling SYN Cookies. When a SYN wait queue overflows, cookies are enabled to prevent a small number of SYN attacks. The default value is 0, indicating that the service is disabled. net. ipv4.tcp _ tw_reuse = 1 # indicates that reuse is enabled. Allow TIME-WAIT sockets to be re-used for a New TCP connection. The default value is 0, indicating that it is disabled. net. ipv4.tcp _ tw_recycle = 1 # indicates to enable quick recovery of TIME-WAIT sockets in TCP connections. The default value is 0, indicating to disable it. Net. ipv4.tcp _ fin_timeout = 30 # indicates that if the socket is disabled by the local end, this parameter determines the time it remains in the FIN-WAIT-2 state. Net. ipv4.tcp _ keepalive_time = 1200 # indicates the frequency of keepalive messages sent by TCP when keepalive is in use. The default value is 2 hours, which is changed to 20 minutes. Net. ipv4.ip _ local_port_range = 1024 65000 # indicates the port range used for external connection. The default value is small: 32768 to 61000, Which is changed to 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 socket is immediately cleared and warning information is printed. The default value is 180000, Which is changed to 5000. # For servers such as Apache and Nginx, the number of TIME_WAIT sockets can be greatly reduced by parameters in the previous lines. # However, Squid is not effective. This parameter can control the maximum number of TIME_WAIT sockets to prevent the Squid server from being dragged to death by a large number of TIME_WAIT sockets.
4.3 password and Password Policy Modification
Cat/etc/login. defs | grep PASSPASS_MAX_DAYS 90 # maximum number of days for new user passwords PASS_MIN_DAYS 0 # minimum number of days for new user passwords PASS_WARN_AGE 7 # minimum number of days PASS_MIN_LEN 9 # Minimum Password Length 9
4.4 historical command retention and frequently used service port Modification
Vim/etc/profile modify HISTSIZE = 5 and HISTFILESIZE = 5, that is, keep the 5 most recently executed commands frequently used services into SSH, FTP, MYSQL, and so on. Do not use the default port
4.5 Banner disguise
Can disrupt the attacker's judgment on server information.
A. Disguise Vsftpd banner
Modify vsftpd. conf
Ftpd_banner = Welcome to Microsoft FTP service.
B. Apache banner disguise
Modify the/usr/local/apache/conf/httpd. conf file to hide some apache information. To shield all information, modify the source code file and re-compile it.
Httpd-2.2.25/include/ap_release.h
Httpd-2.2.25/OS/unix/OS. h
C. Nginx banner disguise
Add server_tokens off in the http block of nginx. conf;
To completely block it, you need to modify the source code and reinstall it.
Src/core/nginx. h
D. PHP banner Modification
Php. ini modify expose_phpOn-> expose_php = Off
Php egg, PHP source code/ext/standard/info. h
E. Modify the TTL value
Echo net. ipv4.ip _ default_ttl = 128>/etc/sysctl. conf
/Sbin/sysctl-p
F. Use iptables to transfer the TCP port 3389 of the Local Machine to another computer with port 3389 enabled, and disguise a TCP port 3389 that provides services for the Linux system.
echo 1 > /proc/sys/net/ipv4/ip_forwardiptables -t nat -I PREROUTING -p tcp --dport 3389 -j DNAT --to xx.xx.xx.xxiptables -t nat -I POSTROUTING -p tcp --dport 3389 -j MASQUERADE
4.6 firewall IPtables settings
The following are the rules required for some common linux services. (Changed based on actual conditions)
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 (can be replaced by 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-unreachable-a forward-j REJECT -- reject-with icmp-port-unreachable-a output-j ACCEPTCOMMIT # Completed on Thu Oct 31 19:38:46 2013 service iptables saveservice iptables restart
(1) Rules for iptables to prevent CC attacks
Install kernel-smp-modules-connlimit and 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
Maximum number of concurrent connections per IP Address
Iptables-I INPUT-p tcp -- dport 80-m connlimit -- connlimit-above 50-j REJECT # the maximum number of connections allowed for a single IP address is 30 // control a single IP address at a certain time (for example, 60 seconds) allowed new connections in iptables-a input-p tcp -- dport 80-m recent -- name BAD_HTTP_ACCESS -- update -- seconds 60 -- hitcount 30-j REJECTiptables-a input-p tcp -- dport 80-m recent -- name BAD_HTTP_ACCESS -- set-j ACCEPT # A Single IP Address can create up to 30 connections in 60 seconds.
(2) iptables limits Host Logon rules
// Limit that each host can be connected to only five hosts per hour (the default INPUT chain rule 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 SSHPOOL -- set-j ACCEPT
4.7 prevent brute force login
Ftp, ssh Brute Force LOGIN, script implementation.
4.8 monitor all terminal user operations
Records Operation Command records of all logon User Terminals
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/${LOGNAME} 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/profile4.9 log auditing
Unified remote log server configuration. Currently, the system should configure the remote log function to transmit the log Content that requires attention to the log server for backup.
Modify the configuration file/etc/rsyslog. conf
Add this line: authpriv. * @ x. x
Restart the syslog service and run the following command: services syslogd restart
4.10. Modify dangerous file (command) Permissions
Only the root user can use the following 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/
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 File
Monitoring 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
An error is reported when Inotify monitors a large directory. You need to modify the value of/proc/sys/fs/inotify/max_user_watches.
We recommend that you write sysctl. conf: fs. inotify. max_user_watches = 8192000
5. System Application Security Configuration 5.1. Middleware Security Configuration
(1) apache Security Configuration
// Apache disables the data Directory from executing script files such as php <directory "/path/Directory"> <FilesMatch ". (php | asp | jsp) $ "> Deny from all </FilesMatch> </Directory> // disable Directory browsing and symbolic link tracing in Apache <Directory"/usr/local/apache/htdocs "> Options Indexes FollowSymLinks # disable AllowOverrride None Order allow, deny Allow from all </Directory>
(2) nginx Security Configuration
// Nginx disables the data directory from executing script files such as php (configured in the nginx. conf server segment) // a single directory location ~ * ^/Attachments/. * \. (php | php5) $ {deny all;} // multiple directories location ~ * ^/(Image | upload )/. *\. (php | php5) $ {deny all;} // nginx restricted connection modules limit_zone and limit_req_zone // limit_zone configure http {limit_conn_zone $ binary_remote_addr zone = one: 10 m; # one is the name of the zone, and 10 m is the session state bucket server {limit_zone one 1; #1 limit 1 link per second} // Limit_req_zone configure http {limit_req_zone $ binary_remote_addr zone = req_one: 10 m rate = 1r/s; # rate = 1r/s means that each address can only request once per second. That is to say, according to the principle of Bucket leakage, burst = 120 has a total of 120 tokens, and only one new token is added every second. The requests that are added after the 120 token is sent will return the 503 server {limit_req zone = req_one burst = 120 ;}}5.2. php Security Configuration
Open_basedir =.:/tmp/# It is important to prevent php trojans from being cross-site !! 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, delimiter, callback, escapeshellcmd, dll, popen, disk_free_space, checkdnsrr, checkdnsr R, getservbyname, getservbyport, delimiter, posix_getgrnam, posix_getgroups, posix_getlogin, delimiter, delimiter, posix_getpid, delimiter, 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 collection, enable unlink, fopen, file_get_contents, fputs, fwrite, dir // The mkdir, file, file_get_contents, fputs, fwrite, dirmagic_quotes_gpc = Off // enable magic_quotes_gpc to prevent SQL Injection magic_quotes_gpc = On // if it is enabled, users are automatically submitted to convert SQL queries, such as converting ', this plays a major role in preventing SQL injection. Therefore, we recommend that you set register_globals = Off // disable the registration of the global variable safe_mode = on // The Security Mode of php is a very important embedded security mechanism, ability to control some php functions, such as system (), and permission control for many file operation functions, and prohibit files of certain key files, such as/etc/passwd, however, the default php. ini does not enable safe mode. We open it: safe_mode_gid = off // user group security. When safe_mode is enabled, safe_mode_gid is disabled, so the php script can access the file, users in the same group can also access files. Logs =/usr/wwwdisplay_errors = Offerror_reporting = E_WARNING & E_ERRORlog_errors = Onerror_log = D:/usr/local/apache2/logs/php_error.log // note: the apache user and group must have the write permission for the file.
References
Http://m.jb51.net/hack/55784.html
Https://blog.slogra.com/post-684.html
Http://blog.chinaunix.net/uid-25723371-id-4542221.html