LoginSignup
3
2

CentOS7をインストールした直後に行う初期設定

Last updated at Posted at 2022-06-16

インフラ初心者が纏めているため、信用しないでください。この記事を参考にセットアップしたことによって被った損害・損失に対し、いかなる場合でも一切の責任を負いませんのでご了承ください。あくまでも自己責任でお願いします。CentOS は VPS のコンソール画面から最小限インストールをしています。

ここでは、ウェブサーバーや PHP などのプラグラムをインストールする前に必要なCentOSの初期設定をまとめています。

root アカウントのパスワードの変更

root でログインします。

$ passwd

passwd は現在のユーザーのパスワードを変更するコマンドです。

CentOS のアップデートとアップグレード

$ yum clean all && \
yum -y update && \
yum clean all && \
yum -y upgrade && \
yum clean all && \
cat /etc/redhat-release

開発ツールなどを、グループインストールする

wgetgit をはじめ、開発などで使用するパッケージをグループインストールする。
CentOS7 では不要な、net-tool などもインストールされてしまうが、気になるようであれば、個別に remove する。

$ yum -y groupinstall "base" && \
yum -y groupinstall "Development tools"

言語確認

CentOS7 では、ロケールの設定内容の確認や変更は localectl コマンドを使用します。
また、CentOS6 までは yum -y groupinstall "Japanese Support" のコマンドで日本語環境を整えていましたが、これらは不要です。

現在のロケール設定を確認する例を、以下に示します。

$ localectl status

すると、以下のように表示されます。

   System Locale: LANG=ja_JP.UTF-8
       VC Keymap: jp
      X11 Layout: jp

利用可能なロケール一覧を確認する

$ localectl list-locales

利用可能な日本語ロケールの一覧を確認する

$ localectl list-locales | grep -i ja

使用ロケールを変更する

以下に、ja_JP.eucjp へ変更する例。

$ localectl set-locale LANG=ja_JP.eucjp

設定を反映させる。

$ source /etc/locale.conf

キーボードマッピングの変更

$ localectl set-keymap jp && \
sudo vi /etc/default/grub

GRUB_CMDLINE_LINUX 定数の vconsole.keymap を書き換える。

GRUB_CMDLINE_LINUX="rd.lvm.lv=centos/root rd.lvm.lv=centos/swap crashkernel=auto vconsole.keymap=ja rhgb quiet"

X11 Layout を変更する。

$ vi /etc/X11/xorg.conf.d/00-keyboard.conf

Option "XkbLayout" "**"** の部分を書き換える。

再起動させる。

$ reboot

リポジトリを追加する

1つのリポジトリで全てのソフトウェアが提供されていれば面倒はないのですが、現状はそうではありません(きっと何か理由があるのでしょう。)。そのため、いくつかのサードパーティのリポジトリを追加していきます。

Epel と Remi と okay のリポジトリを追加する

$ rpm --import http://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-7 && \
rpm -ivh http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm && \
rpm --import http://rpms.remirepo.net/RPM-GPG-KEY-remi && \
rpm -ivh http://ftp.riken.jp/Linux/remi/enterprise/remi-release-7.rpm && \
rpm --import http://apt.sw.be/RPM-GPG-KEY.dag.txt && \
rpm -ivh http://repo.okay.com.mx/centos/7/x86_64/release/okay-release-1-5.el7.noarch.rpm && \
rpm --import https://yum.mariadb.org/RPM-GPG-KEY-MariaDB && \
vi /etc/yum.repos.d/mariadb.repo

一部のリポジトリを初期で無効化します。無効化したリポジトリから何かをインストールしたい場合は、yum コマンドに --enablerepo オプションを追加して yum コマンドを実行します。

$ sed -i 's/enabled=1/enabled=0/g' /etc/yum.repos.d/epel.repo && \
sed -i 's/enabled=1/enabled=0/g' /etc/yum.repos.d/remi.repo && \
sed -i 's/enabled=1/enabled=0/g' /etc/yum.repos.d/remi-safe.repo

Epel から clam を対象外にします。

$ vi /etc/yum.repos.d/epel.repo

