CentOS7 サーバ構築メモ

さくらVPSにCentOS 7をminimumインストールして初期構築したときのメモ

  1. ログイン用ユーザー追加
  2. sudo設定
  3. motd設定
  4. SELinux無効化
  5. 名前解決設定
  6. sshd設定
  7. vim設定
  8. 追加パッケージのインストール
  9. httpd設定
  10. ntp設定
  11. WebDAV設定
  12. MariaDB設定
  13. PHP設定
  14. Postfix設定
  15. Dovecot設定
  16. Logwatch設定
  17. SPFチェック
  18. RoundCubeメール設定(Webメール設定)
  19. メール振り分け設定プラグイン設定
  20. OpenDKIM設定
  21. 暗号化SMTP対応
  22. php74インストール

さくらVPS固有の設定値についてはさくらVPSサポートページを参照


ログイン用ユーザー追加

# useradd username
# echo "username:password" | chpasswd
# usermod -G wheel username
(sshの鍵を .ssh/authorized_keysに記載する)
# chmod 600 ~username/.ssh/authorized_keys

sudo設定

# visudo
(wheelグループはパスワードなしでsudoできるように設定する)

motd設定

# cp /etc/motd /etc/motd_orig
# echo "" > /etc/motd
# echo "sakura server" >> /etc/motd
# echo "" >> /etc/motd

SELinux無効化

そのうち勉強したら無効化しなくてもいいようになるのかも

# getenforce
# setenforce 0
# vi /etc/selinux/config

名前解決設定

unboundをインストールして自サーバ専用のキャッシングネームサーバーにする

# vi /etc/hosts
(自サーバの名前を記載しておく)
# yum install bind-utils
# yum install unbound
# cd /etc/unbound
# cp unbound.conf unbound.conf_orig
# vi unbound.conf
control-enable: no
(server-key-file行をコメントアウト)
(server-cert-file行をコメントアウト)
(control-key-file行をコメントアウト)
(control-cert-file行をコメントアウト)
# systemctl start unbound
# systemctl enable unbound
# vi /etc/resolv.conf
search 自ドメイン
nameserver 127.0.0.1

sshd設定

まず初めに/etc/servicesの末尾にエントリーを追加しておく

alterssh       XXXXX/tcp

そのうえで/etc/ssh/sshd_configを変更する。 なお/etc/ssh/sshd_configのコメントによるとRHEL(≒CentOS)ではUsePAM=noはサポートされていないらしいので、 UsePAMの変更はしない

# vi /etc/ssh/sshd_config
Port XXXXX
PermitRootLogin no

あとはfirewalldの設定を変更する

# cd /usr/lib/firewalld/services
# cp ssh.xml alterssh.xml
# vi alterssh.xml
(記述を適当に変更して、ポート番号を書き換える)
# firewall-cmd --add-service=alterssh --permanent
# firewall-cmd --reload

vim設定

ユーザーのホームディレクトリに.vimrcファイルを作成して以下を記載する

set ambiwidth=double

追加パッケージのインストール

日本語manとepelレポジトリをインストール

# yum install man-pages-ja
# yum install epel-release
# yum clean all
# yum update

あとunzipも

# yum install unzip

httpd設定

# yum install httpd
# vi /etc/httpd/conf/httpd.conf
(ServerNameを変更する)
# vi /etc/httpd/conf.d/autoindex.conf
IndexOptions FancyIndexing HTMLTable VersionSort Charset=UTF-8
# firewall-cmd --add-service=http --permanent
# firewall-cmd --add-service=https --permanent
# firewall-cmd --reload
# firewall-cmd --state
# systemctl start httpd
# systemctl enable httpd

続いてmod_sslをインストール

# yum install mod_ssl
(鍵とサーバ証明書と中間証明書を/etc/httpd以下に配置)
# vi /etc/httpd/conf.d/ssl.conf
(鍵とサーバ証明書と中間証明書のパスを指定)
(SSLv3を禁止)
# vi /var/www/html/index.html
(初期ページを記載)

ntp設定

# vi /etc/chrony.conf
(ntp1.sakura.ad.jp iburst をサーバに指定)
# firewall-cmd --add-service=ntp --permanent
# firewall-cmd --reload
# systemctl start chronyd
# systemctl enable chronyd

WebDAV設定

CentOS 7 では、CentOS 6の設定そのままでは動かなかった。DavLockDBが必要とのこと。

