Some security tips for SSH in CentOS

Source: Internet
Author: User
Tags ssh server egrep

Some security tips for SSH in CentOS
Preface

I don't need to talk about the benefits of ssh? For example, the previous rpc commands can be replaced by ssh in telnet:

 
  1. -Remote Logon
  2. ssh user@remote.machine
  3. -Remote Execution
  4. ssh user@remote.machine 'command ...'
  5. -Remote replication
  6. scp user@remote.machine:/remote/path /local/path
  7. scp /local/path user@remote.machine:/remote/path
  8. - X forward
  9. ssh -X user@remote.machine
  10. xcommand ...
  11. - Tunnel / Portforward
  12. ssh -L 1234:remote.machine:4321 user@remote.machine
  13. ssh -R 1234:local.machine:4321 user@remote.machine
  14. ssh -L 1234:other.machine:4321 user@remote.machine

For detailed usage, I will not talk about it. Please study it on your own.

I want to talk about some security skills for the ssh service.

Instance

(Take RedHat 9 as an example)

 
  1. Publish to client:
  2. $ ssh-keygen -t rsa
  3. * You do not need to set a password when you press enter three times, unless you use ssh-agent.
  4. $ scp ~/.ssh/id_rsa.pub user1@server.machine:id_rsa.pub
  5. * If it is a windows client, puttygen.exe can be used to generate a public key,
  6. Then modify it after writing the code to the server to make the content a single line.
  7. * If the server has disabled Password Logon, use other methods to encrypt the publick key.

Log on to the server:

  • Disable root Login

     
      
    1. # vi /etc/ssh/sshd_config
    2. PermitRootLogin no
  • In addition to password authentication, the token forces the use of the RSA certificate (false ssh authentication as user1)

     
      
    1. # vi /etc/ssh/sshd_config
    2. RSAAuthentication yes
    3. PubkeyAuthentication yes
    4. AuthorizedKeysFile .ssh/authorized_keys
    5. PasswordAuthentication no
    6. # service sshd restart
    7. # su - user1
    8. $ mkdir ~/.ssh 2>/dev/null
    9. $ chmod 700 ~/.ssh
    10. $ touch ~/.ssh/authorized_keys
    11. $ chmod 644 ~/.ssh/authorized_keys
    12. $ cat ~/id_rsa.pub >> ~/.ssh/authorized_keys
    13. $ rm ~/id_rsa.pub
    14. $ exit
  • Restrict su/sudo names:

     
      
    1. # vi /etc/pam.d/su
    2. auth required /lib/security/$ISA/pam_wheel.so use_uid
    3. # visudo
    4. %wheel ALL=(ALL) ALL
    5. # gpasswd -a user1 wheel
  • Restrict ssh user names

     
      
    1. # vi /etc/pam.d/sshd
    2. auth required pam_listfile.so item=user sense=allow file=/etc/ssh_users onerr=fail
    3. # echo user1 >> /etc/ssh_users
  • Use the web control tool to clear the login ssh authentication ticket.

     
      
    1. # iptables -I INPUT -p tcp --dport 22 -j DROP
    2. # mkdir /var/www/html/ssh_open
    3. # cat > /var/www/html/ssh_open/.htaccess <<END
    4. AuthName "ssh_open"
    5. AuthUserFile /var/www/html/ssh_open/.htpasswd
    6. AuthType basic
    7. require valid-user
    8. END
    9. # htpasswd -c /var/www/html/ssh_open/.htpasswd user1