下記を追加します。

[epel]
exclude=clam*

CentOS 7 パッケージ管理(yum)

H2O のリポジトリを追加する

2022/04 にリポジトリが消滅しました
詳細: https://github.com/tatsushid/h2o-rpm/issues/10

Nginx のリポジトリを追加する

$ vi /etc/yum.repos.d/nginx.repo

下記をペーストします。

[nginx]
name=nginx
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=0
enabled=0

MariaDB のリポジトリを追加する

この作業は、MariaDB のバージョンが古い場合だけにします。

rpm --import https://yum.mariadb.org/RPM-GPG-KEY-MariaDB && \
vi /etc/yum.repos.d/mariadb.repo

下記をペーストします。

[mariadb]
name=mariadb
baseurl=http://yum.mariadb.org/10.2.1/centos$releasever-$basearch
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1
enabled=0

最初にインストールするソフトウェア

$ yum -y install vim-enhanced logwatch denyhosts yum-cron && \
yum --enablerepo=epel -y install rkhunter clamav clamav-update

Clam AntiVirus の設定(ウィルス対策ソフト)

オープンソースで開発・運用されているウィルス対策ソフト。

インストール

$ yum -y install --enablerepo=epel clamav clamav-update

設定ファイルを編集

$ mv /etc/freshclam.conf /etc/freshclam.conf.old && \
/etc/freshclam.conf

以下をペースト。

##
## Example config file for freshclam
## Please read the freshclam.conf(5) manual before editing this file.
##

UpdateLogFile /var/log/freshclam.log
LogTime yes
LogSyslog yes
LogRotate yes
PidFile /var/run/freshclam.pid
DatabaseOwner root
DatabaseMirror database.clamav.net
NotifyClamd /etc/clamd.d/scan.conf

設定ファイルを編集 2

$ mv /etc/clamd.d/scan.conf /etc/clamd.d/scan.conf.old && \
vi /etc/clamd.d/scan.conf

以下をペースト。

##
## Example config file for the Clam AV daemon
## Please read the clamd.conf(5) manual before editing this file.
##

LogFile /var/log/clamd.scan
LogTime yes
LogSyslog yes
LogRotate yes
PidFile /var/run/clamd.scan/clamd.pid
LocalSocket /var/run/clamd.scan/clamd.sock
FixStaleSocket yes
User root
ExcludePath ^/proc/
ExcludePath ^/sys/

スケジュール設定

1 時間に 1 回スキャンされる。

$ vi /etc/cron.hourly/clamd

下記をペースト。

#!/bin/bash

PATH=/usr/bin:/bin

# ClamAV update process
freshclam --quiet

# Virus scan
CLAMSCANTMP=`mktemp`
clamscan --recursive --remove / > ${CLAMSCANTMP} /dev/null 2>&1
[ ! -z "$(grep FOUND$ ${CLAMSCANTMP})" ] && \

# When detect virus, send mail
grep FOUND$ $CLAMSCANTMP | /bin/mail -s "Virus Found in `hostname`" root
rm -f ${CLAMSCANTMP}

実行権限を付与。

$ chmod +x /etc/cron.hourly/clamd

CPU 使用率 / メモリー使用率の上限を設定

$ /usr/lib/systemd/system/clamd@.service

Service ディレクティブの末尾に以下を追加。

MemoryLimit=512M
CPUQuota=30%

デーモンを再読み込みする。

$ systemctl daemon-reload
$ systemctl restart clamd@scan

RKHunter の設定(Rootkit 検出ツール)

設定ファイルを変更します。

$ vi /etc/sysconfig/rkhunter

変更が必要であれば変更します。保存後、データベースをアップデートします。

$ rkhunter --update

次にシステムのファイル情報をアップデートします。

$ rkhunter --propupd

スキャンを実行します。

$ rkhunter -c -sk

スケジュール設定

1 日に 1 回スキャンされる。

$ mv vi /etc/cron.daily/rkhunter vi /etc/cron.daily/rkhunter.old && \
vi /etc/cron.daily/rkhunter

下記をペースト。

#!/bin/bash

