はじめに
※これは現在進行系で実験をしている鯖でのことです。
この手順を踏んでなにかトラブルになったとしても責任は負いません。
ご意見・こういうことしたほうがいいよなど募集しています!是非コメントまで
PR
よろしければTwitterもフォローしてね!
Twitter - @server_inn
環境説明
カゴヤジャパン社のVPS<KAGOYA CLOUD/2> KVMプランでやってます。
PLAN | KAGOYA CLOUD/2 KVM |
---|---|
CPU | 2コア |
メモリ | 2GB |
ストレージ | 30GB(SSD) |
virtio | ON |
月額換算 | 約961円 |
OS | Centos7 64bit |
萬屋、構築始めるってよ
とりあえず初期設定
カゴヤのVPSは初期状態でSELinuxが入っていてファイヤーウォールがない(あっぱっぱーな)状態なのでそこを設定します。
ログインは認証キーを使ってのSSHログインです。ここも危ないのでのちのち作業っす。
# yum -y update
# yum -y groupinstall 'Development tools'
# yum -y install epel-release
# rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-7.rpm
# yum -y install nano wget iptables-services
Iptableの設定
この構築の方法はCentOSで自宅サーバー構築さんの ファイアウォール構築(iptables)を利用しております。
この場を借りて、素晴らしい情報をいただきましたサイト管理人様へ感謝申し上げます。
#nano iptables.sh
で、↓を入力
#!/bin/bash
#---------------------------------------#
# 設定開始 #
#---------------------------------------#
# 内部ネットワークアドレス定義
LOCALNET=192.168.1.0/24
#---------------------------------------#
# 設定終了 #
#---------------------------------------#
# デフォルトルール(以降のルールにマッチしなかった場合に適用するルール)設定
IPTABLES_CONFIG=`mktemp`
echo "*filter" >> $IPTABLES_CONFIG
echo ":INPUT DROP [0:0]" >> $IPTABLES_CONFIG # 受信はすべて破棄
echo ":FORWARD DROP [0:0]" >> $IPTABLES_CONFIG # 通過はすべて破棄
echo ":OUTPUT ACCEPT [0:0]" >> $IPTABLES_CONFIG # 送信はすべて許可
echo ":ACCEPT_COUNTRY - [0:0]" >> $IPTABLES_CONFIG # 指定した国からのアクセスを許可
echo ":DROP_COUNTRY - [0:0]" >> $IPTABLES_CONFIG # 指定した国からのアクセスを破棄
echo ":LOG_PINGDEATH - [0:0]" >> $IPTABLES_CONFIG # Ping of Death攻撃はログを記録して破棄
# 自ホストからのアクセスをすべて許可
echo "-A INPUT -i lo -j ACCEPT" >> $IPTABLES_CONFIG
# 内部からのアクセスをすべて許可
echo "-A INPUT -s $LOCALNET -j ACCEPT" >> $IPTABLES_CONFIG
# 内部から行ったアクセスに対する外部からの返答アクセスを許可
echo "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT" >> $IPTABLES_CONFIG
# SYN Cookiesを有効にする
# ※TCP SYN Flood攻撃対策
sysctl -w net.ipv4.tcp_syncookies=1 > /dev/null
sed -i '/net.ipv4.tcp_syncookies/d' /etc/sysctl.conf
echo "net.ipv4.tcp_syncookies=1" >> /etc/sysctl.conf
# ブロードキャストアドレス宛pingには応答しない
# ※Smurf攻撃対策
sysctl -w net.ipv4.icmp_echo_ignore_broadcasts=1 > /dev/null
sed -i '/net.ipv4.icmp_echo_ignore_broadcasts/d' /etc/sysctl.conf
echo "net.ipv4.icmp_echo_ignore_broadcasts=1" >> /etc/sysctl.conf
# ICMP Redirectパケットは拒否
sed -i '/net.ipv4.conf.*.accept_redirects/d' /etc/sysctl.conf
for dev in `ls /proc/sys/net/ipv4/conf/`
do
sysctl -w net.ipv4.conf.$dev.accept_redirects=0 > /dev/null
echo "net.ipv4.conf.$dev.accept_redirects=0" >> /etc/sysctl.conf
done
# Source Routedパケットは拒否
sed -i '/net.ipv4.conf.*.accept_source_route/d' /etc/sysctl.conf
for dev in `ls /proc/sys/net/ipv4/conf/`
do
sysctl -w net.ipv4.conf.$dev.accept_source_route=0 > /dev/null
echo "net.ipv4.conf.$dev.accept_source_route=0" >> /etc/sysctl.conf
done
# フラグメント化されたパケットはログを記録して破棄
echo "-A INPUT -f -j LOG --log-prefix \"[IPTABLES FRAGMENT] : \"" >> $IPTABLES_CONFIG
echo "-A INPUT -f -j DROP" >> $IPTABLES_CONFIG
# 外部とのNetBIOS関連のアクセスはログを記録せずに破棄
# ※不要ログ記録防止
echo "-A INPUT ! -s $LOCALNET -p tcp -m multiport --dports 135,137,138,139,445 -j DROP" >> $IPTABLES_CONFIG
echo "-A INPUT ! -s $LOCALNET -p udp -m multiport --dports 135,137,138,139,445 -j DROP" >> $IPTABLES_CONFIG
echo "-A OUTPUT ! -d $LOCALNET -p tcp -m multiport --sports 135,137,138,139,445 -j DROP" >> $IPTABLES_CONFIG
echo "-A OUTPUT ! -d $LOCALNET -p udp -m multiport --sports 135,137,138,139,445 -j DROP" >> $IPTABLES_CONFIG
# 1秒間に4回を超えるpingはログを記録して破棄
# ※Ping of Death攻撃対策
echo "-A LOG_PINGDEATH -m limit --limit 1/s --limit-burst 4 -j ACCEPT" >> $IPTABLES_CONFIG
echo "-A LOG_PINGDEATH -j LOG --log-prefix \"[IPTABLES PINGDEATH] : \"" >> $IPTABLES_CONFIG
echo "-A LOG_PINGDEATH -j DROP" >> $IPTABLES_CONFIG
echo "-A INPUT -p icmp --icmp-type echo-request -j LOG_PINGDEATH" >> $IPTABLES_CONFIG
# 全ホスト(ブロードキャストアドレス、マルチキャストアドレス)宛パケットはログを記録せずに破棄
# ※不要ログ記録防止
echo "-A INPUT -d 255.255.255.255 -j DROP" >> $IPTABLES_CONFIG
echo "-A INPUT -d 224.0.0.1 -j DROP" >> $IPTABLES_CONFIG
# 113番ポート(IDENT)へのアクセスには拒否応答
# ※メールサーバ等のレスポンス低下防止
echo "-A INPUT -p tcp --dport 113 -j REJECT --reject-with tcp-reset" >> $IPTABLES_CONFIG
# ACCEPT_COUNTRY_MAKE関数定義
# 指定された国のIPアドレスからのアクセスを許可するユーザ定義チェイン作成
ACCEPT_COUNTRY_MAKE(){
for addr in `cat /tmp/cidr.txt|grep ^$1|awk '{print $2}'`
do
echo "-A ACCEPT_COUNTRY -s $addr -j ACCEPT" >> $IPTABLES_CONFIG
done
grep ^$1 $IP_LIST >> $CHK_IP_LIST
}
# DROP_COUNTRY_MAKE関数定義
# 指定された国のIPアドレスからのアクセスを破棄するユーザ定義チェイン作成
DROP_COUNTRY_MAKE(){
for addr in `cat /tmp/cidr.txt|grep ^$1|awk '{print $2}'`
do
echo "-A DROP_COUNTRY -s $addr -m limit --limit 1/s -j LOG --log-prefix \"[IPTABLES DENY_COUNTRY] : \"" >> $IPTABLES_CONFIG
echo "-A DROP_COUNTRY -s $addr -j DROP" >> $IPTABLES_CONFIG
done
grep ^$1 $IP_LIST >> $CHK_IP_LIST
}
# IPアドレスリスト取得
IP_LIST=/tmp/cidr.txt
CHK_IP_LIST=/tmp/IPLIST
if [ ! -f $IP_LIST ]; then
wget -q http://nami.jp/ipv4bycc/cidr.txt.gz
gunzip -c cidr.txt.gz > $IP_LIST
rm -f cidr.txt.gz
fi
rm -f $CHK_IP_LIST
# 日本からのアクセスを許可するユーザ定義チェインACCEPT_COUNTRY作成
ACCEPT_COUNTRY_MAKE JP
# 以降,日本からのみアクセスを許可したい場合はACCEPTのかわりにACCEPT_COUNTRYを指定する
# 全国警察施設への攻撃元上位5カ国(日本・アメリカを除く)からのアクセスをログを記録して破棄
# 直近1週間の状況 http://www.npa.go.jp/cyberpolice/detect/observation.html
# 前月の状況 https://www.npa.go.jp/cyberpolice/detect/
# 国名と国コードの対応表 https://msdn.microsoft.com/ja-jp/library/ee783931(v=cs.10).aspx
DROP_COUNTRY_MAKE CN
DROP_COUNTRY_MAKE RU
DROP_COUNTRY_MAKE MX
DROP_COUNTRY_MAKE IN
DROP_COUNTRY_MAKE NL
echo "-A INPUT -j DROP_COUNTRY" >> $IPTABLES_CONFIG
#----------------------------------------------------------#
# WEBサービスを公開する場合の設定 #
#----------------------------------------------------------#
# 外部からのTCP22番ポート(SSH)へのアクセスを日本からのみ許可
echo "-A INPUT -p tcp --dport 22 -j ACCEPT_COUNTRY" >> $IPTABLES_CONFIG
# 外部からのTCP80番ポート(HTTP) TCP443番ポート(HTTPS)へのアクセスを許可
echo "-A INPUT -p tcp --dport 80 -j ACCEPT" >> $IPTABLES_CONFIG
echo "-A INPUT -p tcp --dport 443 -j ACCEPT" >> $IPTABLES_CONFIG
#----------------------------------------------------------#
# メールサービスを公開する場合の設定 #
#----------------------------------------------------------#
# 外部からのTCP25番ポート(SMTP) TCP465番ポート(SMTPS)へのアクセスを許可
echo "-A INPUT -p tcp --dport 25 -j ACCEPT" >> $IPTABLES_CONFIG
echo "-A INPUT -p tcp --dport 465 -j ACCEPT_COUNTRY" >> $IPTABLES_CONFIG
# 外部からのTCP110番ポート(POP3) TCP995番ポート(POP3S)へのアクセスを日本からのみ許可
echo "-A INPUT -p tcp --dport 110 -j ACCEPT_COUNTRY" >> $IPTABLES_CONFIG
echo "-A INPUT -p tcp --dport 995 -j ACCEPT_COUNTRY" >> $IPTABLES_CONFIG
# 外部からのTCP143番ポート(IMAP) TCP993番ポート(IMAPS)へのアクセスを日本からのみ許可
echo "-A INPUT -p tcp --dport 143 -j ACCEPT_COUNTRY" >> $IPTABLES_CONFIG
echo "-A INPUT -p tcp --dport 993 -j ACCEPT_COUNTRY" >> $IPTABLES_CONFIG
#----------------------------------------------------------#
# 設定(ここまで) #
#----------------------------------------------------------#
# 拒否IPアドレスからのアクセスはログを記録せずに破棄
# ※拒否IPアドレスは/root/deny_ipに1行ごとに記述しておくこと
# (/root/deny_ipがなければなにもしない)
if [ -s /root/deny_ip ]; then
for ip in `cat /root/deny_ip`
do
echo "-I INPUT -s $ip -j DROP" >> $IPTABLES_CONFIG
done
fi
# 上記のルールにマッチしなかったアクセスはログを記録して破棄
echo "-A INPUT -m limit --limit 1/s -j LOG --log-prefix \"[IPTABLES INPUT] : \"" >> $IPTABLES_CONFIG
echo "-A INPUT -j DROP" >> $IPTABLES_CONFIG
echo "-A FORWARD -m limit --limit 1/s -j LOG --log-prefix \"[IPTABLES FORWARD] : \"" >> $IPTABLES_CONFIG
echo "-A FORWARD -j DROP" >> $IPTABLES_CONFIG
# ファイアウォール設定反映
echo "COMMIT" >> $IPTABLES_CONFIG
cat $IPTABLES_CONFIG > /etc/sysconfig/iptables
if [ -f /usr/libexec/iptables/iptables.init ]; then
/usr/libexec/iptables/iptables.init restart
else
/etc/rc.d/init.d/iptables restart
fi
rm -f $IPTABLES_CONFIG
なお、国内・国外判定などでIPアドレスのリストを更新するプログラムが必要なので作ります。
# nano /etc/cron.daily/iplist_check.sh
#!/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# 新旧IPLIST差分チェック件数(0を指定するとチェックしない)
# ※新旧IPLIST差分がSABUN_CHKで指定した件数を越える場合はiptables設定スクリプトを実行しない
# ※新旧IPLIST差分チェック理由はhttp://centossrv.com/bbshtml/webpatio/1592.shtmlを参照
SABUN_CHK=100
[ $# -ne 0 ] && SABUN_CHK=${1}
# IPアドレスリスト取得
IP_LIST=/tmp/cidr.txt
CHK_IP_LIST=/tmp/IPLIST
wget -q http://nami.jp/ipv4bycc/cidr.txt.gz
gunzip -c cidr.txt.gz > $IP_LIST
rm -f cidr.txt.gz
# チェック対象IPアドレスリスト最新化
rm -f IPLIST.new
for country in `awk '{print $1}' $CHK_IP_LIST |uniq`
do
grep ^$country $IP_LIST >> IPLIST.new
done
# チェック対象IPアドレスリスト更新チェック
diff -q $CHK_IP_LIST IPLIST.new > /dev/null 2>&1
if [ $? -ne 0 ]; then
if [ ${SABUN_CHK} -ne 0 ]; then
if [ $(diff $CHK_IP_LIST IPLIST.new | egrep -c '<|>') -gt ${SABUN_CHK} ]; then
(
diff $CHK_IP_LIST IPLIST.new
echo
echo "iptables.sh not executed."
) | mail -s 'IPLIST UPDATE' root
rm -f IPLIST.new
exit
fi
fi
/bin/mv IPLIST.new $CHK_IP_LIST
sh /root/iptables.sh > /dev/null
else
rm -f IPLIST.new
fi
IPアドレスリストチェックスクリプトに実行権限付加+実行
# chmod +x /etc/cron.daily/iplist_check.sh
# sh /etc/cron.daily/iplist_check.sh
一回目はファイルが存在しないのでエラーを吐きますけど二回目からは問題ありませんので大丈夫っす。
そしたら、Iptable起動して保護状態へ。定期的にログは見に行きましょうね。
# sh iptables.sh
# systemctl enable iptables
SELinuxの無効化
SELinuxですが、今回NginxからApacheへのデータ受け渡しに支障が出る場合がありますので切るor穴を開ける必要があります。
孔を開ける場合は以下の設定は不要ですが、一応かいておきます。(SELinuxを完全に無効にする方法)
# nano /etc/selinux/config
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
# enforcing - SELinux security policy is enforced.
# permissive - SELinux prints warnings instead of enforcing.
# disabled - No SELinux policy is loaded.
#SELINUX=enforcing ここを無効化して↓を入力する
SELINUX=disable
再起動すると完全にSELinuxが無効になります。
WEBサイドの構築
PHPの設定
Yumで一気にインストール行きます。
# yum -y install --enablerepo=remi,remi-php72 php php-devel php-mbstring php-pdo php-gd php-fpm php-mysqlnd
# nano /etc/php.ini
php.iniを編集する。(各種チューニング)
下の値はチューニング済みなのでそのままお使いいただけます。
#POST容量を適時変更します
; Maximum size of POST data that PHP will accept.
; Its value may be 0 to disable the limit. It is ignored if POST data reading
; is disabled through enable_post_data_reading.
; http://php.net/post-max-size
post_max_size = 20M
#アップロードファイル容量を適時変更します(phpMyAdminでダンプファイル入れようとするとよくここで引っかかる)
; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 20M
#タイムゾーンの設定
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone = Asia/Tokyo
#セッションのPIDはちょっとおおめにしておきましょう
; Set session ID character length. This value could be between 22 to 256.
; Shorter length than default is supported only for compatibility reason.
; Users should use 32 or more chars.
; http://php.net/session.sid_length
; Default Value: 32
; Development Value: 26
; Production Value: 26
session.sid_length = 32
#mbstringの言語設定
; language for internal character representation.
; This affects mb_send_mail() and mbstring.detect_order.
; http://php.net/mbstring.language
mbstring.language = Japanese
お疲れ様です!php.iniは結構行数が多いので、みんな探すのが大変ですよね
PHP-FPMの設定
NginxだとFastCgi使用にしますが、今回はApache上でphpは回すので、少しのチューニングだけです。
# nano /etc/php-fpm.d/www.conf
以下の設定を適用します(値はすでに調整済み)
; Set permissions for unix socket, if one is used. In Linux, read/write
; permissions must be set in order to allow connections from a web server.
; Default Values: user and group are set as the running user
; mode is set to 0660
listen.owner = nobody
listen.group = nobody
Apache(httpd) のインストールと設定
ここで一つ注意なのですが、今回、Nginx側でSSLを利用します。
ですが、ApacheもSSL通信をしようとしてしまいますのであえてここでmod_sslをインストールして設定ファイルでSSL通信を無効にします。
# yum -y install httpd mod_ssl
# /etc/httpd/conf/httpd.conf
設定しまーす!(値は変更済みのものを表示しています)
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
#Listen 80 # ポートを他のポートへ設定する。
Listen 8080
(中略)
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.4/mod/core.html#options
# for more information.
#
Options Includes ExecCGI FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride All
# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
AddHandler cgi-script .cgi .pl
#最終行に挿入する
TraceEnable off
つづいて、autoindexも触ります。
# nano /etc/httpd/conf.d/autoindex.conf
<Directory "/usr/share/httpd/icons">
Options MultiViews
AllowOverride None
Require all granted
</Directory>
mod_sslの設定をします。
# nano /etc/httpd/conf.d/ssl.conf
#
# When we also provide SSL we have to listen to the
# the HTTPS port in addition.
#
#Listen 443 https ##コメント化して無効にする。
# SSL Engine Switch:
# Enable/Disable SSL for this virtual host.
SSLEngine off ##SSLエンジンをOFFにする
ここまで設定したらPerlの調整(リンク先変更)とApacheの起動をします。
# ln -s /usr/bin/perl /usr/local/bin/perl
# systemctl start httpd
# systemctl enable httpd
もし、ここでApacheのテストをしたいって場合は、一度Iptablesを停止して http://サーバーIP:8080/と打ち込むとApacheのいつものテスト画面が表示されます。
nginxのインストールと設定
この構築の方法は@hioriさんの CentOS 7.4に最新のNginx+PHP+MariaDB環境を構築を利用しております。
この場を借りて、素晴らしい情報を載せていただいております、@hiori様へ感謝申し上げます。
インストールと設定
yumでインストールされるNginxは古いバージョンです(危険)
リポジトリを手動で入力してインストールしましょう。
# nano /etc/yum.repos.d/nginx.repo
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/mainline/centos/7/$basearch/
enabled=0
gpgcheck=0
追加完了したら早速インストールしましょう!
その後、設定をします。
# yum -y --enablerepo=nginx install nginx
# mv /etc/nginx/nginx.conf /etc/nginx/nginx.conf.org
# nano /etc/nginx/nginx.conf
既存の設定は横においておいて、新しく設定を構築します。
user nginx;
worker_processes auto;
worker_cpu_affinity auto;
worker_rlimit_nofile 4096;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
index index.html index.php;
server_tokens off;
access_log off;
charset UTF-8;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
sendfile on;
tcp_nopush on;
keepalive_timeout 60;
gzip on;
gzip_disable "msie6";
gzip_min_length 1024;
gzip_types text/css
image/gif
image/png
image/jpeg
application/javascript;
server {
listen 80 default_server;
return 444;
log_not_found off;
}
include /etc/nginx/conf.d/*.conf;
}
では、リバースプロキシの設定をしましょう!
# nano /etc/nginx/conf.d/reverse_proxy.conf
server {
listen 80;
server_name example.com; ##ドメインを書き換えてください。
client_max_body_size 20M;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
これでリバースプロキシは完成です!一旦保存してnginxを起動させましょう。
# systemctl start nginx
# systemctl enable nginx
もし、502 Bad Gatewayがでたら
先程のSELinuxの設定をしていないのであれば、以下のコマンドを打つとだいたい回避できます。
SELinuxへ穴を開ける方法です。
setsebool -P httpd_can_network_connect 1
Testing123..が表示されましたか?
この状態であれば、リバースプロキシが完了しています。
Nginxなのに.htacessが使える環境へようこそ!
SQLサーバー(MariaDB)構築
Wordpressに必要なSQLサーバーを構築します。なお、Centos7からはMysqlではなくMariaDBが対象になっています。
また、yumでインストールされる(すでに一部入っている)MariaDBはかなり古いので入れ替えます。
# yum remove -y mariadb-libs
# nano /etc/yum.repos.d/MariaDB.repo
[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.2/centos7-amd64
gpgkey = https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
enabled = 0
gpgcheck = 1
# yum -y --enablerepo=mariadb install MariaDB-server MariaDB-client
# nano /etc/my.cnf.d/server.cnf
MariaDBサーバーの文字コードをUTF-8に、メモリーキャッシュ容量を変更します。
[mysqld]
character-set-server = utf8
innodb_buffer_pool_size=1G
MariaDB起動と初期設定
# systemctl start mariadb
# systemctl enable mariadb
# mysql_secure_installation
Enter current password for root (enter for none): 空Enter
Set root password? [Y/n] y
New password: パスワードを入力
Re-enter new password: パスワードを入力
Remove anonymous users? [Y/n] y
Disallow root login remotely? [Y/n] y
Remove test database and access to it? [Y/n] y
Reload privilege tables now? [Y/n] y
Thanks for using MariaDB!
初期設定が終わったら、ユーザーを作成しましょう。
今回はユーザー名/データベース名が【 loon 】 パスワードは【 XYQ7jxfXah 】で設定します。
ここは各自読み替えてくださいませ。
# mysql -u root -p
Enter password:rootパスワード応答
MariaDB [(none)]> grant all privileges on loon.* to loon@localhost identified by 'XYQ7jxfXah';
MariaDB [(none)]> create database loon;
MariaDB [(none)]> exit;
これで終わり?いいえ?ケフィアです。
Nginxの真骨頂!https(SSL)通信編
みなさん、Nginxと言ったら何を思い浮かべますか?
・通信速度が早い?
・リバースプロキシ
・玄人向け ...etc
でもでも!もっとすごいのがあるよね!
HTTP/2
nginxといえばhttp/2。なのでこれの設定をしようかなと思います!
なお、HTTP/2にはSSL証明書が必要です。
# cd /usr/local/
# git clone https://github.com/certbot/certbot
# cd
# /usr/local/certbot/certbot-auto -n
# /usr/local/certbot/certbot-auto certonly --webroot
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator webroot, Installer None
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): #<=メールアドレス入力
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v02.api.letsencrypt.org/directory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(A)gree/(C)ancel: #<=規約に同意するかどうか
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about our work
encrypting the web, EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: #<=今後、ニュースを送ったりしてもいいかどうか
Please enter in your domain name(s) (comma and/or space separated) (Enter 'c'
to cancel): ドメイン #<=ドメイン入力
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for ドメイン名
Input the webroot for ドメイン名: (Enter 'c' to cancel): /var/www/html #<=ルートを入力
Waiting for verification...
Cleaning up challenges
IMPORTANT NOTES:
- Congratulations! Your certificate and chain have been saved at:
/etc/letsencrypt/live/ドメイン名/fullchain.pem
Your key file has been saved at:
/etc/letsencrypt/live/ドメイン名/privkey.pem
Your cert will expire on 2018-12-31. To obtain a new or tweaked
version of this certificate in the future, simply run certbot-auto
again. To non-interactively renew *all* of your certificates, run
"certbot-auto renew"
- Your account credentials have been saved in your Certbot
configuration directory at /etc/letsencrypt. You should make a
secure backup of this folder now. This configuration directory will
also contain certificates and private keys obtained by Certbot so
making regular backups of this folder is ideal.
- If you like Certbot, please consider supporting our work by:
Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate
Donating to EFF: https://eff.org/donate-le
これでLet'sEncryptの証明書が完成しました。
なお、Let'sEncryptは有効期限が3ヶ月なので毎月更新するように設定しましょうね。
# nano /etc/cron.monthly/certbot
#!/bin/sh
log=`mktemp`
code=0
#
# 証明書更新
#
for conf in `ls /etc/letsencrypt/renewal/`
do
# ドメイン名取得
domain=`echo ${conf}|sed -e 's/\([^ ]*\)\.conf/\1/p' -e d`
# 認証方式取得
authenticator=`grep authenticator /etc/letsencrypt/renewal/${conf}|awk '{print $3}'`
if [ ${authenticator} = 'webroot' ]; then
# Web認証の場合
# ドキュメントルート取得
webroot=`grep -A 1 webroot_map /etc/letsencrypt/renewal/${conf}|grep =|awk '{print $3}'`
# 証明書更新
/usr/local/certbot/certbot-auto certonly --webroot \
-w ${webroot} -d ${domain} --renew-by-default >> ${log} 2>&1
[ $? -ne 0 ] && cat ${log}
else
# スタンドアロン認証の場合
# 証明書更新
lsof -i:80 > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo 'Webサーバー稼働中のためスタンドアロン認証不可'
else
/usr/local/certbot/certbot-auto certonly -a standalone \
-d ${domain} --renew-by-default >> ${log} 2>&1
[ $? -ne 0 ] && cat ${log}
fi
fi
done
#
# 証明書更新反映
#
# Webサーバー設定再読込み
lsof -i:443 > /dev/null 2>&1
if [ $? -eq 0 ]; then
rpm -q systemd > /dev/null 2>&1
if [ $? -eq 0 ]; then
systemctl reload httpd
else
/etc/rc.d/init.d/httpd reload > /dev/null 2>&1
fi
fi
# SMTPサーバー設定再読込み
lsof -i:465 > /dev/null 2>&1
if [ $? -eq 0 ]; then
rpm -q systemd > /dev/null 2>&1
if [ $? -eq 0 ]; then
systemctl reload postfix
else
/etc/rc.d/init.d/postfix reload > /dev/null 2>&1
fi
fi
# IMAPサーバー設定再読込み
lsof -i:995 > /dev/null 2>&1
if [ $? -eq 0 ]; then
rpm -q systemd > /dev/null 2>&1
if [ $? -eq 0 ]; then
systemctl reload dovecot
else
/etc/rc.d/init.d/dovecot reload > /dev/null 2>&1
fi
fi
#
# ログをsyslogへ出力後削除
#
cat ${log}|logger -t `basename ${0}` ; rm -f ${log}
保存したら権限を上げてCronが回るようにしましょう。
# chmod +x /etc/cron.monthly/certbot
お疲れ様でした。証明書のパスは、以下のとおりです。
/etc/letsencrypt/live/ドメイン名/fullchain.pem #証明書と中間証明書がセットになったもの
/etc/letsencrypt/live/ドメイン名/privkey.pem #秘密鍵
では、これをこれをNginx の設定ファイルに書き込みましょう。一緒に、HTTP/2の設定もご紹介します。
途中のSSLセキュリティ設定は、
https://www.ssllabs.com/ssltest/index.html でAを叩き出すことを目標に組んでいます。
# nano /etc/nginx/conf.d/reverse_proxy.conf
#SSL設定スタート#
server {
listen 443 ssl http2; # ここでSSLとHTTP/2を有効にする。
server_name example.com; ##ドメインを書き換えてください。
ssl_certificate /etc/letsencrypt/live/ドメイン名/fullchain.pem; # 証明書
ssl_certificate_key /etc/letsencrypt/live/ドメイン名/privkey.pem; #秘密鍵
client_max_body_size 20M;
#ここからSSLのセキュリティ強化。
ssl_prefer_server_ciphers on;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-EC$
add_header Strict-Transport-Security "max-age=31536000; includeSubdomains";
#SSLのセキュリティ強化以上#
location / {
proxy_pass http://127.0.0.1:8080;
proxy_redirect off;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $http_host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
#HTTPSじゃないのかつ、該当ドメインはリダイレクト。それ以外は404をお返しします。#
server {
if ($host = ドメイン名) {
return 301 https://$host$request_uri;
}
listen 80;
server_name example.com; ##ドメインを書き換えてください。
return 404;
}
我が鯖ではAを叩き出しました。これで十分なのですが、セキュリティは日々進歩しますし気をつけましょう。
Wordpressをインストールとするぜ!
では早速Wordpressをインストールしましょう!
ダウンロードURLは、https://ja.wordpress.org/を見て最新版を入れるようにしましょう。
# wget https://ja.wordpress.org/wordpress-4.9.8-ja.zip
# unzip wordpress-4.9.8-ja.zip
# cp -pR wordpress/* /var/www/html/
# chown -Rf apache:apache /var/www/html
Wordpressの設定やテーマのインストールなど此処から先に関してはみなさまでお願いいたします。
Google PageSpeed Insightsでは、標準状態で爆速と認定ですね。
これからのテンプレート制作が楽しみです。
では、本日はここまで!おつでした!
参考にさせていただきました。
CentOS 7.4に最新のNginx+PHP+MariaDB環境を構築
CentOS7にPHP7をyumでインストールする
Nginxのリーバスプロキシ化(Apacheと共存)
nginx で SSL リバースプロキシを構築
NginxでHTTP2を有効にする
NginxでのSSL設定の細かい意味
Webサーバー nginx における SSL証明書設定の安全性向上 ~SSL Server Test で A+ 判定を目指して~
NginxでSSLを設定する方法を基本から学ぶ
SSLサーバー証明書に中間証明書を結合する
Let's encrypt運用のベストプラクティス
Nginx で「502 Bad Gateway」とか、なんだかエラーログがでるよって時
nginx : Permission denied を解決
SELinuxの無効化
【ざっくりと理解する】SELinuxとは?