(It is better to set up SSL, or set it only for https protocol. I have set it for SSL. Please refer to the setting here .) (If you need to control the source region, please refer to the Allow/Deny category, or the author's self-contained .)

 
  1. # cat > /var/www/html/ssh_open/ssh_open.php <<END
  2. <?
  3. //Set dir path for ip list
  4. $dir_path=".";
  5. //Set filename for ip list
  6. $ip_list="ssh_open.txt";
  7. //Get client ip
  8. $user_ip=$_SERVER['REMOTE_ADDR'];
  9. //allow specifying ip if needed
  10. if (@$_GET['myip']) {
  11. $user_ip=$_GET['myip'];
  12. }
  13. //checking IP format
  14. if ($user_ip==long2ip(ip2long($user_ip))) {
  15. //Put client ip to a file
  16. if(@!($file = fopen("$dir_path/$ip_list","w+")))
  17. {
  18. echo "Permission denied!!<br>";
  19. echo "Pls Check your rights to dir $dir_path or file $ip_list";
  20. }
  21. else
  22. {
  23. fputs($file,"$user_ip");
  24. fclose($file);
  25. echo "client ip($user_ip) has put into $dir_path/$ip_list";
  26. }
  27. } else {
  28. echo "Invalid IP format!!<br>ssh_open.txt was not changed.";
  29. }
  30. ?>
  31. END
  32. # touch /var/www/html/ssh_open/ssh_open.txt
  33. # chmod 640 /var/www/html/ssh_open/*
  34. # chgrp apache /var/www/html/ssh_open/*
  35. # chmod g+w /var/www/html/ssh_open/ssh_open.txt
  36. # chmod o+t /var/www/html/ssh_open
  37. # service httpd restart
  38. # mkdir /etc/iptables
  39. # cat > /etc/iptables/sshopen.sh <<END
  40. #!/bin/bash
  41. PATH=/sbin:/bin:/usr/sbin:/usr/bin
  42. list_dir=/var/www/html/ssh_open
  43. list_file=$list_dir/allow_ssh.txt
  44. bad_list=$list_dir/bad_ip.txt
  45. auth_log=$list_dir/xinetd.log
  46. trusted_ip="127.0.0.1 4.3.2.1"
  47. chain_name=ssh_rules
  48. mail_to=root
  49. # clear chain if exits, or create chain.
  50. iptables -L -n | /bin/grep -q "^Chain $chain_name" && {
  51. iptables -F $chain_name
  52. true
  53. } || {
  54. iptables -N $chain_name
  55. iptables -I INPUT -p tcp --dport 22 -j $chain_name
  56. }
  57. # clear chain on demand
  58. [ "$1" = clear ] && {
  59. iptables -F $chain_name
  60. cat /dev/null > $list_file
  61. exit 0
  62. }
  63. # do nothing while list is empty
  64. [ -s $list_file ] || exit 1
  65. # deny connection if host dosn't math to list
  66. host_ip=$(grep 'myssh from=' $auth_log | tail -1 | awk -F'=' '{print $NF}')
  67. list_ip=$(cat $list_file)
  68. if [ -n "$host_ip" -a "$host_ip" != "$list_ip" ]; then
  69. echo -e "${trusted_ip/ /\n}" | grep -q "$host_ip" || {
  70. /sbin/iptables-save | grep -q "INPUT -s $host_IP -j DROP$" || {
  71. /sbin/iptables -I INPUT -s $host_ip -j DROP
  72. echo $host_ip >> $bad_list
  73. echo "$host_ip is blocked by $0 on $(date)" | mail -s "block
  74. ip" $mail_to
  75. }
  76. }
  77. exit 2
  78. fi
  79. # add rule
  80. iptables -A $chain_name -p tcp --dport 22 -s $(< $list_file) -j ACCEPT && \
  81. echo "ssh opened to $(< $list_file) on $(date)" | \
  82. mail -s "sshopen" $mail_to
  83. exit 0
  84. END
  85. # chmod +x /etc/iptables/sshopen.sh
  86. # echo -e 'sshopen\t\t1234/tcp' >> /etc/services
  87. # cat > /etc/xinetd.d/sshopen <<END
  88. service sshopen
  89. {
  90. log_type = FILE /studyarea/www/phorum/xinetd.log
  91. log_on_success = HOST
  92. log_on_failure = HOST
  93. disable = no
  94. socket_type = stream
  95. protocol = tcp
  96. wait = no
  97. user = root
  98. server = /etc/iptables/sshopen.sh
  99. }
  100. # iptables -I INPUT -p tcp --dport 1234 -j ACCEPT
  101. # cat > /etc/cron.d/sshopen <<END
  102. */5 * * * * root /etc/iptables/sshopen.sh clear
  103. END
  104. Publish to client
  105. In browser URL merge:
  106. http://server.machine/ssh_open/ssh_open.php?myip=1.2.3.4
  107. (If not specified? Myip = 1.2.3.4 is based on the client's IP address at that time. If no proxy is available .)
  108. In this way, the ssh_open.txt on the server only has a single record, and each time the record is sent.
  109. Next:
  110. $ telnet server.machine 1234
  111. Then you have a maximum of five minutes using ssh to connect to the server!

The basic structure of this step is as follows:

  • Block all firewall blocks of sshd.

    • Then, set a directory in httpd, set ssl + htpasswd + allow/deny control, and then upload a php file to record the browser ip address. txt text. depending on your browser capabilities, you can manually capture the IP address of the browser, or allow the browser terminal to import data to specify. only one record is displayed for the text watermark, Which is cleared regularly each time.
    • Modify/etc/services, add a new category (such as xxx), and specify a new port (such as 1234)
    • Use the xinetd script to listen to the port and run a script to configure iptables. Then, obtain the IP address from the checklist in step 2 and enable ssh authentication.
    • Set crontab to clean up iptables rules related to ssh route entries and clear the records in each score. this does not mean that there are already two operators. If the time exceeds the limit, the above will be repeated.
  • If this parameter is not set in the previous step, you may be tempted to try your ssh Server:

     
      
    1. # cat > /etc/iptables/sshblock.sh <<END
    2. #!/bin/bash
    3. PATH=/sbin:/bin:/usr/sbin:/usr/bin
    4. LOG_FILE=/var/log/secure
    5. KEY_WORD="Illegal user"
    6. KEY_WORD1="Failed password for root"
    7. PERM_LIST=/etc/firewall/bad.list.perm
    8. LIMIT=5
    9. MAIL_TO=root
    10. IPT_SAV="$(iptables-save)"
    11. bad_list=$(egrep "$KEY_WORD" $LOG_FILE | awk '{print $NF}' | xargs)
    12. bad_list1=$(egrep "$KEY_WORD1" $LOG_FILE | awk '{print $11}' | xargs)
    13. bad_list="$bad_list $bad_list1"
    14. for i in $(echo -e "${bad_list// /\n}" | sort -u)
    15. do
    16. hit=$(echo $bad_list | egrep -o "$i" | wc -l)
    17. [ "$hit" -ge "$LIMIT" ] && {
    18. echo "$IPT_SAV" | grep -q "$i .*-j DROP" || {
    19. echo -e "\n$i was dropped on $(date)\n" | mail -s "DROP by ${0##*/}: $i" $MAIL_TO
    20. iptables -I INPUT -s $i -j DROP
    21. }
    22. egrep -q "^$i$" $PERM_LIST || echo $i >> $PERM_LIST
    23. }
    24. done
    25. END
    26. # chmod +x /etc/firewall/sshblock.sh
    27. # cat >> /etc/hosts.allow <<END
    28. sshd: ALL: spawn ( /etc/firewall/sshblock.sh )& : ALLOW
    29. END

In this way, the guys who try SSH can initiate a maximum of five LIMIT requests, and then BLOCK the requests. in addition, the ip address in PERM_LIST can also be provided to the initial script of iptables to generate a permanent token:

 
  1. for i in $(< $PERM_LIST)
  2. do
  3. /sbin/iptables -I INPUT -s $i -j DROP
  4. done
  • Also, if you want to know who is doing full range port scan for you:

     
      
    1. # iptables -I INPUT -p tcp --dport 79 -j ACCEPT
    2. cat > /etc/xinetd.d/finger <<END
    3. service finger
    4. {
    5. socket_type = stream
    6. wait = no
    7. user = nobody
    8. server = /usr/sbin/in.fingerd
    9. disable = no
    10. }
    11. END
    12. # cat >> /etc/hosts.allow <<END
    13. in.fingerd: ALL : spawn ( echo -e "\nWARNING %a was trying finger.\n$(date)" | mail -s "finger from %a" root ) & : DENY
    14. END

Here, I just set it to send to root.

In fact, you can modify it to trigger firewall to return the value of % a to ban.

However, if the peer has a selective port scan and does not reach finger, then it is useless...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.