さくらVPS再々セットアップ

さくらの公式スタートアップスクリプトを参考にしながら、自前のスタートアップスクリプトを組んでみたが、設定ファイルをいじったり、通常は対話式で進めていくような作業がうまく行かない。

挙句の果てには、”dnf update” が失敗したり・・・

そりゃ、回線状況で失敗することがあるのはわかるけど、”dnf update” が失敗したまま先に進んでしまったら、後々不都合が起きそう。

ということで、やっぱり手作業で素の状態からやり直そうと思う。

1. OS再インストール

VPSのコンパネからOSを再インストール。

パケットフィルタリングは以下の設定。

  • SSH:22 → 開放(後で閉じる)
  • Web:80/443 → 開放
  • メール:25/110/143/465/587/993/995 → 開放
  • カスタム:(SSH用の別番号) → 開放

2. 初期設定いろいろ

2.1. ホスト名変更

hostnamectl set-hostname hogehoge.xxx

2.2. パッケージのアップデート

dnf -y update

2.3. 管理用一般ユーザーの追加

adduser hoge
passwd hoge
Changing password for user hoge.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.
usermod -G wheel hoge

2.4. sudo関連

vi /etc/pam.d/su
#%PAM-1.0
(中略)
# Uncomment the following line to require a user to be in the "wheel" group.
#auth           required        pam_wheel.so use_uid 
 ↓
auth           required        pam_wheel.so use_uid
visudo
(中略)
## Same thing without a password
# %wheel        ALL=(ALL)       NOPASSWD: ALL
 ↓
%wheel        ALL=(ALL)       NOPASSWD: ALL ##コメント解除。sudo でいちいちパスワード聞かれなくなる。

2.5. セキュリティ関連のパッケージを自動アップデート

dnf -y install dnf-automatic
vi /etc/dnf/automatic.conf
===
[commands]
#  What kind of upgrade to perform:
# default                            = all available upgrades
# security                           = only the security upgrades
upgrade_type = default
 ↓
upgrade_type = security
# Whether updates should be applied when they are available, by
# dnf-automatic.timer. notifyonly.timer, download.timer and
# install.timer override this setting.
apply_updates = no
 ↓
apply_updates = yes
===
systemctl enable dnf-automatic.timer
systemctl start dnf-automatic.timer

2.6. SSH関連

2.6.1. sshdの設定ファイルを変更

vi /etc/ssh/sshd_config
### root の直ログイン禁止
#PermitRootLogin yes
  ↓
PermitRootLogin no  # コメント解除し、no に変更。
### 空パスワードの禁止
#PermitEmptyPasswords no
  ↓
PermitEmptyPasswords no  # コメント解除。
### パスワード認証を禁止
PasswordAuthentication yes
  ↓
PasswordAuthentication no
### 公開鍵認証を有効に
PubkeyAuthentication yes  # コメント解除
### ポート番号変更
# Port 22
  ↓
Port 99999  # コメント解除し、ポート番号を変更

2.6.2. クライアント側で鍵ファイル生成し、サーバーにアップ

2.6.2.1. Mac側で鍵ペアを生成
cd ~/.ssh
ssh-keygen -t rsa -f ~/.ssh/id_rsa.sakura
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /Users/hoge/.ssh/id_rsa.sakura.
Your public key has been saved in /Users/hoge/.ssh/id_rsa.sakura.pub.
The key fingerprint is:
SHA256:********************* hoge@MacBook-Pro.local
The key's randomart image is:
2.6.2.2. 公開鍵をサーバーに転送

まずは、サーバー側にディレクトリを用意。(管理用の一般ユーザーでログイン)

cd ~
mkdir .ssh

ディレクトリを作成したら、Macのターミナルからscpコマンドでファイルを転送。

cd .ssh
scp id_rsa.sakura.pub hoge@xxx.xxx.xxx.xxx:.ssh/

Windowsからの場合は、以下の記事参照。

2.6.3. サーバー側の設定変更

cat id_rsa.sakura.pub >> authorized_keys
cd
chmod 700 .ssh
chmod 600 .ssh/authorized_keys
sudo systemctl restart sshd

2.7. 日本語化

dnf -y install langpacks-ja
localectl set-locale LANG=ja_JP.utf8
localectl
   System Locale: LANG=ja_JP.utf8
       VC Keymap: jp
      X11 Layout: jp

2.8. リポジトリの追加

dnf install -y epel-release
dnf install -y https://rpms.remirepo.net/enterprise/remi-release-8.rpm

