创建Linux服务器后进行的安全设置备忘录(随时更新)
首先
每次创建Linux服务器后,我经常会忘记执行与安全相关的设置,并在后来意识到存在漏洞时感到惊恐。因此,在以下我将做出备忘录。(随时更新)
环境
-
- Ubuntu 18.04 LTS
- CentOS 7
更新已安装的软件包
$ sudo apt-get update
$ sudo apt-get upgrade
$ yum update
更改根目录和用户密码
在使用云服务虚拟控制台时,建议至少包含一个英文大写字母、小写字母、数字和符号,且密码长度最好为8个字符以上。
$ sudo passwd root
$ sudo passwd user
禁用Root(默认帐户)的shell。
请在执行以下操作之前确保至少有一个账号拥有sudo权限。
$ cat /etc/group
(sudo権限を付与する場合)
$ usermod -G wheel user
- rootのシェル状態確認(有効状態)
$ cat /etc/passwd | grep root
root:x:0:0:root:/root:/bin/bash
- nologinのありかを探す
$ where nologin
/usr/sbin/nologin
- root(デフォルトアカウント)のシェル無効化
$ usermod -s /usr/sbin/nologin root
$ cat /etc/passwd | grep root
root:x:0:0:root:/root:/usr/sbin/nologin
$ su -
This account is currently not available.
SSH相关设置
公開密钥认证的设置
- 鍵作成
$ ssh-keygen -t rsa -b 4096
- 鍵の置き場作成
$ cd
$ mkdir .ssh
$ chmod 700 .ssh/
$ touch .ssh/authorized_keys
$ chmod 600 .ssh/authorized_keys
- 鍵送信
$ cat ~/.ssh/id_rsa.pub | ssh user@xxx.xxx.xxx.xxx 'cat >> .ssh/authorized_keys'
- 公開鍵認証のよるSSHアクセス確認
$ ssh user@xxx.xxx.xxx.xxx -i .ssh/id_rsa -v
请务必在之后使用密钥认证登录成功后,确认禁用密码认证。
重新审视SSH服务器的配置
$ vi /etc/ssh/sshd_config
- SSHをLISTENするポート番号の変更
- #Port 22
+ Port 22222
- SSHをLISTENするIPを限定(複数NICの場合)
- #ListenAddress 0.0.0.0
+ ListenAddress xxx.xxx.xxx.xxx
- rootのログイン禁止
- #PermitRootLogin yes
+ PermitRootLogin no
- パスワード認証の禁止
- #PasswordAuthentication yes
+ PasswordAuthentication no
- パスワードなしでの認証禁止
- #PermitEmptyPasswords no
+ PermitEmptyPasswords no
- (CentOSの場合)SELinuxの設定変更
$ getenforce
Enforcing
$ yum install policycoreutils-python
$ which semanage
/usr/sbin/semanage
$ /usr/sbin/semanage port --list | grep ssh
ssh_port_t tcp 22
$ /usr/sbin/semanage port --add --type ssh_port_t --proto tcp 22222
$ /usr/sbin/semanage port --list | grep ssh
ssh_port_t tcp 22222,22
- (CentOSの場合)firewalldの設定変更
$ firewall-cmd --permanent --remove-service=ssh
$ cp /usr/lib/firewalld/services/ssh.xml /etc/firewalld/services/ssh-22222.xml
$ vi /etc/firewalld/services/ssh-22222.xml
- <port protocol="tcp" port="22"/>
+ <port protocol="tcp" port="22222"/>
$ firewall-cmd --permanent --add-service=ssh-22222
$ firewall-cmd --reload
$ firewall-cmd --list-all
- 設定変更したらSSHプロセスを再起動
$ systemctl restart sshd
$ systemctl status sshd
请确认是否有任何多余的端口打开。
从内部进行确认
- 接続待ちをしているTCP、UDPポートを表示
※1 请确认 LISTEN 端口在哪里打开(本地地址:端口)
※2 请确认 ESTAB 端口正在与哪里连接(对等地址:端口)
$ ss -antu
$ netstat -antu
用外部工具(如nmap)进行确认。
- フルスキャン(時間かかるので注意)
$ nmap -p 1-65535 xxx.xxx.xxx.xxx
- ウェルノウンポートスキャン
$ nmap -p 0-1023 xxx.xxx.xxx.xxx
- UDPスキャン
$ nmap -sU xxx.xxx.xxx.xxx