# cd /var/www/html
# mkdir dirname
# chown apache.apache dirname
# vi /etc/httpd/conf.d/webdav.conf
Alias /dirname "/var/www/html/dirname"
<IfModule mod_dav.c>
    DAVMinTimeout 600
    DavLockDB "/tmp/DavLock"
    <Location /dirname>
        DAV On
        SSLRequireSSL
        AuthType        Basic
        AuthName        "WebDAV Server"
        AuthUserFile    "/etc/httpd/.htpasswd"
        <LimitExcept OPTIONS>
            Require valid-user
        </LimitExcept>
        Header add MS-Author-Via "DAV"
        Order deny,allow
        Deny from none
        Allow from all
    </Location>
</IfModule>
<VirtualHost *:80>
    Redirect /dirname https://www.terra.jp.net/dirname
</VirtualHost>
# htpasswd -c /etc/httpd/.htpasswd username
# systemctl restart httpd

Windows 7でWebDAV接続に一度失敗した後でhttpd設定を変更したら、Windows 7側でWebClientサービスを再起動しないとうまくいかないかもしれない。

Windows 7でログオン認証ダイアログで保存されたパスワードの一覧表示/削除等をするには "rundll32 keymgr.dll KRShowKeyMgr"。

インストールした証明書の一覧表示/削除等ができる証明書マネージャを起動するには "certmgr.msc"。

2015/09/03更新:Windows10に対しても上の設定で特に問題なかった。


MariaDB設定

CentOS 7 にはMariaDB 5.5系が採用されているが、新しいほうが気分がいいので10.0系をインストールする。

(まずあらかじめMariaDBのサイトでyumレポジトリの設定ファイルを手に入れておく)
# vi /etc/yum.repos.d/MariaDB.repo
(yumレポジトリの設定ファイルを作成する)
# yum cleann all
# yum install MariaDB-server MariaDB-client
# chkconfig
# vi /etc/my.cnf.d/server.cnf
[server]
character-set-server = utf8
# service mysql start
# mysql_secure_installation
# mysql -u root -p
Enter password: パスワード
MariaDB [(none)]> create database dbname;
MariaDB [(none)]> create user username@localhost;
MariaDB [(none)]> set password for username@localhost = password('password');
MariaDB [(none)]> grant all on dbname.* to username@localhost;
MariaDB [(none)]> flush privileges;
MariaDB [(none)]> quit
# mysql -u username -p
Enter password: password
MariaDB [(none)]> show databases;
MariaDB [(none)]> quit

mysql_secure_installationコマンドは知らなかったのだが、testデータベースを削除したりrootのパスワードを設定したりリモートからのrootログインをできなくしたり、といった簡単なハードニングをしてくれるらしい。


PHP設定

# yum install php php-mysql php-mbstring
# vi /etc/php.ini
default_charset = "UTF-8"
date.timezone = "Asia/Tokyo"
# systemctl restart httpd

Postfix設定

自分のドメインを使って、できるだけ簡単にメールアドレスを使えるようにする。

まずはpostfixの基本設定。

# vi /etc/postfix/main.cf
myorigin = $mydomain
inet_interfaces = $myhostname, localhost
inet_protocols = ipv4
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
mynetworks_style = host
home_mailbox = Maildir/
canonical_maps = hash:/etc/postfix/canonical
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous, noplaintext
smtpd_sasl_tls_security_options = noanonymous
smtpd_sasl_local_domain = $mydomain
smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destination
smtpd_tls_cert_file = /etc/postfix/servercert.pem
smtpd_tls_key_file = /etc/postfix/serverkey.pem
# vi /etc/postfix/master.cf
submission inet n       -       n       -       -       smtpd
  -o syslog_name=postfix/submission
  -o smtpd_tls_security_level=encrypt
  -o smtpd_sasl_auth_enable=yes
smtps     inet  n       -       n       -       -       smtpd
  -o syslog_name=postfix/smtps
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes

続いてメールアドレスとUNIXユーザーのマッピング。

# vi /etc/postfix/canonical
UNIXユーザ名	メールアドレスにしたいユーザ名
# postmap hash:/etc/postfix/canonical
# vi /etc/aliases
メールアドレスにしたいユーザ名:	UNIXユーザ名
転送したいユーザ名:		転送先メールアドレス@example.co.jp
# newalises

次はSMTP AUTHの設定。DIGEST-MD5とかCRAM-MD5を使いたいのでsaslauthdは使わない。

# yum install cyrus-sasl-md5 cyrus-sasl-plain
# saslpasswd2 -u `postconf -h mydomain` -c UNIXユーザ名
Password: SMTP AUTH用のパスワード
Again (for verification): SMTP AUTH用のパスワード(再)
# chgrp postfix /etc/sasldb2
# chmod g+r /etc/sasldb2
# vi /etc/sasl2/smtpd.conf
pwcheck_method: auxprop
auxprop_plugin: sasldb
mech_list: CRAM-MD5 DIGEST-MD5 LOGIN PLAIN

