修改ssh默認端口
1 . 登錄服務器,打開sshd_config文件
[root@centos ~]# vim /etc/ssh/sshd_config
1
2 . 找到#Port 22,默認是注釋掉的,先把前面的#號去掉,再插入一行設置成你想要的端口號,注意不要跟現有端口號重復
......
# If you want to change the port on a SELinux system, you have to tell
# SELinux about this change.
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
Port 22
Port 10022
.....
SSH默認監聽端口是22,如果你不強制說明別的端口,”Port 22”注不注釋都是開放22訪問端口。上面我保留了22端口,防止之后因為各種權限和配置問題,導致連22端口都不能訪問了,那就尷尬了。等一切都ok了,再關閉22端口。
Ok,繼續,我增加了10022端口,大家修改端口時候最好挑10000~65535之間的端口號,10000以下容易被系統或一些特殊軟件占用,或是以后新應用准備占用該端口的時候,卻被你先占用了,導致軟件無法運行。
3 . 重啟SSH服務,最好也重啟下服務器
systemctl restart sshd
shutdown -r now
4 . 嘗試通過10022端口登錄SSH,或者進入該服務器直接本地訪問SSH如下:
[root@centos7 ~]#ssh root@localhost -p 10022
1
如果成功,說明10022已經完全可以使用了,接下來你就可以根據上述步驟把sshd_config的Port22注釋掉就OK了,大工造成
————————————————
centos7 SSH防暴力破解五種方法
什么是暴力破解,簡單來說就是對一個服務器進行無數次嘗試登陸,並用不同的密碼進行登陸直到可以登陸成功。暴力破解的基本步驟可以分為以下幾步:
- 找到對應的linux服務器 Ip地址
- 掃描端口號:22 nmap掃描端口
- 開始暴力破解 : 一般root 破解你的密碼 登錄你的機器 破壞 盜取你的重要的數據
對於這種情況我們有以下5種解決辦法:
- 將密碼設置復雜,長度大於8位或者最好大於14位,密碼的復雜度:由大小寫字母以及字符和數字組成。 0-9 a-z A-Z
@!#$%*. 等等。 - 更改端口號,默認的端口是sshd(22),修改默認端口號。
- 不用root用戶登陸(禁止root用戶登陸),使用其他用戶登陸並且擁有root用戶權限。
- sshd服務,直接編寫腳本檢查/var/log/secure 內登錄失敗次數超過某個閾值的ip並將它添加到/etc/hosts.deny(fail2ban的優點更多)
- 使用fail2ban,起到登錄失敗多次后直接禁止某個時間段此ip登陸。
方法一
收集 /var/log/secure 里面的信息,若是某個IP 鏈接次數超過一定次數 ,則把此ip記錄到/etc/hosts.deny里面。
先把始終允許的IP填入 /etc/hosts.allow這很重要!比如:
sshd:19.16.18.1:allow
sshd:19.16.18.2:allow
vi /usr/local/bin/secure_ssh.sh
創建腳本
#! /bin/bash
cat /var/log/secure|awk '/Failed/{print $(NF-3)}'|sort|uniq -c|awk '{print $2"="$1;}' > /usr/local/bin/black.list
for i in `cat /usr/local/bin/black.list`
do
IP=`echo $i |awk -F= '{print $1}'`
NUM=`echo $i|awk -F= '{print $2}'`
if [ ${#NUM} -gt 1 ]; then
grep $IP /etc/hosts.deny > /dev/null
if [ $? -gt 0 ];then
echo "sshd:$IP:deny" >> /etc/hosts.deny
fi
fi
done
通過crontab來執行,每天的1點1分執行一次。
crontab -e
1 * * * * sh /usr/local/bin/secure_ssh.sh
方法二
Denyhosts是一個由Linux系統管理員運行,用來阻止SSH服務器攻擊的python腳本(參考:Denyhosts官網http://denyhosts.sourceforge.net/)。
在服務器安全日志(Centos:/var/log/secure;Ubutun:/var/log/auth.log)里,可以查看到訪問服務器的記錄。在受到不明IP多次訪問時,我們可以通過將允許訪問的IP添加至系統白名單(/etc/hosts.allow),或者將禁止的IP添加到黑名單(/etc/hosts.deny),來限制訪問服務器的IP;但是攻擊者一般都是通過不同IP對服務器進行訪問,這樣就對阻止攻擊造成很大的麻煩。Dneyhosts就是一個自動查看分析安全日志,將符合設定禁止條件的IP添加到/etc/hosts.deny的腳本程序。
下載后安裝:
python setup.py install
源碼里面有個README.md 文件說明了用法。
vim /etc/denyhosts.conf
SECURE_LOG = /var/log/secure ( denyhosts.conf默認不是這個,我們用的centos要修改這行)
#ssh 日志文件,它是根據這個文件來判斷的。
HOSTS_DENY = /etc/hosts.deny
#控制用戶登陸的文件
# never purge:
PURGE_DENY = (默認是這個,我們改成下面的)
PURGE_DENY = 10m
#過 多久后清除已經禁止的
#
# PURGE_DENY: removed HOSTS_DENY entries that are older than this time
# when DenyHosts is invoked with the --purge flag
#
# format is: i[dhwmy]
# Where 'i' is an integer (eg. 7)
# 'm' = minutes
# 'h' = hours
# 'd' = days
# 'w' = weeks
# 'y' = years
#
BLOCK_SERVICE = sshd
#禁止 的服務名
DENY_THRESHOLD_INVALID = 1
#允許無 效用戶失敗的次數
DENY_THRESHOLD_VALID = 10
#允 許普通用戶登陸失敗的次數
DENY_THRESHOLD_ROOT = 5
#允 許root登陸失敗的次數
HOSTNAME_LOOKUP=NO
#是 否做域名反解
ADMIN_EMAIL = iakuf@163.com
#管 理員郵件地址,它會給管理員發郵件
DAEMON_LOG = /var/log/denyhosts
#自己的日志文件
Next, if you intend to run DenyHosts in daemon mode (recommended)
copy the sample daemon-control.dist script as such:
# cp daemon-control-dist daemon-control
Edit the daemon-control file. You should only need to edit this section
near the top:
###############################################
#### Edit these to suit your configuration ####
###############################################
DENYHOSTS_BIN = "/usr/bin/denyhosts.py"
DENYHOSTS_LOCK = "/var/lock/subsys/denyhosts"
DENYHOSTS_CFG = "/etc/denyhosts.conf"
These defaults should be reasonable for many systems. You
should customize these settings to match your particular
system.
Once you have edited the configuration and daemon control files
make sure that the daemon control script it executable (by root).
# chown root daemon-control
# chmod 700 daemon-control
Starting DenyHosts Manually
===========================
Assuming you have configured DenyHosts to run as a daemon, you
can use the daemon-control script to control it:
# daemon-control start
You should refer to the daemon log (typically /var/log/denyhosts)
to ensure that DenyHosts is running successfully. If you
notice any problems you may wish to consult the FAQ at
http://www.denyhosts.net/faq.html
If you wish to run DenyHosts from cron rather than as a
daemon, please refer to the FAQ.
Starting DenyHosts Automatically
================================
Method 1 (preferred)
--------------------
Create a symbolic link from /etc/init.d such as:
# cd /etc/init.d
# ln -s /usr/share/denyhosts/daemon-control denyhosts
If you have chkconfig installed you can then use it to
ensure that DenyHosts runs at boot time:
# chkconfig --add denyhosts
If you do not have chkconfig (or similar) installed you can either manually
create the symlinks in /etc/rc2.d, /etc/rc3.d, /etc/rc5.d but that is beyond
the scope of this document.
我們在上面的繼續操作:
chkconfig denyhosts on
chkconfig --list 可以看到右denyHosts說明成功了。
啟動:
service denyhost start
可以看看/etc/hosts.deny內是否有禁止的IP,有的話說明已經成功了。
我運行了一下,看到了一個最近嘗試登陸被禁止的ip:
cat /etc/hosts.deny
#
# hosts.deny This file contains access rules which are used to
# deny connections to network services that either use
# the tcp_wrappers library or that have been
# started through a tcp_wrappers-enabled xinetd.
#
# The rules in this file can also be set up in
# /etc/hosts.allow with a 'deny' option instead.
#
# See 'man 5 hosts_options' and 'man 5 hosts_access'
# for information on rule syntax.
# See 'man tcpd' for information on tcp_wrappers
#
sshd: 121.46.1.145
~
(簡單部署的幾行命令:
mv /usr/bin/denyhosts.py /usr/sbin/denyhosts
mv /usr/bin/daemon-control-dist /etc/init.d/denyhosts
cd /etc/init.d
chkconfig --add denyhosts
chkconfig denyhosts on
vim /etc/denyhosts.conf 修改SECURE_LOG位置
service denyhosts start
denyhost檢測進程是否在運行寫的非常好,可以借鑒:
#!/usr/bin/python # denyhosts Bring up/down the DenyHosts daemon # # chkconfig: 2345 98 02 # description: Activates/Deactivates the # DenyHosts daemon to block ssh attempts # ############################################### ############################################### #### Edit these to suit your configuration #### ############################################### DENYHOSTS_BIN = "/usr/sbin/denyhosts" DENYHOSTS_LOCK = "/run/denyhosts.pid" DENYHOSTS_CFG = "/etc/denyhosts.conf" PYTHON_BIN = "/usr/bin/env python" ############################################### #### Do not edit below #### ############################################### DENYHOSTS_BIN = "%s %s" % (PYTHON_BIN, DENYHOSTS_BIN) import os, sys, signal, time # make sure 'ps' command is accessible (which should be # in either /usr/bin or /bin. Modify the PATH so # popen can find it env = os.environ.get('PATH', "") os.environ['PATH'] = "/usr/bin:/bin:%s" % env STATE_NOT_RUNNING = -1 STATE_LOCK_EXISTS = -2 def usage(): print "Usage: %s {start [args...] | stop | restart [args...] | status | debug | condrestart [args...] }" % sys.argv[0] print print "For a list of valid 'args' refer to:" print "$ denyhosts.py --help" print sys.exit(0) def getpid(): try: fp = open(DENYHOSTS_LOCK, "r") pid = int(fp.readline().rstrip()) fp.close() except Exception, e: return STATE_NOT_RUNNING if not sys.platform.startswith('freebsd') and os.access("/proc", os.F_OK): # proc filesystem exists, look for pid if os.access(os.path.join("/proc", str(pid)), os.F_OK): return pid else: return STATE_LOCK_EXISTS else: # proc filesystem doesn't exist (or it doesn't contain PIDs), use 'ps' p = os.popen("ps -p %d" % pid, "r") p.readline() # get the header line pid_running = p.readline() # pid_running will be '' if no process is found if pid_running: return pid else: return STATE_LOCK_EXISTS def start(*args): cmd = "%s --daemon " % DENYHOSTS_BIN if args: cmd += ' '.join(args) print "starting DenyHosts: ", cmd os.system(cmd) def stop(): pid = getpid() if pid >= 0: os.kill(pid, signal.SIGTERM) print "sent DenyHosts SIGTERM" else: print "DenyHosts is not running" def debug(): pid = getpid() if pid >= 0: os.kill(pid, signal.SIGUSR1) print "sent DenyHosts SIGUSR1" else: print "DenyHosts is not running" def status(): pid = getpid() if pid == STATE_LOCK_EXISTS: print "%s exists but DenyHosts is not running" % DENYHOSTS_LOCK elif pid == STATE_NOT_RUNNING: print "Denyhosts is not running" else: print "DenyHosts is running with pid = %d" % pid def condrestart(*args): pid = getpid() if pid >= 0: restart(*args) def restart(*args): stop() time.sleep(1) start(*args) if __name__ == '__main__': cases = {'start': start, 'stop': stop, 'debug': debug, 'status': status, 'condrestart': condrestart, 'restart': restart} try: args = sys.argv[2:] except Exception: args = [] try: # arg 1 should contain one of the cases above option = sys.argv[1] except Exception: # try to infer context (from an /etc/init.d/ script, perhaps) procname = os.path.basename(sys.argv[0]) infer_dict = {'K': 'stop', 'S': 'start'} option = infer_dict.get(procname[0]) if not option: usage() try: if option in ('start', 'restart', 'condrestart'): anystartswith = lambda prefix, xs: any(map(lambda x: x.startswith(prefix), xs)) if not anystartswith('--config', args) and '-c' not in args: args.append("--config=%s" % DENYHOSTS_CFG) cmd = cases[option] apply(cmd, args) except Exception: usage()
denyhosts 解鎖ip:
命令幫助中提供了denyhosts.py --purgeip
命令,看含義應該是解封指定Ip。但運行命令會報錯:[Errno 2] No such file or directory
需要先切換到/var/lib/denyhosts/這個文件夾下,
查找出當前文件夾以及子目錄中,哪些文件包含有字符串內容。
然后在vim打開后,找到所在行,dd刪除所在行。
cd /var/lib/denyhosts/
grep -rn "目標ip" *
然后用sed命令刪除。
也要把/var/log/secure中的ip刪除。
sed命令常用到的兩個選項:
-i : 直接在文件上編輯 (edit files in place)
-e[默認選項]:只在命令行輸出,而文件不改變
(add the script to the commands to be executed)
注:使用sed命令可以使用 -i 或者 -e 選項(以下例子僅以-i舉例)
sed命令刪除包含特定字符行
刪除包含"xxx"的行
sed -i '/xxx/d' filename
會把查找到xxx都刪除所在行。
1 sed -i '/ip/d' `ls`
2 sed -i '/ip/d' /var/log/secure
denyhosts徹底解禁步驟:
1. 刪除/etc/hosts.deny對應行
2. 進入/var/lib/denyhosts/這個文件夾,
執行: sed -i '/ip/d' /var/log/secure 這個ip換成解禁的對應的ip
3. 清空 /var/log/secure
4。如果上面步驟還不行,重啟系統,有一次就是沒有重啟系統,按照上面步驟做了幾次都不行,結果重啟下就可以了。