2025年7月20日 星期日

Mapleboard MP510-50 測試 (三十四) : 更改 SSH 通訊埠之埠號

今天繼續修改 Fail2ban 設定來強化主機安全性, 本篇測試旨在更改 Mapleboard SSH 通訊埠埠號, 由預設的 22 改為 2222. 

本系列全部的測試紀錄參考 :
將 SSH 埠號從預設的 22 改為其他非標準埠 (例如 2222), 這種做法稱為 "透過模糊化提升安全性", 可以在一定程度上減少自動掃描與暴力破解的攻擊次數, 優點如下 : 
  • 降低被掃描頻率 :
    大多數惡意機器人與腳本程式通常會集中攻擊 22 埠, 改用非標準埠例如 2222 埠會使主機避開大部分低階攻擊. 
  • 減少 Fail2Ban 負擔 :
    因為暴力破解頻率降低了, fail2ban 就不用頻繁寫入封鎖紀錄, 可節省系統資源. 
但修改 SSH 埠號無法完全防止入侵. 有心的攻擊者會利用通訊埠掃描工具 (例如 nmap) 輕易地找出主機所使用的 SSH 埠. 

修改 SSH 通訊埠號程序如下 :


1. 修改 SSH 設定檔 : 

先用 cat 檢視 SSH 的設定檔 /etc/ssh/sshd_config : 

tony1966@LX2438:~$ cat /etc/ssh/sshd_config    

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.