そして暗号化用の鍵と証明書の作成。 submissionポート(587)とsmtpsポート(465)経由で自分でメールを送信するときの PLAIN認証のパスワードを暗号化したいだけなので、 オレオレ証明書で構わない。

# cd /etc/postfix
# openssl genrsa -out serverkey.pem 2048
# chgrp postfix serverkey.pem
# chmod 640 serverkey.pem
# openssl req -new -key serverkey.pem -days 3650 -out servercert.pem
CNはホスト名 (FQDN) で答える
emailは postmaster@ドメイン名 で答える
それ以外はすべて . (ピリオド) で答える

最後にファイヤーウォールの開放。

# cd /usr/lib/firewalld/services
# cp smtp.xml smtpsubmission.xml
# vi smtpsubmission.xml
<short>Mail (SMTP Submission)</short>
<port protocol="tcp" port="465"/>
<port protocol="tcp" port="587"/>
# firewall-cmd --reload
# firewall-cmd --add-service smtp --permanent
# firewall-cmd --add-service smtpsubmission --permanent
# firewall-cmd --reload
# systemctl restart postfix
# systemctl enable NetworkManager-wait-online

Dovecot設定

# yum install dovecot
# vi /etc/dovecot/conf.d/10-mail.conf
mail_location = maildir:~/Maildir

imaps用のSSL暗号化のためにオレオレ証明書を作る。 個人用サーバなので、暗号化できさえすればオレオレ証明書で問題ない。

# cd /etc/pki/dovecot
# vi dovecot-openssl.cnf
default_bits = 2048
default_md = sha256        (default_bits行の下に書く)
...
CN=ホスト名.ドメイン
emailAddress=postmaster@ドメイン
# openssl genrsa -out private/dovecot.pem 2048
# chmod 600 private/dovecot.pem
# openssl req -new -x509 -key private/dovecot.pem -config dovecot-openssl.cnf -days 3650 -out certs/dovecot.pem

最後にファイヤーウォールを開ける

# firewall-cmd --add-service imaps
# systemctl start dovecot
# systemctl enable dovecot

Logwatch設定

logwatchをインストールして、メールでレポートを送れるようにする。

# yum install logwatch
# vi /etc/logwatch/conf/logwatch.conf
MailTo = レポート送信先メールアドレス
Format = html

ついでにhttpのログをカスタマイズするために、httpのスクリプトを/usr/share以下から/etc以下にコピーする。 実際のカスタマイズはコピーした/etc以下のファイルに対して実施する。

# cp /usr/share/logwatch/scripts/services/http /etc/logwatch/scripts/services/http
# vi /etc/logwatch/scripts/services/http

カスタマイズ後のdiffはこんな感じ。 まずは攻撃とみなすURLの対象を増やし、 さらに攻撃者のホスト名がもしあれば参考までに表示させる。 これで"A total of xx sites probed the server"のセクションが少し使いやすくなるはず。

# diff -c /usr/share/logwatch/scripts/services/http /etc/logwatch/scripts/services/http
*** /usr/share/logwatch/scripts/services/http   2014-06-10 11:15:40.000000000 +0900
--- /etc/logwatch/scripts/services/http 2015-08-11 17:25:23.393478932 +0900
***************
*** 334,339 ****
--- 334,346 ----
     'shtml\.exe',
     'win\.ini',
     'xxxxxxxxxxxxxxxxxxxxxx',
+    'login\.do',
+    'login\.action',
+    '\/manager\/html',
+    'muieblackcat',
+    'Diagnostics.asp',
+    '\/cgi-bin\/php',
+    '\/scripts\/setup.php',
  );

  #
***************
*** 705,711 ****
        $flag = 0;
     }
     #if ($detail > 4) {
!       print "   $i\n";
     #}
  }

--- 712,722 ----
        $flag = 0;
     }
     #if ($detail > 4) {
!       my $hname = gethostbyaddr(pack("C4",split(/\./,$i)),2);
!       if (!$hname) {
!          $hname="unknown";
!       }
!       print "   $i ($hname)\n";
     #}
  }

さらにpostfixのログ解析の詳細度を上げておく。

# vi /etc/logwatch/conf/override.conf
services/postfix: Detail=10

SPFチェック

EPELからyumでインストールできるので簡単。 デフォルト設定のままで使う。

# yum install pypolicyd-spf
# vi /etc/postfix/master.cf
policy-spf  unix  -       n       n       -       0       spawn
  user=nobody argv=/usr/bin/python /usr/libexec/postfix/policyd-spf /etc/python-policyd-spf/policyd-spf.conf
# vi /etc/postfix/master.cf
policy-spf_time_limit = 3600s
smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destination, check_policy_service unix:private/policy-spf
# systemctl reload postfix