MAIL_TO=root
MAIL_SUBJECT="`hostname -s` `date +%Y%m%d_%H-%M-%S` Rootkit Hunter"
LOG_FILE=`mktemp /tmp/rkhunter.temp.XXXXXX`
/bin/rkhunter --update > /dev/null 2>&1
/bin/rkhunter --check --skip-keypress --cronjob --report-warnings-only 2>&1 > ${LOG_FILE}
if [ -s ${LOG_FILE} ]; then
    grep Warning ${LOG_FILE} | mail -s "$MAIL_SUBJECT NG" $MAIL_TO
else
    echo "$MAIL_SUBJECT OK" |  mail -s "$MAIL_SUBJECT OK" $MAIL_TO
fi
rm -f ${LOG_FILE}

実行権限を付与。

$ chmod +x /etc/cron.daily/rkhunter

Logwatch の設定(ログ監視ツール)

設定ファイルを作成します。

$ cat /usr/share/logwatch/default.conf/logwatch.conf >> /etc/logwatch/conf/logwatch.conf && \
vi /etc/logwatch/conf/logwatch.conf

変更が必要であれば変更します。

ログを確認する

Command Logfile Description
last /var/log/wtmp ログイン/ログアウトの履歴
lastb /var/log/btmp 不正ログインの試行履歴
lastlog /var/log/lastlog 最新のログイン
cat /var/log/secure | grep sshd /var/log/secure SSHの履歴

Denyhosts の設定(SSH のブルートフォース攻撃対策)

設定ファイルを変更します。

$ vi /etc/denyhosts.conf

変更が必要であれば変更します。以下にいくつかピックアップしておきます。

PURGE_DENY=4w            # 拒否を解除するまで期間
DENY_THRESHOLD_INVALID=1 # 存在しないユーザでのログイン試行回数
DENY_THRESHOLD_VALID=3   # 存在するユーザでのログイン試行回数
DENY_THRESHOLD_ROOT=1    # rootのログイン試行回数

次にホワイトリストを設定します。

$ vi /var/lib/denyhosts/allowed-hosts

ブロックされた IP アドレスを削除したい場合は

$ vi /etc/hosts.deny

を編集します。設定が完了したら、サービス登録し起動させます。

$ systemctl enable denyhosts && \
systemctl start denyhosts

yum-cron の設定(yum update 自動化)

yum-updateonboot がインストールされている場合は、停止させます。

$ systemctl stop yum-updateonboot.service && \
systemctl disable yum-updateonboot.service

設定ファイルを変更します。

$ vi /etc/yum/yum-cron.conf

ダウンロードとインストールを自動化するため、apply_updatesyes にします。

apply_updates = yes

次に自動でアップデートさせたくないをソフトウェアを指定します。

$ vi /etc/yum.conf

下記をペーストします(任意に追加・削除)。

[main]
exclude=gcc* kde* openssh* kernel* php* mysql*

yum-cron のバグ対策のために、プログラムの一部を改変します。

$ vi /usr/sbin/yum-cron

以下のように変更します。

# Build up the email to be sent
msg = MIMEText(''.join(self.output))

# Build up the email to be sent
# msg = MIMEText(''.join(self.output))
msg = MIMEText(''.join(self.output),_charser='utf-8')

保存後、サービス登録し起動させます。

$ systemctl enable yum-cron && \
systemctl start yum-cron

Vim の設定

$ mv /bin/vi /bin/vim-tiny && \
ln -s /usr/bin/vim /bin/vi

エイリアスを追加

$ vi /etc/bashrc
# alias
alias vi="vim"

$ source /etc/bashrc

行番号を表示

$ vi /etc/vimrc

下記を追加。

set number

/etc/vimrc はシステム設定なので、行番号を表示を追加くらいに留めておくのがよいと思います。設定ファイルの場所は以下の通り。

   システム vimrc: "/etc/vimrc"
    ユーザ vimrc: "$HOME/.vimrc"
第 2 ユーザ vimrc: "~/.vim/vimrc"
     ユーザ exrc: "$HOME/.exrc"

SELinux を無効化

