技術屋見習いのメモ帳

技術屋見習いのメモ帳です。

CentOS8+Let's Encrypt(certbot)でCloudflareで管理しているドメインのワイルドカード証明書を取得する。

f:id:takashun_0704:20200622022900p:plain

前回までの記事でサーバーの導入は終了しているので、今回は証明書の取得とNginxへのドメインの設定を行います。

 

 前回記事はこちら

takashun.hatenablog.com

余談:Cloudflareの設定

Cloudflareの設定を見てみると、暗号化モードの中に「フル」というものがあります。これはサーバーの証明書が所謂オレオレ証明書(もしくは期限切れ)でもエラーが出ずに接続することができるモードですが、今回は「フル(厳密)」に設定して証明書を更新し続ける環境を目指します。

f:id:takashun_0704:20200622023452p:plain

certbotの導入

Let's Encryptのクライアントはいくつかありますが(acme.shとか)、今回は公式のオススメクライアントである「certbot」を使用します。

letsencrypt.org

# dnf install python38 git -y #Python3.8とgitをインストール
# cd /usr/local/src/ #適当なディレクトリに移動
# git clone https://github.com/certbot/certbot.git
# cd /usr/local/src/certbot/certbot
# python3 setup.py install #インストールを実行

certbot-dns-cloudflareの導入

# cd /usr/local/src/certbot/certbot-dns-cloudflare
# python3 setup.py install

Global API Keyをhttps://www.cloudflare.com/a/profileから取得して保存します。

# mkdir /root/.cloudflare
# chmod 700 /root/.cloudflare
# echo "dns_cloudflare_email = (メールアドレス)" > /root/.cloudflare/credentials
# echo "dns_cloudflare_api_key = (Global API Key)" >> /root/.cloudflare/credentials
# chmod 600 /root/.cloudflare/credentials

コマンドを実行して証明書を取得します。色々聞かれるので適切な回答をしてください。

# certbot certonly \
  --dns-cloudflare \
  --dns-cloudflare-credentials /root/.cloudflare/credentials \
  --dns-cloudflare-propagation-seconds 30 \
  -d example.com \
  -d *.example.com

 成功したら/etc/letsencrypt/live/example.comに証明書が保存されています。

Nginxの設定

あとはNginxの設定を書くだけです。

 ※/etc/nginx/conf.dにdefault.confが存在しますが、削除するか下記内容で上書きすることをおすすめします。

#cd /etc/nginx/conf.d
#vim example.com.conf
server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

server {
    listen              443 ssl http2;
    server_name         example.com;
    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-128-GCM-SHA256:TLS13-AES-128-GCM-SHA256:TLS13-AES-128-CCM-8-SHA256:TLS13-AES-128-CCM-SHA256:EECDH+ECDSA+AESGCM:EECDH+aRSA+AESGCM:EECDH+ECDSA+SHA512:EECDH+ECDSA+SHA384:EECDH+ECDSA+SHA256:ECDH+AESGCM:ECDH+AES256:DH+AESGCM:DH+AES256:!aNULL:!eNULL:!LOW:!RC4:!3DES:!MD5:!EXP:!PSK:!SRP:!DSS;

    location / {
        root   /usr/share/nginx/html/;
        index  index.html index.htm;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

firewallの設定を忘れずに。

#firewall-cmd --add-service=https --zone=public --permanent
# firewall-cmd --add-service=http --zone=public --permanent
firewall-cmd --reload

動作確認

f:id:takashun_0704:20200622043206p:plain

ヨシ!

自動更新の設定

# crontab -e
00 05 01 * * /usr/local/bin/certbot renew && /usr/bin/systemctl restart nginx

まとめ

設定しながら書いたのでなぐりがきにもほどがありますが許して下さい。

次回はnodeアプリを実行してnginxをリバースプロキシとして動作させます。