なおcheck_policy_serviceはreject_unauth_destinationよりも後ろに書かないとダメだそうです。


RoundCubeメール設定

RoundCubeをEPELからインストール。

# yum install roundcubemail
# yum install php-mcrypt

RoundCube用のデータベースとユーザーを作成。

$ mysql -u root -p
MariaDB [(none)]> create user rcmail@localhost;
MariaDB [(none)]> set password for rcmail@localhost=password('パスワード');
MariaDB [(none)]> create database rcmail;
MariaDB [(none)]>> grant all on rcmail.* to rcmail@localhost;
MariaDB [(none)]> flush privileges;
MariaDB [(none)]> \q

RoundCubeへリモートからアクセス可能にする。

# cd /etc/httpd/conf.d
# vi roundcubemail.conf
(略)
Alias /ディレクトリ /usr/share/roundcubemail
(略)
<Directory /usr/share/roundcubemail/>
    <IfModule mod_rewrite.c>
        RewriteEngine on
        RewriteCond %{HTTPS} off
        RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
    </IfModule>
    <IfModule mod_authz_core.c>
        # Apache 2.4
        Require all granted
    </IfModule>
(略)
<Directory /usr/share/roundcubemail/installer>
    <IfModule mod_authz_core.c>
        # Apache 2.4
        Require all granted
    </IfModule>

インストーラー画面へアクセスする。

https://サーバ/ディレクトリ/installer/

---> CREATE CONFIGをクリック

表示されるconfigテキストを/etc/roundcubemail/config.inc.phpとして保存する。

# cd /etc/roundcubemail
# vi config.inc.php
# chgrp apache config.inc.php
# chmod 640 config.inc.php

---> CONTINUEをクリック

---> Initializa databaseをクリック

最後にinstallerへのアクセス権をもとに戻す。

# vi /etc/httpd/conf.d/roundcubemail.conf
<Directory /usr/share/roundcubemail/installer>
    <IfModule mod_authz_core.c>
        # Apache 2.4
        Require local
    </IfModule>

メール振り分け設定プラグイン設定

dovecot-pigeonholeをインストール。

# yum install dovecot-pigeonhole

dovecotでsieveとmanagesieveを有効化。

# cd /etc/dovecot
# vi 15-lda.conf
protocol lda {
  # Space separated list of plugins to load (default is global mail_plugins).
  #mail_plugins = $mail_plugins
  mail_plugins = $mail_plugins sieve
}
# vi 20-lmtp.conf
protocol lmtp {
  # Space separated list of plugins to load (default is global mail_plugins).
  #mail_plugins = $mail_plugins
  mail_plugins = $mail_plugins sieve
}
# vi 20-managesieve.conf
protocols = $protocols sieve

RoundCubeMailでmanagesieveプラグインを有効化する。

# cd /usr/share/roundcubemail/plugins/managesieve
# cp config.inc.php.dist config.inc.php
$config['managesieve_auth_type'] = PLAIN;
# vi /etc/roundcubemail/config.inc.php
$config['plugins'] = array('managesieve');

postfixのメール配信プログラムをdovecot/delverに変更。

# vi /etc/postfix/main.cf
mailbox_command = /usr/libexec/dovecot/deliver

参考にしたサイト:UnixPower on Networking - CentOS7 RoundCubeのインストール


OpenDKIM設定

# yum install opendkim
# opendkim-default-keygen
# cd /etc/opendkim/keys
# ls -l
# cat default.txt

ここでDNSに登録する。

---------------
default._domainkey.ドメイン. IN TXT "v=DKIM1; k=rsa; p=MIG…"
_adsp._domainkey.ドメイン.   IN TXT "dkim=unknown"
---------------

そして続き。

# vi /etc/opendkim.conf
Mode    sv
Domain  ドメイン

# vi /etc/postfix/main.cf
(末尾に3行追加)
smtpd_milters = inet:127.0.0.1:8891
non_smtpd_milters = $smtpd_milters
milter_default_action = accept

# systemctl enable opendkim
# systemctl start opendkim
# systemctl status opendkim
# systemctl restart postfix

SMTP暗号化対応

# vi /etc/postfix/main.cf
smtp_tls_security_level = may
smtp_tls_CAfile = /etc/pki/tls/cert.pem
smtp_tls_loglevel = 1
smtpd_tls_security_level = may
smtpd_tls_loglevel = 1
# systemctl restart postfix

php74インストール

# yum -y install http://rpms.famillecollet.com/enterprise/remi-release-7.rpm
# yum install php74 php74-php
# yum install php74-php-mbstring
# yum install php74-php-mysql php74-php-pdo
# yum install php74-php-gd php74-php-zip php74-php-imagick php74-php-dom php74-php-intl

最終更新日:2023/10/08

↑ トップページ