$ setenforce 0 && \
sed -i "s/^SELINUX\=enforcing/SELINUX\=disabled/g" /etc/selinux/config

ユーザーとグループを作成する

作業用ユーザーに加えて、H2O、Nginx のユーザーを追加しています。

$ groupadd h2o && \
useradd -g h2o -s /sbin/nologin -d /opt/h2o h2o && \
groupadd nginx && \
useradd -g nginx -s /sbin/nologin -d /opt/nginx nginx && \
useradd exampleuser && \
passwd exampleuser && \
gpasswd -a exampleuser wheel && \
gpasswd -a exampleuser h2o && \
gpasswd -a exampleuser nginx

グループ一覧を確認する

$ getent group

ユーザーが所属しているグループを確認する

$ groups exampleuser

ユーザー一覧を確認する

$ cat /etc/passwd|sed -e 's/:.*//g'

作業用ユーザーの公開鍵と秘密鍵を作成する

ローカル PC で、秘密鍵と公開鍵のペアキーを作成します。以下の例は Mac を使用して作成した例です。
※ conoha の部分は適当に読み替えてください。

# 秘密鍵を生成
$ openssl genrsa -des3 -out ~/.ssh/conoha_rsa 2048

# パーミッションの変更
$ chmod 600 ~/.ssh/conoha_rsa

# 公開鍵を生成
$ ssh-keygen -y -f ~/.ssh/conoha_rsa > ~/.ssh/conoha_rsa.pub

# 鍵を登録する
$ ssh-add -K ~/.ssh/conoha_rsa

# 公開鍵をクリップボードにコピー
$ pbcopy < ~/.ssh/conoha_rsa.pub

リモートサーバーに公開鍵を設置します。

$ mkdir -p /home/exampleuser/.ssh/ && \
vi /home/exampleuser/.ssh/authorized_keys

ここで、先ほどクリップボードにコピーした公開鍵をペーストし保存します。保存後、.ssh ディレクトリ、authorized_keys の所有権やアクセス権を変更します。

$ chown exampleuser:exampleuser /home/exampleuser/.ssh/ && \
chmod 700 /home/exampleuser/.ssh/ && \
chown exampleuser:exampleuser /home/exampleuser/.ssh/authorized_keys && \
chmod 400 /home/exampleuser/.ssh/authorized_keys

SSHの設定

ログイン認証方法の変更、ポート番号の変更を行います。

$ vi /etc/ssh/sshd_config
Port 10022                               # SSH のポート番号を任意に変更
Protocol 2                               # SSH のプロトコルを SSH2 のみにする
PermitRootLogin no                       # root でのログインを拒否
PubkeyAuthentication yes                 # 公開鍵での認証を許可
AuthorizedKeysFile .ssh/authorized_keys  # 公開鍵の設置場所をユーザディレクトリ配下の .ssh/authorized_keys に変更
IgnoreUserKnownHosts yes                 # /etc/ssh_known_hosts または ~/.ssh/known_hosts を無視
PermitEmptyPasswords no                  # パスワードが設定されていないアカウントを拒否
PasswordAuthentication no                # パスワード認証を拒否
ChallengeResponseAuthentication no       # チャレンジ/レスポンス認証を無効化
UsePAM no                                # PAM 認証を無効化
SyslogFacility AUTHPRIV                  # ログレベルを指定
LogLevel VERBOSE                         # ログレベルを指定
AllowTcpForwarding no                    # SSHポートフォワードの禁止
AllowStreamLocalForwarding no            # SSHポートフォワードの禁止
GatewayPorts no                          # SSHポートフォワードの禁止
PermitTunnel no                          # SSHポートフォワードの禁止
AllowUsers exampleuser                   # ログイン許可するユーザー

変更内容は、sshdの再起動を行うと反映されますが、再起動はFirewallの設定後に行います。

Firewall の設定

CentOS7 では、iptables が非推奨となり代わりに firewall-cmd を使うように変更されました。iptables は非推奨でですが、利用することは可能です。

HTTP、HTTPS、MySQL のポートを開放する