普段は無効化しておき、必要な時だけリポジトリを都度指定する。

vi /etc/yum.repos.d/epel.repo
[epel]
name=Extra Packages for Enterprise Linux $releasever - $basearch
#baseurl=https://download.fedoraproject.org/pub/epel/$releasever/Everything/$basearch
metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-$releasever&arch=$basearch&infra=$infra&content=$contentdir
enabled=1 ← ここを0に変更
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-8
(以下略)
vi /etc/yum.repos.d/remi-safe.repo
[remi-safe]
name=Safe Remi's RPM repository for Enterprise Linux 8 - $basearch
#baseurl=http://rpms.remirepo.net/enterprise/8/safe/$basearch/
#mirrorlist=https://rpms.remirepo.net/enterprise/8/safe/$basearch/httpsmirror
mirrorlist=http://cdn.remirepo.net/enterprise/8/safe/$basearch/mirror
enabled=1 ← ここを0に変更
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-remi.el8
(以下略)

3. アプリ色々

さくらのスタートアップスクリプトの順番を参考に入れていく。

3.1. Dovecot/Postfix/MariaDB/Apache

dnf -y install dovecot dovecot-mysql
dnf -y install postfix postfix-mysql
dnf -y install mariadb-server httpd mod_ssl

3.2. PHP

dnf install -y wget
wget https://download-ib01.fedoraproject.org/pub/epel/8/Everything/x86_64/Packages/l/libc-client-2007f-24.el8.x86_64.rpm
rpm -Uvh libc-client-2007f-24.el8.x86_64.rpm
dnf --enablerepo=remi -y install oniguruma5php
dnf module reset php
dnf module enable php:remi-7.4
dnf module install -y php:remi-7.4
dnf --enablerepo=remi install -y php-mysqlnd php-imap

3.3. Let’s Encrypt

git clone https://github.com/certbot/certbot /usr/local/certbot
/usr/local/certbot/certbot-auto certonly -n --standalone --agree-tos -d your.domain -m hoge@your.domain --server https://acme-v02.api.letsencrypt.org/directory
vi /etc/cron.d/certbot-auto
0 4 5,15,25 * * root /usr/local/certbot/certbot-auto renew --pre-hook 'systemctl stop httpd' --post-hook 'systemctl reload postfix dovecot; systemctl start httpd'

3.4. Apache/PHP 初期設定

systemctl enable httpd
systemctl enable php-fpm
systemctl start httpd
systemctl start php-fpm

この状態で、phpinfo を出力するPHPファイルを作ってブラウザから確認。

3.5. ApacheのSSL化

3.5.1. ssl.conf の設定

vi /etc/httpd/conf.d/ssl.conf
#SSLCertificateFile /etc/pki/tls/certs/localhost.crt   ### 元の記述をコメントアウト
SSLCertificateFile /etc/letsencrypt/live/test.hogehoge.com/fullchain.pem   ### この行追加
#SSLCertificateKeyFile /etc/pki/tls/private/localhost.key   ### 元の記述をコメントアウト
SSLCertificateKeyFile /etc/letsencrypt/live/test.hogehoge.com/privkey.pem   ### この行追加
SSLCertificateChainFile /etc/letsencrypt/live/virtual.office-iwakiri.com/chain.pem   ### この行追加
SSLProtocol All -SSLv2 -SSLv3 -TLSv1 -TLSv1.1   ### この行追加

3.5.2. welcome.conf の設定

vi /etc/httpd/conf.d/welcome.conf
<locationmatch "^/+$">
#  Options -Indexes
#  ErrorDocument 403 /noindex/index.html
</locationmatch>

3.5.3. httpd.conf の設定

vi /etc/httpd/conf/httpd.conf
### ドキュメントルートのDirectoryディレクティブ
<directory "/var/www/html/">
    Options Indexes FollowSymLinks
      ↓
    Options FollowSymLinks  ## 変更
</directory>
### ファイルの末尾に追加
ServerTokens ProductOnly
ServerSignature Off

3.5.4. rewrite.conf の作成

vi /etc/httpd/conf/rewrite.conf
<ifmodule mod_rewrite.c="">
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
</ifmodule>
systemctl restart httpd
systemctl restart php-fpm

3.4. MariaDB 初期設定

systemctl enable mariadb.service
systemctl start mariadb.service
mysql_secure_installation

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user.  If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none):
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.

