日別アーカイブ: 2023年4月19日

サーバの初期設定する(Rocky Linux 9.1)

CentOSからRocky Linuxに乗り換えました。

さくらのVPSを使っているので、ところどころ www????.sakura.ne.jp として入力しています。

ユーザ作成

まずはrootのパスワードを変更します。

# passwd

作業用アカウントを作成します。

ユーザーhoge作成
# useradd hoge

hogeのパスワード設定
# passwd hoge

hogeをwheelグループに入れる
# usermod -G wheel hoge

作業用アカウント(wheelグループ)以外ではrootになれないように制限します。元から設定済みでしたが念のため。

# visudo

この行を有効化
%wheel ALL=(ALL) ALL

suできるユーザを指定。

# vi /etc/pam.d/su

この行を有効化
auth required pam_wheel.so use_uid

rootはパスワードでログインできないようにします。

# vi /etc/ssh/sshd_config

この行を有効化
PermitRootLogin prohibit-password

鍵なしログイン可にする(コメントアウトのままでOK?)
PasswordAuthentication yes

SSH再起動。

# systemctl restart sshd

Rocky LinuxでのSSHのアクセス制限はfirewalldでやる必要があります。未対応。

パッケージ管理

必要なリポジトリを追加します。

# dnf upgrade
# dnf install https://dl.fedoraproject.org/pub/epel/epel-release-latest-9.noarch.rpm
# dnf install https://rpms.remirepo.net/enterprise/remi-release-9.rpm

Remiを指定してインストールする場合には以下のように記述します。

# dnf --enablerepo=remi install (パッケージ名)

全部のアプリをアップデートする。

# dnf --enablerepo=remi update

ファイアウォール

さくらのVPSはコントロールパネルからポート制限できるので設定不要?

起動
# systemctl enable firewalld
# systemctl start firewalld

設定追加
# firewall-cmd --add-service=http --zone=public --permanent
# firewall-cmd --add-service=https --zone=public --permanent
# firewall-cmd --add-service=smtp --zone=public --permanent
# firewall-cmd --add-port=110/tcp --zone=public --permanent
# firewall-cmd --add-port=587/tcp --zone=public --permanent
# firewall-cmd --reload

現在の設定は以下で確認できます。

# firewall-cmd --list-all --zone=public

繋がらない時は一旦firewalld止めて試してみる。終わったらfirewalld起動。

PHP

PHP8.2とそれに関係するものをインストール。

# dnf module enable php:remi-8.2
# dnf install php-fpm php-mysqlnd php-pear php-mbstring php-pdo php-gd php-json ImageMagick ImageMagick-devel php-devel
# pecl install imagick

各種設定。

# vi /etc/php.ini

post_max_size = 128M
upload_max_filesize = 128M
date.timezone = "Asia/Tokyo"
display_errors = On
error_reporting = E_ALL & ~E_NOTICE
extension = imagick.so

起動。

# chown nginx /var/log/php-fpm/
# systemctl start php-fpm
# systemctl enable php-fpm

Composerインストール

# curl -sS https://getcomposer.org/installer | php
# sudo mv composer.phar /usr/local/bin/composer

webサーバ

Apacheからnginxに変えました。

# dnf install nginx

ログの保持期間変更

# sudo vi /etc/logrotate.d/nginx

rotate 10 を 30とかに増やす

起動

# systemctl start nginx
# systemctl enable nginx

PHP-FPMの権限をapacheからnginxに変更

# vi /etc/php-fpm.d/www.conf

user = nginx
group = nginx
# systemctl restart php-fpm

ドメインごとに管理するユーザを分けます。普通にユーザを作成すると自分のホームディレクトリより上の階層に行けてしまうので、chrootを使って行けないようにします。

グループ作成。

# groupadd sftpgroup

グループに所属するユーザにchrootを適用します。

# vi /etc/ssh/sshd_config

サブシステム変更
#Subsystem sftp /usr/libexec/openssh/sftp-server
Subsystem sftp internal-sftp -u 0022

グループと行ける範囲を末尾に追加
Match group sftpgroup
ChrootDirectory ~
ForceCommand internal-sftp -u 0022

sshdを再起動します。設定間違うとサーバにアクセスできなくなるので、念の為ターミナルをもう1つ開いておいたり。