$ firewall-cmd --add-service=http && \
firewall-cmd --permanent --add-service=http && \
firewall-cmd --add-service=https && \
firewall-cmd --permanent --add-service=https && \
firewall-cmd --add-service=mysql && \
firewall-cmd --permanent --add-service=mysql

ssh のポート番号を 10022 に変更する

定義ファイルをコピーして編集します。

$ cp /usr/lib/firewalld/services/ssh.xml /etc/firewalld/services/ssh-alt.xml && \
vi /etc/firewalld/services/ssh-alt.xml

port="22" の 22 を 10022 に変更します。

<port protocol="tcp" port="10022"/>

変更した内容を Firewall に設定します。

$ firewall-cmd --reload && \
firewall-cmd --add-service=ssh-alt && \
firewall-cmd --permanent --add-service=ssh-alt && \
firewall-cmd --remove-service=ssh && \
firewall-cmd --permanent --remove-service=ssh && \
firewall-cmd --reload && \
firewall-cmd --list-all

sshd を再起動させます。

$ systemctl restart sshd

root になれるユーザーを制限する

誰でも root に成れてしまうのは危険だとなので、root に成れるユーザーとグループの制限と、sudo コマンド使用時のパスワード認証の有無を設定します。

wheelグループのみ root になれるようにする

$ vi /etc/pam.d/su
auth required pam_wheel.so use_uid # コメントアウトを外す

末尾に group=wheel を追記します(不要な気がする…)。

auth required pam_wheel.so use_uid group=wheel

su コマンドは wheel グループのみ使用できるようにします。

$ vi /etc/login.defs
SU_WHEEL_ONLY yes # 最後の行に追加

root になれるユーザーを制限する

以下の例は、rootとexampleuserのみsuコマンドでrootになれる例です。

$ vi /etc/group
wheel:x:10:root,exampleuser

sudo コマンドの設定をする

$ visudo
# %wheel ALL=(ALL) ALL            # sudo コマンドにパスワードを必要とする場合
# %wheel ALL=(ALL) NOPASSWD: ALL  # sudo コマンドにパスワードを必要としない場合

不要なデーモンを停止させる

下記コマンドで起動中のデーモンを確認し不要なサービスを個別に停止させます。

$ ls /etc/systemd/system/multi-user.target.wants|grep \.service

acpid
ホスト側からシャットダウンできなくなるのでonのままにしておきます。また、カスタムOSをインストールした場合は acpid がインストールされているか確認します。

acpid がインストールされていない場合、以下のコマンドでインストールできます。

$ yum -y install acpid && \
systemctl enable acpid.service && \
systemctl start acpid.service

avahi-daemon

$ systemctl stop avahi-daemon.service && \
systemctl disable avahi-daemon.service

blk-availability

$ systemctl stop blk-availability.service && \
systemctl disable blk-availability.service

cpuspeed

$ systemctl stop cpuspeed.service && \
systemctl disable cpuspeed.service

haldaemon

$ systemctl stop haldaemon.service && \
systemctl disable haldaemon.service

mdmonitor

$ systemctl stop mdmonitor.service && \
systemctl disable mdmonitor.service

messagebus

$ systemctl stop messagebus.service && \
systemctl disable messagebus.service

kdump

$ systemctl stop kdump.service && \
systemctl disable kdump.service

netfs

$ systemctl stop netfs.service && \
systemctl disable netfs.service

quota_nld

$ systemctl stop quota_nld.service && \
systemctl disable quota_nld.service

rdisc

$ systemctl stop rdisc.service && \
systemctl disable rdisc.service

svnserve

$ systemctl stop svnserve.service && \
systemctl disable svnserve.service

udev-post

$ systemctl stop udev-post.service && \
systemctl disable udev-post.service

yum-updatesd

$ systemctl stop yum-updatesd.service && \
systemctl disable yum-updatesd.service

ログイン時のメッセージを変更する

$ vi /etc/motd

適当にブランド名などを記載。以下は一例です。

  
  ██╗   ██╗██╗███████╗██╗   ██╗ █████╗ ██╗     ██╗██╗   ██╗███████╗
  ██║   ██║██║██╔════╝██║   ██║██╔══██╗██║     ██║██║   ██║██╔════╝
  ██║   ██║██║███████╗██║   ██║███████║██║     ██║██║   ██║█████╗  
  ╚██╗ ██╔╝██║╚════██║██║   ██║██╔══██║██║     ██║╚██╗ ██╔╝██╔══╝  
   ╚████╔╝ ██║███████║╚██████╔╝██║  ██║███████╗██║ ╚████╔╝ ███████╗
    ╚═══╝  ╚═╝╚══════╝ ╚═════╝ ╚═╝  ╚═╝╚══════╝╚═╝  ╚═══╝  ╚══════╝

  H2O + HHVM + MariaDB

  VisuAlive https://www.visualive.jp
  KUCKLU    https://www.kuck1u.me
  

テキストバナーは下記サイトで簡単に作成できます。

Text to ASCII Art Generator (TAAG)

ホスト名を変更する

$ vi /etc/hostname

root宛のメールを転送する

$ sed -i '/^root:/d' /etc/aliases && \
vi /etc/aliases

「# Person who should get root's mail」の下にある「root:」の値を変更します。

root: hoge@example.com

設定を反映させます。

$ postalias /etc/aliases

Postfix のメールをGmail経由で送信する

2 重認証の設定を行っている場合は、予めアプリ用パスワードを発行しておきます。

$ yum -y install cyrus-sasl cyrus-sasl-plain cyrus-sasl-md5 && \
systemctl enable saslauthd && \
systemctl start saslauthd &&\
echo [smtp.gmail.com]:587 accountname@gmail.com:apppassword > /etc/postfix/sasl_gmail &&\
chmod 600 /etc/postfix/sasl_gmail &&\
postmap /etc/postfix/sasl_gmail &&\
vi /etc/postfix/main.cf

以下を末尾に追加します。

