つばろぐ

主に C#, .NET, Azure の備忘録です。たまに日記。

CentOSのセキュリティ的な設定

自宅サーバCentOSで運用する際に行ったセキュリティ対策を備忘録としてまとめます。

何はともあれアップデート

[root@localhost ~]# yum -y update

作業ユーザの追加

root以外の作業ユーザを追加します。

[root@localhost ~]# useradd tsubaki
[root@localhost ~]# passwd tsubaki
ユーザー tsubaki のパスワードを変更。
新しいパスワード:
新しいパスワードを再入力してください:
passwd: 全ての認証トークンが正しく更新できました。

作業ユーザのsudoの使用を許可する

ユーザを追加しただけではsudoが使えないため、使えるようにします。

[root@localhost ~]# usermod -G wheel tsubaki        ←wheelグループにtsubakiを追加
[root@localhost ~]# visudo

## Allows people in group wheel to run all commands
# %wheel        ALL=(ALL)       ALL
↓
## Allows people in group wheel to run all commands
%wheel  ALL=(ALL)       ALL                         ←コメント(#)を外す

新たにターミナルを起動し、ユーザ:tsubakiでログインできれば、rootでログインしているターミナルは閉じましょう。

SELinuxiptablesのサービスを停止

ルータにてパケットフィルタを行なっているため、SELinuxiptablesのサービスを停止します。
パケットフィルタを設定していない環境ではファイアウォールを適切に設定して下さい。

[tsubaki@localhost ~]$ sudo setenfoce 0
[tsubaki@localhost ~]$ sudo vi /etc/sysconfig/selinux

SELINUX=enforcing
↓
SELINUX=disabled

[tsubaki@localhost ~]$ sudo /sbin/service iptables stop
iptables: ファイアウォールルールを消去中:                  [  OK  ]
iptables: チェインをポリシー ACCEPT へ設定中filter         [  OK  ]
iptables: モジュールを取り外し中:                          [  OK  ]
[tsubaki@localhost ~]$ sudo chkconfig iptables off
[tsubaki@localhost ~]$ sudo reboot

SSHのポート番号変更、rootでのログインを禁止、公開鍵認証の導入

通常SSHはポート22を使用しますが、別のポート番号を使用するよう変更しましょう。
またパスワード認証はやめ、公開鍵認証にてログインするよう変更しましょう。

[tsubaki@localhost ~]$ sudo vi /etc/ssh/sshd_config
[sudo] password for tsubaki:

#Port 22
↓
Port 10022

#PermitRootLogin yes
↓
PermitRootLogin no

#PubkeyAuthentication yes
↓
PubkeyAuthentication yes

PasswordAuthentication yes
↓
PasswordAuthentication no

SSHを再起動します。

[tsubaki@localhost ~]$ sudo /etc/init.d/sshd restart
sshd を停止中:                                             [  OK  ]
sshd を起動中:                                             [  OK  ]

公開鍵、秘密鍵の準備

ssh-keygenコマンドを実行すると公開鍵と秘密鍵を生成できます。
なおid_rsaが秘密鍵、id_rsa.pubが公開鍵です。秘密鍵はログイン時に使用するため失くさないようにして下さい。

[tsubaki@localhost ~]$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/tsubaki/.ssh/id_rsa):
Created directory '/home/tsubaki/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/tsubaki/.ssh/id_rsa.
Your public key has been saved in /home/tsubaki/.ssh/id_rsa.pub.

[tsubaki@localhost ~]$ cd ~/.ssh/
[tsubaki@localhost .ssh]$ ls
id_rsa  id_rsa.pub

公開鍵のファイル名と、ディレクトリと公開鍵の権限を変更しましょう。

[tsubaki@localhost .ssh]$ mv id_rsa.pub authorized_keys
[tsubaki@localhost .ssh]$ sudo chmod 700 .
[tsubaki@localhost .ssh]$ sudo chmod 600 authorized_keys

新たにターミナルを起動し、公開鍵認証でログインできるか確認してみましょう。