# systemctl restart sshd

あとはユーザを作成していけば /home/hoge/ がsshのルートディレクトリになります。

ユーザ作成
# useradd -g sftpgroup hoge
# passwd hoge

ホームディレクトリの所有者をrootにする
# chown root:root /home/hoge
# chmod 755 /home/hoge

ディレクトリ作成とパーミッション変更
# mkdir /home/hoge/public_html
# chmod 777 /home/hoge/public_html

バーチャルホスト

ドメインごとにconfファイルを作成します。以下はhoge.com用です。

# vi /etc/nginx/conf.d/hoge.com.conf

server {
listen 80;
server_name hoge.com;
root /home/hoge/public_html;
index index.php index.html index.htm;

access_log /var/log/nginx/hoge.com.access.log;
error_log /var/log/nginx/hoge.com.error.log;

client_max_body_size 128M;

# BASIC認証(必要なら)
auth_basic "Restricted area";
auth_basic_user_file /etc/nginx/.htpasswd;

# WordPress用
location ~ /.well-known {
auth_basic off;
allow all;
}
location / {
try_files $uri $uri/ /index.php?$args;
}

location ~ \.php$ {
try_files $uri =404;
fastcgi_pass unix:/run/php-fpm/www.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}

公開前にサイトを確認できるようにします。こんなURLで見れるようになります。
http://www????.sakura.ne.jp/hoge/

# vi /etc/nginx/conf.d/default.conf

server {
listen 80;
server_name www????.sakura.ne.jp;
root /var/www/html;
index index.php index.html index.htm;

access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;

client_max_body_size 128M;

# BASIC認証(必要なら)
auth_basic "Restricted area";
auth_basic_user_file /etc/nginx/.htpasswd;

# WordPress用
location ~ /.well-known {
auth_basic off;
allow all;
}
location / {
try_files $uri $uri/ /index.php?$args;
}

# サブディレクトリで閲覧
location /hoge {
alias /home/hoge/public_html;
index index.php index.html index.htm;
location ~ \.php$ {
fastcgi_pass unix:/run/php-fpm/www.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $request_filename;
include fastcgi_params;
}
# WordPress用
try_files $uri $uri/ /index.php?$args;
}
}

再起動

# systemctl restart nginx

WordPress

公式サイトからダウンロードしたzipを解凍してアップロードし設定を記述。

# cp wp-config-sample.php wp-config.php
# vi wp-config.php
データベース情報
define( 'DB_NAME', 'database_name_here' );
define( 'DB_USER', 'username_here' );
define( 'DB_PASSWORD', 'password_here' );

ファイル内に書かれたurlで秘密鍵を生成して設定
define( 'AUTH_KEY', 'put your unique phrase here' );
define( 'SECURE_AUTH_KEY', 'put your unique phrase here' );
define( 'LOGGED_IN_KEY', 'put your unique phrase here' );
define( 'NONCE_KEY', 'put your unique phrase here' );
define( 'AUTH_SALT', 'put your unique phrase here' );
define( 'SECURE_AUTH_SALT', 'put your unique phrase here' );
define( 'LOGGED_IN_SALT', 'put your unique phrase here' );
define( 'NONCE_SALT', 'put your unique phrase here' );

SSH接続するためSSH SFTP Updater Supportプラグインをダウンロード、解凍してから以下にアップロード。

/wp-content/plugins

設定ファイルに追記。

# vi wp-config.php

define('FS_METHOD', 'ssh2');

所有者の変更。WordPressのあるディレクトリで実行。

# chown -R nginx:sftpgroup ./

うまく行かない場合は開き直ってパーミッション変更。危険なので後で戻す。

# find ./ -type d -exec chmod 775 {} +
# find ./ -type f -exec chmod 664 {} +

おまけ:urlを変更する場合はMySQLで以下実行。

UPDATE wp_options SET option_value='http://hoge.com' WHERE option_name IN ('home','siteurl');

SSL

OpenSSLは既に入っているので、mod_sslをインストールします。

# dnf --enablerepo=remi install mod_ssl

証明書は無料のLet’s Encryptを使います。

インストール
# dnf install certbot

ドメイン追加
# certbot certonly --webroot -w /home/hoge/public_html -d hoge.com
メールアドレス入力
規約に同意:y
メールでお知らせ:n

バッチで証明書を自動更新します。

# crontab -e

0 4 1,15 * * certbot renew && systemctl restart nginx

SSLサーバの設定はドメインの設定ファイルに追加します。

# vi /etc/httpd/conf.d/hoge.conf

server {
listen 443 ssl;
server_name hoge.com;
root /home/hoge/public_html;
index index.php index.html index.htm;

access_log /var/log/nginx/hoge.com.access.log;
error_log /var/log/nginx/hoge.com.error.log;

client_max_body_size 128M;

# BASIC認証(必要なら)
auth_basic "Restricted area";
auth_basic_user_file /etc/nginx/.htpasswd;

# WordPress用
location ~ /.well-known {
auth_basic off;
allow all;
}
location / {
try_files $uri $uri/ /index.php?$args;
}

location ~ \.php$ {
try_files $uri =404;
fastcgi_pass unix:/run/php-fpm/www.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}

ssl_certificate /etc/letsencrypt/live/hoge.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/hoge.com/privkey.pem;
}

ちなみにlisten 80の方に以下のreturn行を入れるとhttpsにリダイレクトする
server {
listen 80;
server_name hoge.com;
return 301 https://$host$request_uri;
}

設定できたら再起動。

# systemctl restart nginx

MySQL

# dnf install mysql mysql-server

起動

# systemctl enable mysqld
# systemctl start mysqld

初期設定

# mysql_secure_installation
出てくる質問は以下の通り(英語)。
・VALIDATE PASSWORD利用:y
・パスワード検証ポリシー:0
・rootのパスワード:
・rootのパスワード確認用:
・いいですか?:y
・匿名ユーザの削除:y
・リモートからrootユーザ接続禁止:y
・テスト用データベースの削除:y
・変更を有効にする:y

デフォルト文字コードはutf8mb4だったので、そのままにしておきます。

終わったら再起動。

# systemctl restart mysqld

パスワードの制限をゆるくする。

# mysql -uroot -p

mysql> SET GLOBAL validate_password.policy=LOW;
mysql> set global validate_password.length=8;

データベースhogeとそのDBに紐づいたユーザhogeを作成します。

mysql> CREATE DATABASE `hoge`;
mysql> CREATE USER `hoge`@`localhost` IDENTIFIED BY 'パスワード';
mysql> GRANT ALL PRIVILEGES ON `hoge`.* TO `hoge`@`localhost`;
mysql> FLUSH PRIVILEGES;

phpMyAdmin

せっかくなのでMySQLの管理ページを入れる。

# dnf install --enablerepo=remi phpmyadmin

こんなURLで見れるようになります。
http://www????.sakura.ne.jp/phpMyAdmin/

# vi /etc/nginx/conf.d/default.conf
server {}の中に以下を追加

location /phpMyAdmin {
root /usr/share;
index index.php;

# BASIC認証(必要なら)
auth_basic "Restricted area";
auth_basic_user_file /etc/nginx/.htpasswd;

location ~ \.php$ {
fastcgi_pass unix:/run/php-fpm/www.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
include fastcgi_params;
}
}

あとはnginx再起動。

メールサーバ(送信)

Postfixの設定。

# dnf install postfix cyrus-sasl cyrus-sasl-md5 cyrus-sasl-plain

# vi /etc/postfix/main.cf
以下のように修正
myhostname = www????.sakura.ne.jp
mydomain = www????.sakura.ne.jp
myorigin = $mydomain
inet_interfaces = all
#inet_interfaces = localhost
inet_protocols = ipv4
home_mailbox = Maildir/
smtpd_banner = $myhostname ESMTP unknown

以下を追加(スパム対策)
disable_vrfy_command = yes
smtpd_helo_required = yes
anvil_rate_time_unit=60s
smtpd_client_message_rate_limit=200
smtpd_soft_error_limit = 5
smtpd_hard_error_limit = 8
smtpd_error_sleep_time = 70
smtpd_delay_reject = yes

以下を追加(スパムをメールアドレス単位で拒否する場合。reject_senderに記述。正規表現を使う場合はhashをregexpにする)
smtpd_sender_restrictions = reject_unknown_sender_domain,reject_non_fqdn_sender hash:/etc/postfix/reject_sender

以下を追加(バーチャルドメイン用)
virtual_alias_maps = hash:/etc/postfix/virtual

以下を追加(SMTP-Auth用)
smtpd_sasl_auth_enable = yes
smtpd_sasl_type = cyrus
smtpd_sasl_path = smtpd
smtpd_sasl_local_domain = $myhostname
smtpd_recipient_restrictions = permit_mynetworks,permit_sasl_authenticated,reject_unauth_destination
smtpd_relay_restrictions = permit_mynetworks,permit_sasl_authenticated,reject_unauth_destination

以下を追加(メールへの添付可能サイズを無制限にする)
message_size_limit = 0
mailbox_size_limit = 0

以下を追加(SSL化する場合)
tls_server_sni_maps=hash:/etc/postfix/tls_server_sni_maps
smtp_tls_security_level = may

スパムを登録して反映。ドメインかメールアドレスで指定できる。

# vi /etc/postfix/reject_sender

example.com REJECT
spam@example.com REJECT

正規表現(regexp)の場合は以下のようになる。

/@example\.com$/ REJECT
/spam@example\.com$/ REJECT
/.*@example\.com$/ REJECT
# postmap /etc/postfix/reject_sender

メール送信時にサブミッションポート(587)を使用します。

# vi /etc/postfix/master.cf

以下の行のコメントアウトを外す
submission inet n - n - - smtpd
-o smtpd_sasl_auth_enable=yes
-o smtpd_relay_restrictions=permit_sasl_authenticated,reject
-o milter_macro_daemon_name=ORIGINATING

SSL化する場合以下の行のコメントアウトも外す
smtps inet n - n - - smtpd
-o smtpd_tls_wrappermode=yes
-o smtpd_sasl_auth_enable=yes
-o smtpd_recipient_restrictions=permit_sasl_authenticated,reject

SSL化する場合証明書を記述、再起動。

# vi /etc/postfix/tls_server_sni_maps

hoge.com /etc/letsencrypt/live/hoge.com/privkey.pem /etc/letsencrypt/live/hoge.com/fullchain.pem
# postmap /etc/postfix/tls_server_sni_maps
# systemctl restart postfix

起動。

# systemctl start postfix
# systemctl enable postfix

SMTP認証のためにSaslauthdを使用します。アプリと認証処理を分離してくれるものらしい。

# vi /etc/sysconfig/saslauthd

Linuxユーザのパスワード(/etc/shadow)を使う
MECH=shadow

起動します。

# systemctl enable saslauthd
# systemctl start saslauthd

メールサーバ(受信)

Dovecotの設定。

# dnf install dovecot

# vi /etc/dovecot/conf.d/10-mail.conf
以下の行のコメントアウトを外す
mail_location = maildir:~/Maildir
# vi /etc/dovecot/dovecot.conf
protocols = imap pop3 lmtp
listen = *
# vi /etc/dovecot/conf.d/10-auth.conf
パスワードを平文にする
disable_plaintext_auth = no
# vi /etc/dovecot/conf.d/10-ssl.conf
SSL有り無し両方対応
ssl = yes

SSL化する場合以下追加
local_name hoge.com {
ssl_cert = </etc/letsencrypt/live/hoge.com/fullchain.pem
ssl_key = </etc/letsencrypt/live/hoge.com/privkey.pem
}

Dovecotを起動します。

# systemctl enable dovecot
# systemctl start dovecot

useradd時にメールボックス用のディレクトリを自動で作成されるようにします。

# mkdir -p /etc/skel/Maildir/{new,cur,tmp}
# chmod -R 700 /etc/skel/Maildir/

こんな感じで作られる。

/home/hoge-info/Maildir/new/
/home/hoge-info/Maildir/cur/
/home/hoge-info/Maildir/tmp/

メールアドレス作成

メールアカウント用のユーザをシェルログイン不可で作成します。

# useradd -s /sbin/nologin hoge-info
# passwd hoge-info

メールアドレスとその振り分け処理を作成します。ドメインごとにanythingの行を入れないとメールが使用できません。

# vi /etc/postfix/virtual

hoge.com         anything
info@hoge.com hoge-info
web@hoge.com hoge-web

振り分けを反映させます。

# postmap /etc/postfix/virtual

まとめ

WordPressの設定は毎回忘れる…