relayhost = [smtp.gmail.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_gmail
smtp_sasl_tls_security_options = noanonymous
smtp_sasl_mechanism_filter = plain
smtp_tls_CApath = /etc/ssl/certs/ca-certificates.crt

Postfix を再起動させます。

$ systemctl restart postfix

テスト送信を行い、Gmail 経由でメールが送信されているのを確認します。

$ echo test | mail root

TCP カーネルパラメータを変更する

ipv6 が不要であれば、その辺りは各々調節してください。

sysctl -w kernel.exec-shield=2
sysctl -w vm.swappiness=0 && \
sysctl -w net.ipv4.ip_local_port_range="18000 65535" && \
sysctl -w net.ipv4.tcp_fastopen=3 &&\
sysctl -w net.ipv4.tcp_tw_reuse=1 && \
sysctl -w net.ipv4.tcp_fin_timeout=10 && \
sysctl -w net.ipv4.tcp_max_syn_backlog=1024 && \
sysctl -w net.core.somaxconn=65535 && \
sysctl -w net.ipv6.conf.all.disable_ipv6=0 && \
sysctl -w net.ipv6.conf.default.disable_ipv6=0 && \
sysctl -w net.ipv6.conf.lo.disable_ipv6=0

設定ファイルの編集します。

$ vi /usr/lib/sysctl.d/10-custom.conf

下記をペーストします。

kernel.exec-shield = 2
vm.swappiness = 0
net.ipv4.ip_local_port_range = 18000 65535
net.ipv4.tcp_fastopen = 3
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 10
net.ipv4.tcp_max_syn_backlog = 1024
net.core.somaxconn = 65535
net.ipv6.conf.all.disable_ipv6 = 0
net.ipv6.conf.default.disable_ipv6 = 0
net.ipv6.conf.lo.disable_ipv6 = 0

変更した設定を反映させます。

$ sysctl -p

参考
Nginxのパフォーマンスを極限にするための考察
ローカルポートを食いつぶしていた話
Linuxカーネルパラメータ一覧・標準設定(CentOS 6)

ファイルディスクリプタの上限を変更する

$ vi /etc/security/limits.conf 

以下を追加。

* soft nofile 65536
* hard nofile 65536

再起動にも反映されるように

$ vi /etc/sysconfig/init

以下を末尾に追加します。

ulimit -n 65536

再起動させる

再起動させないと設定が反映されない項目があるため、CentOSを再起動させます。

$ reboot

ライブラリやソフトウェアを諸々インストールする

yum install でインストール可能なライブラリやソフトウェア群

$ yum -y install \
cpp gcc-c++ gcc psmisc numactl m4 automake bison \
{binutils,boost,bison,sqlite,tbb,bzip2,openldap,readline,elfutils-libelf,gmp,pcre,perl,GeoIP,gd,zlib,fribidi,numactl}-devel \
lib{xslt,event,yaml,vpx,png,zip,icu,memcached,cap,dwarf,jpeg-turbo}-devel \
mariadb mariadb-server {unixODBC,expat,mariadb}-devel lib{edit,curl,xml2,ffi}-devel \
libjpeg-turbo ocaml gperf libjpeg-turbo-static libjpeg-turbo-utils optipng \
make libtool libssh ruby ruby-devel dialog augeas-libs environment-modules compat-openldap
$ yum -y --enablerepo=epel install \
xsel glib fastlz double-conversion inotify-tools zeromq enca gifsicle gperftools lib{uv,mcrypt} \
{double-conversion,jemalloc,lz4,libc-client,fastlz,glib,inotify-tools,zeromq,libuv,glog,oniguruma,libmcrypt,gperftools}-devel

作業ディレクトリを作成

$ mkdir -p /tmp/dev/ && \
mkdir -m 750 -p /var/log/h2o/ && \
chown -R h2o:h2o /var/log/h2o/ && \
mkdir -m 750 -p /var/log/hhvm/ && \
chown -R hhvm:hhvm /var/log/hhvm/ && \
mkdir -m 770 -p /var/www/public_html/ && \
chmod 2770 /var/www/public_html/ && \
chown -R nginx:nginx /var/www/vhosts/

OpenSSL をインストールする

$ cd /tmp/dev && \
wget https://github.com/openssl/openssl/archive/OpenSSL_1_1_1o.tar.gz -O openssl.tar.gz && \
mkdir ./openssl && \
tar -zxvf openssl.tar.gz -C ./openssl --strip-components=1 && \
rm -rf openssl.tar.gz && \
cd ./openssl && \
./config --prefix=/usr/local/openssl/1_1_1o --openssldir=/usr/local/openssl shared zlib
make depend && \
make && \
make install

シンボリックリンクを作成

$ ln -s /usr/local/openssl/1_1_1o/bin/c_rehash /usr/local/bin/ && \
ln -s /usr/local/openssl/1_1_1o/bin/openssl /usr/local/bin/ && \
ln -s /usr/local/openssl/1_1_1o/include/openssl /usr/local/include/ && \
ln -s /usr/local/openssl/1_1_1o/lib/engines /usr/local/lib/ && \
ln -s /usr/local/openssl/1_1_1o/lib/libcrypto.a /usr/local/lib/  && \
ln -s /usr/local/openssl/1_1_1o/lib/libcrypto.so /usr/local/lib/ && \
ln -s /usr/local/openssl/1_1_1o/lib/libcrypto.so.1.1 /usr/local/lib/ && \
ln -s /usr/local/openssl/1_1_1o/lib/libssl.a /usr/local/lib/ && \
ln -s /usr/local/openssl/1_1_1o/lib/libssl.so /usr/local/lib/ && \
ln -s /usr/local/openssl/1_1_1o/lib/libssl.so.1.1 /usr/local/lib/ && \
ln -s /usr/local/openssl/1_1_1o/lib/pkgconfig/libcrypto.pc /usr/local/lib/pkgconfig/ && \
ln -s /usr/local/openssl/1_1_1o/lib/pkgconfig/libssl.pc /usr/local/lib/pkgconfig/ && \
ln -s /usr/local/openssl/1_1_1o/lib/pkgconfig/openssl.pc /usr/local/lib/pkgconfig/

Git のインストール

$ cd /tmp/dev && \
yum -y remove git && \
wget https://github.com/git/git/archive/v2.36.1.tar.gz -O git.tar.gz && \
mkdir git && \
tar -zxvf git.tar.gz -C /tmp/dev/git --strip-components=1 && \
rm -rf git.tar.gz && \
cd ./git && \
make configure && \
./configure --prefix=/usr/local --with-openssl=/usr/local/ssl/lib/ && \
make all && \
make install && \
git --version

CMake のインストール

$ cd /tmp/dev && \
wget https://cmake.org/files/v3.23/cmake-3.23.2.tar.gz -O cmake.tar.gz && \
mkdir cmake && \
tar -zxvf cmake.tar.gz -C /tmp/dev/cmake --strip-components=1 && \
rm -rf cmake.tar.gz && \
cd ./cmake && \
./configure && \
make && \
make install

libuv のインストール

$ cd /tmp/dev && \
git clone https://github.com/libuv/libuv.git --depth=1 && \
cd ./libuv && \
sh autogen.sh && \
./configure && \
make && \
make install

libre2 のインストール

$ cd /tmp/dev && \
git clone https://github.com/google/re2.git --depth=1 && \
cd ./re2 && \
make && \
make install

libiconv のインストール

$ cd /tmp/dev && \
wget http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.14.tar.gz -O libiconv.tar.gz && \
mkdir ./libiconv && \
tar -zxvf libiconv.tar.gz -C ./libiconv --strip-components=1 && \
cd ./libiconv && \
wget http://apolloron.org/software/libiconv-1.14-ja/libiconv-1.14-ja-2.patch && \
patch -p1 < ./libiconv-1.14-ja-2.patch && \
./configure && \
make && \
make install

libmruby のインストール

$ cd /usr/local/src && \
wget https://github.com/mruby/mruby/archive/3.1.0.tar.gz -O mruby.tar.gz && \
mkdir ./mruby && \
tar -zxvf mruby.tar.gz -C ./mruby --strip-components=1 && \
rm -rf mruby.tar.gz && \
cd ./mruby && \
./minirake

libmruby.pc 作成。

$ cat <<EOD>$PWD/build/host/lib/libmruby.pc
prefix=$PWD
libdir=\${prefix}/build/host/lib/
includedir=\${prefix}/include

Name: libmruby
Description: mruby libraries
Version: 3.1.0
Libs: -L\${libdir} -lmruby
Cflags: -I\${includedir}
EOD

Ruby のライブラリのインストール

$ gem install rake --remote

不要ファイルの削除などの後始末

$ rm -rf /tmp/dev

これで、CentOS の設定は完了です。

セキュリティ関連

パーミッション

設定する値 一般的な値(参考)
ディレクトリ 750 ( rwxr-x--- ) 755 ( rwxr-xr-x )
.html / .php / .jpg 640 ( rw-r----- ) 644 ( rw-r--r-- )
.cgi / .pl 700 ( rwx------ ) 755 ( rwxr-xr-x )
.text / .dat / .log 600 ( rw------- ) 666 ( rw-rw-rw- )
.htaccess / .htpasswd 640 ( rw-r----- ) 644 ( rw-r--r-- )

public_html 以下のファイルを一括で750へ変更する

$ find /var/www/public_html -type d -print | xargs chmod 750

public_html 以下のファイルを一括で640へ変更する

$ find /var/www/public_html -type f -print | xargs chmod 640

public_html 以下の特定の拡張子のファイルを640へ変更する

$ find /var/www/public_html -type f -regex ".*\.\(php\|html|css|js|jpg|jpeg|pnh|gif|svg\)" -print | xargs chmod 640

OpenSSH のローミング機能をオフにする

$ echo -e 'UseRoaming no' | sudo tee -a /etc/ssh/ssh_config && \
systemctl restart sshd

ウイルスの検出

Clam AntiVirus の設定(ウィルス対策ソフト) をご覧ください。

Rootkit の検出

RKHunter の設定(Rootkit 検出ツール) をご覧ください。

ログを監視する

Logwatch の設定(ログ監視ツール) をご覧ください。

SSH のブルートフォース攻撃に備える

Denyhosts の設定(SSH のブルートフォース攻撃対策) をご覧ください。

参考サイト

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2