Include /etc/ssh/sshd_config.d/*.conf

#Port 22       #  在底下新增 Port 2222 明確指定 SSH 使用 2222 埠
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_ecdsa_key
#HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
#RekeyLimit default none

# Logging
#SyslogFacility AUTH
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
#PermitRootLogin prohibit-password
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

#PubkeyAuthentication yes

# Expect .ssh/authorized_keys2 to be disregarded by default in future.
#AuthorizedKeysFile .ssh/authorized_keys .ssh/authorized_keys2

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
KbdInteractiveAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the KbdInteractiveAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via KbdInteractiveAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and KbdInteractiveAuthentication to 'no'.
UsePAM yes

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
PrintMotd no
#PrintLastLog yes
#TCPKeepAlive yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS no
#PidFile /run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

# override default of no subsystems
Subsystem sftp /usr/lib/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
# X11Forwarding no
# AllowTcpForwarding no
# PermitTTY no
# ForceCommand cvs server

用 nano 編輯 sshd 設定檔 : 

sudo nano /etc/ssh/sshd_config  

tony1966@LX2438:~$ sudo nano /etc/ssh/sshd_config   
[sudo] tony1966 的密碼: 

在底下 #Port 22 新增 Port 2222 明確指定 SSH 使用 2222 埠 (或直接將 22 改成 2222) : 




按 Ctrl+O 存檔後按 Ctrl+X 跳出 nano 即可. 


2. UFW 防火牆開啟 2222 埠 : 

這步非常重要必須先下, 如果先刪除 22 埠那 SSH 就連不進來了, 指令如下 :

sudo ufw allow 2222/tcp    

tony1966@LX2438:~$ sudo ufw allow 2222/tcp  
已添加規則
已添加規則 (v6)

檢視防火牆狀態 :

tony1966@LX2438:~$ sudo ufw status verbose   
狀態: 啓用
日誌: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
新建設定檔案: skip

至                          動作          來自
-                          --          --
22/tcp                     ALLOW IN    Anywhere                  
80/tcp                     ALLOW IN    Anywhere                  
443/tcp                    ALLOW IN    Anywhere                  
2222/tcp                   ALLOW IN    Anywhere                  
22/tcp (v6)                ALLOW IN    Anywhere (v6)             
80/tcp (v6)                ALLOW IN    Anywhere (v6)             
443/tcp (v6)               ALLOW IN    Anywhere (v6)     
2222/tcp (v6)              ALLOW IN    Anywhere (v6)    

可見 2222 埠已開啟.


3. 暫時允許 22/2222 雙埠重新啟動 SSH 服務 : 

在確保新埠 2222 能順利連入之前, 不要馬上移除原本的 22 port 規則 : 

sudo systemctl restart ssh   

tony1966@LX2438:~$ sudo systemctl restart ssh   


4. 用 Putty 測試 2222 埠是否可連線 : 

開啟 Putty, 將 port 設為 2222 開啟連線, 確認可順利登入 : 


 


用 HTmail 帳密可以登入, 就可以封鎖 22 埠了.


5. UFW 防火牆移除 22 埠 : 

用下列指令關閉 22 埠 :

sudo ufw delete allow 22/tcp   

tony1966@LX2438:~$ sudo ufw delete allow 22/tcp  
已刪除規則
已刪除規則 (v6)

檢視防火牆狀態 :

tony1966@LX2438:~$ sudo ufw status verbose   
狀態: 啓用
日誌: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
新建設定檔案: skip

至                          動作          來自
-                          --          --
80/tcp                     ALLOW IN    Anywhere                  
443/tcp                    ALLOW IN    Anywhere                  
2222/tcp                   ALLOW IN    Anywhere                  
80/tcp (v6)                ALLOW IN    Anywhere (v6)             
443/tcp (v6)               ALLOW IN    Anywhere (v6)     
2222/tcp (v6)              ALLOW IN    Anywhere (v6)    

可見 22 埠已經被封鎖. 再次重啟 ssh 服務 : 

tony1966@LX2438:~$ sudo systemctl restart ssh   


6. 更新 Fail2Ban 的 SSH jail 設定 : 

用下列指令編輯 Fail2ban 的設定檔 jail.local, 修改 sshd 的監控規則 : 

sudo nano /etc/fail2ban/jail.local   

tony1966@LX2438:~$ sudo nano /etc/fail2ban/jail.local   

將其中的 port 參數從原先的 ssh 或 22 改為 2222 : 

port = 2222

另外在 sshd 區段末尾添加下面這一行 : 

action = %(action_mwl)s  

這是 fail2ban 預設模板中一個內建的動作縮寫, 此動作有如下作用 : 
  • 封鎖企圖暴力破解的 IP (保護 2222 埠)
  • 記錄封鎖事件到 /var/log/fail2ban.log 日誌檔
  • 發送郵件通知 (需在 DEFAULT 區段配置 mta 和 destemail)
然後在 [sshd] 區段底下 (註 : 錯誤, 是上面, 見底下補充說明) 新增一個 [DEFAULT] 區段, 設定寄件者與收件者 :

[DEFAULT]
mta = postfix
destemail = yhhuang1966@gmail.com
sender = fail2ban@tony1966.cc




按 Ctrl+O 存檔後按 Ctrl+X 跳出 nano. 

然後重啟 Fail2Ban :

sudo systemctl restart fail2ban   

tony1966@LX2438:~$ sudo systemctl restart fail2ban   


7. 檢查目前 SSH Daemon 是否使用 2222 : 

用下列指令檢查目前 SSH Daemon 是否使用 2222 :

sudo ss -tnlp | grep sshd    

tony1966@LX2438:~$  sudo ss -tnlp | grep sshd   
LISTEN 0      128          0.0.0.0:2222      0.0.0.0:*    users:(("sshd",pid=604384,fd=3))                              
LISTEN 0      128             [::]:2222         [::]:*    users:(("sshd",pid=604384,fd=4))      

此處 0.0.0.0:2222 表示監聽所有 IPv4 網卡上的 2222 埠; 而 [::]:2222 則是監聽所有 IPv6 網卡上的 2222 埠, 這樣就確認了以上操作已成功地將 SSH 監聽埠號改為 2222, 且 SSH 服務也已正常啟動並在預期的 IPv4 和 IPv6 埠號 2222 上監聽. 


2025-07-25 補充 :

上周末更新完 jail.local 後一直沒有收到監控資訊的 Email, 今天進入系統檢查, 發現 sshd 監控根本沒有載入 :

tony1966@LX2438:~$ sudo fail2ban-client status sshd   
2025-07-25 00:26:04,215 fail2ban [678576]: 
ERROR NOK: ('sshd',) Sorry but the jail 'sshd' does not exist 
tony1966@LX2438:~$ sudo fail2ban-client status     
Status |- Number of jail: 4 - Jail list: nginx-404, nginx-badbots, nginx-noscript, recidive

詢問 AI 才知原來 jail.local 中 DEFAULT 區塊應該放在 sshd 最前面才對 : 

[DEFAULT]
mta = postfix
destemail = yhhuang1966@gmail.com
sender = yhhuang1966@gmail.com

[sshd]
enabled = true
port = 2222
logpath = /var/log/auth.log
maxretry = 5
bantime = 1h
findtime = 10m
action = %(action_mwl)s

但即使順序弄對了還是不行. AI 建議將 action = %(action_mwl)s 改成 action = %(action_mw)s 或 action = %(action_)s 試試看, 測試結果如下 :

action = %(action_mwl)s  --> NG
action = %(action_mw)s  --> NG
action = %(action_)s  --> OK (5 個規則都有載入)

這個 action 用來設定預設的封鎖與通知方式, 來自於 /etc/fail2ban/action.d/ 目錄中定義的行為模板, 它們的差異在於是否寄信與包含 log 摘要內容, 這三種設定的差異如下 :

action = %(action_mwl)s  : 封鎖 IP + 寄信通知 + 包含違規 log 摘要
action = %(action_mw)s : 封鎖 IP + 寄信通知, 但不含違規 log 摘要內容
action = %(action_)s : 只封鎖 IP 不會寄信通知

我需要寄信通知, 前兩個設定會 NG 的原因可能是缺少 /etc/fail2ban/action.d/postfix-whois.conf 這個檔案, 我用 nano 建立了此檔 : 

tony1966@LX2438:~$ sudo nano /etc/fail2ban/action.d/postfix-whois.conf 

輸入如下內容 : 

[Definition]
actionstart =
actionstop =
actioncheck =
actionban = postfix[name=%(__name__)s, dest="%(destemail)s", sender="%(sender)s"]
actionunban =

重啟 Fail2ban 還是不行, AI 認為可能 Postfix 安裝或設定有問題, 需要重新安裝, 但建議將 jail.local 裡面的 mta 直接改為 sendmail 最快, 我使用 action = %(action_mw)s 搭配 mta=sendmail 果然就可以了, 完整的 jail.local 如下  :

tony1966@LX2438:~$ cat /etc/fail2ban/jail.local   
[DEFAULT]
mta = postfix
destemail = yhhuang1966@gmail.com
sender = yhhuang1966@gmail.com

[sshd]
enabled = true
port = 2222
logpath = /var/log/auth.log
maxretry = 5
bantime = 1h
findtime = 10m
action = %(action_)s

[nginx-404]
enabled = true
port = http,https
logpath = /var/log/nginx/access.log
maxretry = 10
findtime = 10m
bantime = 1h

[nginx-badbots]
enabled = true
port = http,https
logpath = /var/log/nginx/access.log
maxretry = 1
findtime = 1d
bantime = 1d

[nginx-noscript]
enabled = true
port = http,https
logpath = /var/log/nginx/access.log
maxretry = 3
findtime = 10m
bantime = 1h

[recidive]
enabled = true
logpath = /var/log/fail2ban.log
bantime = 86400       ; 1 天
findtime = 1d
maxretry = 5

檢視 Fail2ban 狀態 :

tony1966@LX2438:~$ sudo fail2ban-client status   
[sudo] tony1966 的密碼: 
Status
|- Number of jail: 5
`- Jail list: nginx-404, nginx-badbots, nginx-noscript, recidive, sshd

tony1966@LX2438:~$ sudo fail2ban-client status sshd   
[sudo] tony1966 的密碼: 
Status for the jail: sshd
|- Filter
|  |- Currently failed: 5
|  |- Total failed: 135
|  `- File list: /var/log/auth.log
`- Actions
   |- Currently banned: 0
   |- Total banned: 7
   `- Banned IP list:


可見 5 個監控規則都順利載入運行中, 而且馬上收到封鎖 IP 的 Email : 

Hi,

The IP 45.135.232.92 has just been banned by Fail2Ban after
5 attempts against sshd.


Here is more information about 45.135.232.92 :

% This is the RIPE Database query service.
% The objects are in RPSL format.
%
% The RIPE Database is subject to Terms and Conditions.
% See https://docs.db.ripe.net/terms-conditions.html

% Note: this output has been filtered.
%       To receive output for a database update, use the "-B" flag.

% Information related to '45.135.232.0 - 45.135.232.255'

% Abuse contact for '45.135.232.0 - 45.135.232.255' is 'mail@proton66.ru'

inetnum:        45.135.232.0 - 45.135.232.255
netname:        RU-PROTON66
country:        RU
org:            ORG-PL533-RIPE
admin-c:        PL14453-RIPE
tech-c:         PL14453-RIPE
status:         ASSIGNED PA
mnt-by:         IP-RIPE
created:        2023-03-31T20:14:04Z
last-modified:  2023-03-31T20:14:07Z
source:         RIPE

organisation:   ORG-PL533-RIPE
org-name:       Proton66 LLC
org-type:       OTHER
address:        pr-kt Iskrovskiy, d. 21YU, kv. 218
address:        193230 Saint Petersburg
address:        Russia
abuse-c:        PL14453-RIPE
mnt-ref:        IP-RIPE
mnt-by:         IP-RIPE
created:        2023-03-31T20:10:41Z
last-modified:  2023-03-31T20:10:41Z
source:         RIPE # Filtered

role:           Proton66 LLC
nic-hdl:        PL14453-RIPE
address:        pr-kt Iskrovskiy, d. 21YU, kv. 218
address:        193230 Saint Petersburg
address:        Russia
abuse-mailbox:  mail@proton66.ru
phone:          +7 999 5285271
mnt-by:         IP-RIPE
created:        2023-03-31T20:09:34Z
last-modified:  2023-03-31T20:10:30Z
source:         RIPE # Filtered

% Information related to '45.135.232.0/24AS198953'

route:          45.135.232.0/24
origin:         AS198953
mnt-by:         IP-RIPE
created:        2023-04-14T19:15:16Z
last-modified:  2023-04-14T19:15:16Z
source:         RIPE

% This query was served by the RIPE Database Query Service version 1.117 (DEXTER)

Regards,

Fail2Ban

大部分都是來自中國與俄羅斯的, 真是駭客之邦啊!

沒有留言 :