Set root password? [Y/n] Y
New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] Y
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] Y
 ... Success!

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] Y
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] Y
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

3.5. phpMyAdmin

3.5.1. インストール

dnf -y install expect
cd /srv/
wget https://files.phpmyadmin.net/phpMyAdmin/5.0.4/phpMyAdmin-5.0.4-all-languages.zip
unzip phpMyAdmin-5.0.4-all-languages.zip
mv phpMyAdmin-5.0.4-all-languages phpmyadmin
chown -R apache:apache phpmyadmin

3.5.2. 設定ファイル

cd /srv/phpmyadmin
cp config.sample.inc.php config.inc.php
mkpasswd -l 32
oLbkrmlmju6mltofgis_Huikefuef5tm  ### Cookie認証用のパスフレーズとして後で使用
vi config.inc.php
/**
 * This is needed for cookie based authentication to encrypt password in
 * cookie. Needs to be 32 chars long.
 */
$cfg['blowfish_secret'] = 'oLbkrmlmju6mltofgis_Huikefuef5tm'; /* 先程取得したパスフレーズを記入 */

3.5.3. ヴァーチャルホスト設定ファイル

vi /etc/httpd/conf.d/phpmyadmin.conf

Alias /phpmyadmin "/srv/phpmyadmin"
<Directory "/srv/phpmyadmin">
    DirectoryIndex index.html index.php
    AllowOverride All
    Options FollowSymlinks
    Require all granted
</Directory>
systemctl restart httpd

3.6. postfixAdmin

3.6.1. PostfixAdmin 本体のダウンロードと apache の設定

cd /srv/
git clone https://github.com/postfixadmin/postfixadmin.git
cd postfixadmin
LATEST_TAG=$(git tag -l | sort -V |  grep -iv 'push\|rc\|beta' | tail -1)
git checkout ${LATEST_TAG}
mkdir templates_c
chown -R apache templates_c
vi /etc/httpd/conf.d/postfixadmin.conf
Alias /postfixadmin "/srv/postfixadmin/public"
<Directory "/srv/postfixadmin/public">
    DirectoryIndex index.html index.php
    AllowOverride All
    Options FollowSymlinks
    Require all granted
</Directory>

3.6.2. PostfixAdmin 用のデータベース作成

MariaDBにログインして、以下のSQLを実行。同じことができれば、コマンドラインでも phpMyAdmin でも可。

CREATE DATABASE IF NOT EXISTS postfix;  
CREATE USER 'postfix'@'localhost' IDENTIFIED BY '[postfixユーザーのパスワード]';
GRANT ALL PRIVILEGES ON postfix.* TO 'postfix'@'localhost';
FLUSH PRIVILEGES;

3.6.3. PostfixAdmin の設定ファイル、セットアップ画面

vi /srv/postfixadmin/config.local.php
<?php
$CONF['configured'] = true;

$CONF['default_language'] = 'ja';
$CONF['database_type'] = 'mysql';
$CONF['database_user'] = 'postfix';

$CONF['database_password'] = '[postfixユーザーのパスワード]';
$CONF['database_name'] = 'postfix';

$CONF['domain_path'] = 'YES';
$CONF['domain_in_mailbox'] = 'NO';

$CONF['encrypt'] = 'dovecot:SHA512-CRYPT';

$CONF['footer_link'] = 'https://[your-domain]/postfixadmin/';
$CONF['footer_text'] = 'Return to [your-domain]/postfixadmin/';
?>
systemctl restart httpd

ここまでできたら、ブラウザでPostfixAdminのセットアップ画面にアクセスする。

https://[your-domain]/postfixadmin/setup.php

すると、各種チェックが行われて、問題なければページの下の方に、パスワードの入力欄が出てくる。

パスワードを入力して、[Generate password hash] というボタンを押すと、入力したパスワードがハッシュ化されて、以下のようなメッセージが出てくる。

If you want to use the password you entered as setup password, edit config.inc.php or config.local.php and set

$CONF['setup_password'] = '[ハッシュ化されたパスワード]';

これに従って、/srv/postfixadmin/config.local.php に追記する。

設定ファイルに追記できたら、セットアップ画面に再度アクセス。

今度は「Add a SuperAdmin Account」の欄が増えているので、必要事項を入力。

今度は、ログイン画面にアクセスする。

https://[your-domain]/postfixadmin/login.php

今回はすんなり進んだので、前回うまく行かなかったのは dovecot をインストールしてなかったのが原因か。

コメントはまだありません

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA