そういうのがいいブログ

SIerで働く30代サラリーマンSEがインフラエンジニアに憧れてLinux・クラウド・AWSの勉強をするブログ

CentOS8プライベート認証局(WEBサーバHTTPS化)【⑥ApacheにSSL設定】

※[PR]当ブログの記事の中にはプロモーションが含まれています。

・CentOS8でプライベート認証局を作って、LAN内のWEBサーバにHTTPSアクセスができるようにしたい。
・ネットで検索すると、新旧のいろいろな情報が出てきて、同じように真似してやってみたが上手くいかないので、最新の手順を詳しく知りたい。

こういった疑問に答えます。

本記事の内容

  1. CentOS8とOpenSSLでプライベート認証局(ルートCA)を作る方法
  2. CentOS8とOpenSSLで中間認証局を作る方法
  3. CentOS8のWEBサーバの証明書を作る方法
  4. CentOS8・ApacheのWEBサーバに証明書を設定してHTTPSアクセスを許可する方法

この記事を書いている私は、某SIerに勤務しながら、
WEB系エンジニア・インフラエンジニアに憧れて、プログラミングおよびインフラ技術の勉強をしています。

私が実機で試したコマンドや画像を載せて書いています。
記事の信頼性担保に繋がると思います。

前回の記事

前回の記事で、WEBサーバの証明書を作成するところまでが済みました。

souiunogaii.hatenablog.com

①~⑦までをまとめて読みたい方は下記のまとめ記事から。

souiunogaii.hatenablog.com

WEBサーバ(CentOS8)に、mod_sslインストール

dnf install mod_ssl
[root@sv-neptune conf.d]# dnf install mod_ssl
メタデータの期限切れの最終確認: 2:22:26 時間前の 20200912165250秒 に実施しました。
依存関係が解決しました。
========================================================================================================================
 パッケージ          アーキテクチャー   バージョン                                          リポジトリー          サイズ
========================================================================================================================
インストール中:
 mod_ssl             x86_64             1:2.4.37-21.module_el8.2.0+382+15b0afa8             AppStream             132 k

トランザクションの概要
========================================================================================================================
インストール  1 パッケージ

ダウンロードサイズの合計: 132 k
インストール済みのサイズ: 262 k
これでよろしいですか? [y/N]: y
パッケージのダウンロード:
mod_ssl-2.4.37-21.module_el8.2.0+382+15b0afa8.x86_64.rpm                                997 kB/s | 132 kB     00:00
------------------------------------------------------------------------------------------------------------------------
合計                                                                                    207 kB/s | 132 kB     00:00
トランザクションの確認を実行中
トランザクションの確認に成功しました。
トランザクションのテストを実行中
トランザクションのテストに成功しました。
トランザクションを実行中
  準備              :                                                                                               1/1
  インストール中    : mod_ssl-1:2.4.37-21.module_el8.2.0+382+15b0afa8.x86_64                                        1/1
  scriptlet の実行中: mod_ssl-1:2.4.37-21.module_el8.2.0+382+15b0afa8.x86_64                                        1/1
  検証              : mod_ssl-1:2.4.37-21.module_el8.2.0+382+15b0afa8.x86_64                                        1/1
Installed products updated.

インストール済み:
  mod_ssl-1:2.4.37-21.module_el8.2.0+382+15b0afa8.x86_64

完了しました!

firewalldにサービスHTTPSの許可を追加

firewall-cmd --add-service=https --zone=public --permanent
firewall-cmd --reload
[root@sv-neptune conf.d]# firewall-cmd --add-service=https --zone=public --permanent
success
[root@sv-neptune conf.d]# firewall-cmd --reload
success

SSLのconfファイルの修正

元の「ssl.conf」のバックアップ

cp /etc/httpd/conf.d/ssl.conf /etc/httpd/conf.d/ssl.conf.original_bk

ssl.conf」の修正

vi /etc/httpd/conf.d/ssl.conf
#
# When we also provide SSL we have to listen to the 
# standard HTTPS port in addition.
#
Listen 443 https

##
##  SSL Global Context
##
##  All SSL configuration in this context applies both to
##  the main server and all SSL-enabled virtual hosts.
##

#   Pass Phrase Dialog:
#   Configure the pass phrase gathering process.
#   The filtering dialog program (`builtin' is a internal
#   terminal dialog) has to provide the pass phrase on stdout.
SSLPassPhraseDialog exec:/usr/libexec/httpd-ssl-pass-dialog

#   Inter-Process Session Cache:
#   Configure the SSL Session Cache: First the mechanism 
#   to use and second the expiring timeout (in seconds).
SSLSessionCache         shmcb:/run/httpd/sslcache(512000)
SSLSessionCacheTimeout  300

#
# Use "SSLCryptoDevice" to enable any supported hardware
# accelerators. Use "openssl engine -v" to list supported
# engine names.  NOTE: If you enable an accelerator and the
# server does not start, consult the error logs and ensure
# your accelerator is functioning properly. 
#
SSLCryptoDevice builtin
#SSLCryptoDevice ubsec

##
## SSL Virtual Host Context
##

#<VirtualHost _default_:443>

# General setup for the virtual host, inherited from global configuration
#DocumentRoot "/var/www/html"
#ServerName www.example.com:443

# Use separate log files for the SSL virtual host; note that LogLevel
# is not inherited from httpd.conf.
#ErrorLog logs/ssl_error_log
#TransferLog logs/ssl_access_log
#LogLevel warn

#   SSL Engine Switch:
#   Enable/Disable SSL for this virtual host.
#SSLEngine on

#   List the protocol versions which clients are allowed to connect with.
#   The OpenSSL system profile is used by default.  See
#   update-crypto-policies(8) for more details.
#SSLProtocol all -SSLv3
#SSLProxyProtocol all -SSLv3

#   User agents such as web browsers are not configured for the user's
#   own preference of either security or performance, therefore this
#   must be the prerogative of the web server administrator who manages
#   cpu load versus confidentiality, so enforce the server's cipher order.
#SSLHonorCipherOrder on

#   SSL Cipher Suite:
#   List the ciphers that the client is permitted to negotiate.
#   See the mod_ssl documentation for a complete list.
#   The OpenSSL system profile is configured by default.  See
#   update-crypto-policies(8) for more details.
#SSLCipherSuite PROFILE=SYSTEM
#SSLProxyCipherSuite PROFILE=SYSTEM

#   Point SSLCertificateFile at a PEM encoded certificate.  If
#   the certificate is encrypted, then you will be prompted for a
#   pass phrase.  Note that restarting httpd will prompt again.  Keep
#   in mind that if you have both an RSA and a DSA certificate you
#   can configure both in parallel (to also allow the use of DSA
#   ciphers, etc.)
#   Some ECC cipher suites (http://www.ietf.org/rfc/rfc4492.txt)
#   require an ECC certificate which can also be configured in
#   parallel.
#SSLCertificateFile /etc/pki/tls/certs/localhost.crt

#   Server Private Key:
#   If the key is not combined with the certificate, use this
#   directive to point at the key file.  Keep in mind that if
#   you've both a RSA and a DSA private key you can configure
#   both in parallel (to also allow the use of DSA ciphers, etc.)
#   ECC keys, when in use, can also be configured in parallel
#SSLCertificateKeyFile /etc/pki/tls/private/localhost.key

#   Server Certificate Chain:
#   Point SSLCertificateChainFile at a file containing the
#   concatenation of PEM encoded CA certificates which form the
#   certificate chain for the server certificate. Alternatively
#   the referenced file can be the same as SSLCertificateFile
#   when the CA certificates are directly appended to the server
#   certificate for convenience.
#SSLCertificateChainFile /etc/pki/tls/certs/server-chain.crt

#   Certificate Authority (CA):
#   Set the CA certificate verification path where to find CA
#   certificates for client authentication or alternatively one
#   huge file containing all of them (file must be PEM encoded)
#SSLCACertificateFile /etc/pki/tls/certs/ca-bundle.crt

#   Client Authentication (Type):
#   Client certificate verification type and depth.  Types are
#   none, optional, require and optional_no_ca.  Depth is a
#   number which specifies how deeply to verify the certificate
#   issuer chain before deciding the certificate is not valid.
#SSLVerifyClient require
#SSLVerifyDepth  10

#   Access Control:
#   With SSLRequire you can do per-directory access control based
#   on arbitrary complex boolean expressions containing server
#   variable checks and other lookup directives.  The syntax is a
#   mixture between C and Perl.  See the mod_ssl documentation
#   for more details.
#<Location />
#SSLRequire (    %{SSL_CIPHER} !~ m/^(EXP|NULL)/ \
#            and %{SSL_CLIENT_S_DN_O} eq "Snake Oil, Ltd." \
#            and %{SSL_CLIENT_S_DN_OU} in {"Staff", "CA", "Dev"} \
#            and %{TIME_WDAY} >= 1 and %{TIME_WDAY} <= 5 \
#            and %{TIME_HOUR} >= 8 and %{TIME_HOUR} <= 20       ) \
#           or %{REMOTE_ADDR} =~ m/^192\.76\.162\.[0-9]+$/
#</Location>

#   SSL Engine Options:
#   Set various options for the SSL engine.
#   o FakeBasicAuth:
#     Translate the client X.509 into a Basic Authorisation.  This means that
#     the standard Auth/DBMAuth methods can be used for access control.  The
#     user name is the `one line' version of the client's X.509 certificate.
#     Note that no password is obtained from the user. Every entry in the user
#     file needs this password: `xxj31ZMTZzkVA'.
#   o ExportCertData:
#     This exports two additional environment variables: SSL_CLIENT_CERT and
#     SSL_SERVER_CERT. These contain the PEM-encoded certificates of the
#     server (always existing) and the client (only existing when client
#     authentication is used). This can be used to import the certificates
#     into CGI scripts.
#   o StdEnvVars:
#     This exports the standard SSL/TLS related `SSL_*' environment variables.
#     Per default this exportation is switched off for performance reasons,
#     because the extraction step is an expensive operation and is usually
#     useless for serving static content. So one usually enables the
#     exportation for CGI and SSI requests only.
#   o StrictRequire:
#     This denies access when "SSLRequireSSL" or "SSLRequire" applied even
#     under a "Satisfy any" situation, i.e. when it applies access is denied
#     and no other module can change it.
#   o OptRenegotiate:
#     This enables optimized SSL connection renegotiation handling when SSL
#     directives are used in per-directory context. 
#SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
#<FilesMatch "\.(cgi|shtml|phtml|php)$">
#    SSLOptions +StdEnvVars
#</FilesMatch>
#<Directory "/var/www/cgi-bin">
#    SSLOptions +StdEnvVars
#</Directory>

#   SSL Protocol Adjustments:
#   The safe and default but still SSL/TLS standard compliant shutdown
#   approach is that mod_ssl sends the close notify alert but doesn't wait for
#   the close notify alert from client. When you need a different shutdown
#   approach you can use one of the following variables:
#   o ssl-unclean-shutdown:
#     This forces an unclean shutdown when the connection is closed, i.e. no
#     SSL close notify alert is sent or allowed to be received.  This violates
#     the SSL/TLS standard but is needed for some brain-dead browsers. Use
#     this when you receive I/O errors because of the standard approach where
#     mod_ssl sends the close notify alert.
#   o ssl-accurate-shutdown:
#     This forces an accurate shutdown when the connection is closed, i.e. a
#     SSL close notify alert is sent and mod_ssl waits for the close notify
#     alert of the client. This is 100% SSL/TLS standard compliant, but in
#     practice often causes hanging connections with brain-dead browsers. Use
#     this only for browsers where you know that their SSL implementation
#     works correctly. 
#   Notice: Most problems of broken clients are also related to the HTTP
#   keep-alive facility, so you usually additionally want to disable
#   keep-alive for those clients, too. Use variable "nokeepalive" for this.
#   Similarly, one has to force some clients to use HTTP/1.0 to workaround
#   their broken HTTP/1.1 implementation. Use variables "downgrade-1.0" and
#   "force-response-1.0" for this.
#BrowserMatch "MSIE [2-5]" \
#         nokeepalive ssl-unclean-shutdown \
#         downgrade-1.0 force-response-1.0

#   Per-Server Logging:
#   The home of a custom SSL log file. Use this when you want a
#   compact non-error SSL logfile on a virtual host basis.
#CustomLog logs/ssl_request_log \
#          "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
#
#</VirtualHost>

NameVirtualHost *:443

バーチャルホスト用の「ssl_sv-neptune.com.conf」作成

vi /etc/httpd/conf.d/ssl_sv-neptune.com.conf
<VirtualHost *:443>

# General setup for the virtual host, inherited from global configuration
DocumentRoot "/home/www/html/sv-neptune.com"
ServerName sv-neptune.com:443
ServerAlias www.sv-neptune.com:443

# Use separate log files for the SSL virtual host; note that LogLevel
# is not inherited from httpd.conf.
ErrorLog logs/ssl_sv-neptune.com-error_log
TransferLog logs/ssl_sv-neptune.com-access_log
LogLevel warn

#   SSL Engine Switch:
#   Enable/Disable SSL for this virtual host.
SSLEngine on

#   List the protocol versions which clients are allowed to connect with.
#   The OpenSSL system profile is used by default.  See
#   update-crypto-policies(8) for more details.
#SSLProtocol all -SSLv3
#SSLProxyProtocol all -SSLv3

#   User agents such as web browsers are not configured for the user's
#   own preference of either security or performance, therefore this
#   must be the prerogative of the web server administrator who manages
#   cpu load versus confidentiality, so enforce the server's cipher order.
SSLHonorCipherOrder on

#   SSL Cipher Suite:
#   List the ciphers that the client is permitted to negotiate.
#   See the mod_ssl documentation for a complete list.
#   The OpenSSL system profile is configured by default.  See
#   update-crypto-policies(8) for more details.
SSLCipherSuite PROFILE=SYSTEM
SSLProxyCipherSuite PROFILE=SYSTEM

#   Point SSLCertificateFile at a PEM encoded certificate.  If
#   the certificate is encrypted, then you will be prompted for a
#   pass phrase.  Note that restarting httpd will prompt again.  Keep
#   in mind that if you have both an RSA and a DSA certificate you
#   can configure both in parallel (to also allow the use of DSA
#   ciphers, etc.)
#   Some ECC cipher suites (http://www.ietf.org/rfc/rfc4492.txt)
#   require an ECC certificate which can also be configured in
#   parallel.
SSLCertificateFile /etc/pki/tls/certs/newcert.pem

#   Server Private Key:
#   If the key is not combined with the certificate, use this
#   directive to point at the key file.  Keep in mind that if
#   you've both a RSA and a DSA private key you can configure
#   both in parallel (to also allow the use of DSA ciphers, etc.)
#   ECC keys, when in use, can also be configured in parallel
SSLCertificateKeyFile /etc/pki/tls/certs/newkey.pem

#   Server Certificate Chain:
#   Point SSLCertificateChainFile at a file containing the
#   concatenation of PEM encoded CA certificates which form the
#   certificate chain for the server certificate. Alternatively
#   the referenced file can be the same as SSLCertificateFile
#   when the CA certificates are directly appended to the server
#   certificate for convenience.
#SSLCertificateChainFile /etc/pki/tls/certs/server-chain.crt

#   Certificate Authority (CA):
#   Set the CA certificate verification path where to find CA
#   certificates for client authentication or alternatively one
#   huge file containing all of them (file must be PEM encoded)
#SSLCACertificateFile /etc/pki/tls/certs/ca-bundle.crt

#   Client Authentication (Type):
#   Client certificate verification type and depth.  Types are
#   none, optional, require and optional_no_ca.  Depth is a
#   number which specifies how deeply to verify the certificate
#   issuer chain before deciding the certificate is not valid.
#SSLVerifyClient require
#SSLVerifyDepth  10

#   Access Control:
#   With SSLRequire you can do per-directory access control based
#   on arbitrary complex boolean expressions containing server
#   variable checks and other lookup directives.  The syntax is a
#   mixture between C and Perl.  See the mod_ssl documentation
#   for more details.
#<Location />
#SSLRequire (    %{SSL_CIPHER} !~ m/^(EXP|NULL)/ \
#            and %{SSL_CLIENT_S_DN_O} eq "Snake Oil, Ltd." \
#            and %{SSL_CLIENT_S_DN_OU} in {"Staff", "CA", "Dev"} \
#            and %{TIME_WDAY} >= 1 and %{TIME_WDAY} <= 5 \
#            and %{TIME_HOUR} >= 8 and %{TIME_HOUR} <= 20       ) \
#           or %{REMOTE_ADDR} =~ m/^192\.76\.162\.[0-9]+$/
#</Location>

#   SSL Engine Options:
#   Set various options for the SSL engine.
#   o FakeBasicAuth:
#     Translate the client X.509 into a Basic Authorisation.  This means that
#     the standard Auth/DBMAuth methods can be used for access control.  The
#     user name is the `one line' version of the client's X.509 certificate.
#     Note that no password is obtained from the user. Every entry in the user
#     file needs this password: `xxj31ZMTZzkVA'.
#   o ExportCertData:
#     This exports two additional environment variables: SSL_CLIENT_CERT and
#     SSL_SERVER_CERT. These contain the PEM-encoded certificates of the
#     server (always existing) and the client (only existing when client
#     authentication is used). This can be used to import the certificates
#     into CGI scripts.
#   o StdEnvVars:
#     This exports the standard SSL/TLS related `SSL_*' environment variables.
#     Per default this exportation is switched off for performance reasons,
#     because the extraction step is an expensive operation and is usually
#     useless for serving static content. So one usually enables the
#     exportation for CGI and SSI requests only.
#   o StrictRequire:
#     This denies access when "SSLRequireSSL" or "SSLRequire" applied even
#     under a "Satisfy any" situation, i.e. when it applies access is denied
#     and no other module can change it.
#   o OptRenegotiate:
#     This enables optimized SSL connection renegotiation handling when SSL
#     directives are used in per-directory context. 
#SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
<FilesMatch "\.(cgi|shtml|phtml|php)$">
    SSLOptions +StdEnvVars
</FilesMatch>
<Directory "/var/www/cgi-bin">
    SSLOptions +StdEnvVars
</Directory>

#   SSL Protocol Adjustments:
#   The safe and default but still SSL/TLS standard compliant shutdown
#   approach is that mod_ssl sends the close notify alert but doesn't wait for
#   the close notify alert from client. When you need a different shutdown
#   approach you can use one of the following variables:
#   o ssl-unclean-shutdown:
#     This forces an unclean shutdown when the connection is closed, i.e. no
#     SSL close notify alert is sent or allowed to be received.  This violates
#     the SSL/TLS standard but is needed for some brain-dead browsers. Use
#     this when you receive I/O errors because of the standard approach where
#     mod_ssl sends the close notify alert.
#   o ssl-accurate-shutdown:
#     This forces an accurate shutdown when the connection is closed, i.e. a
#     SSL close notify alert is sent and mod_ssl waits for the close notify
#     alert of the client. This is 100% SSL/TLS standard compliant, but in
#     practice often causes hanging connections with brain-dead browsers. Use
#     this only for browsers where you know that their SSL implementation
#     works correctly. 
#   Notice: Most problems of broken clients are also related to the HTTP
#   keep-alive facility, so you usually additionally want to disable
#   keep-alive for those clients, too. Use variable "nokeepalive" for this.
#   Similarly, one has to force some clients to use HTTP/1.0 to workaround
#   their broken HTTP/1.1 implementation. Use variables "downgrade-1.0" and
#   "force-response-1.0" for this.
BrowserMatch "MSIE [2-5]" \
         nokeepalive ssl-unclean-shutdown \
         downgrade-1.0 force-response-1.0

#   Per-Server Logging:
#   The home of a custom SSL log file. Use this when you want a
#   compact non-error SSL logfile on a virtual host basis.
CustomLog logs/ssl_request_log \
          "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"

</VirtualHost>

以下が変更する部分です。

  • DocumentRoot "/home/www/html/sv-neptune.com"
  • ServerName sv-neptune.com:443
  • ServerAlias www.sv-neptune.com:443
  • ErrorLog logs/ssl_sv-neptune.com-error_log
  • TransferLog logs/ssl_sv-neptune.com-access_log
  • SSLCertificateFile /etc/pki/tls/certs/newcert.pem
  • SSLCertificateKeyFile /etc/pki/tls/certs/newkey.pem

「SSLCertificateFile」と「SSLCertificateKeyFile」は、サーバ証明書秘密鍵ファイルの配置場所とファイル名に合わせて書き換えます。

中間CAで作成した証明書ファイルをWEBサーバにアップロードし、秘密鍵ファイルの名前も修正

/etc/pki/tls/certs/

Apacheの再起動

confファイル修正後のテスト

 httpd -t
[root@sv-neptune certs]# httpd -t
/etc/httpd/conf.d/ssl.conf:204
Syntax OK

Apacheの再起動

systemctl restart httpd
[root@sv-neptune conf.d]# systemctl restart httpd
Enter TLS private key passphrase for sv-neptune.com:443 (RSA) : ***********

そのままだと、秘密鍵のパスワード入力を求められます。
Apacheの再起動の度にパスワード入力をしなくて済むように、秘密鍵ファイルからパスワードを除去します。

秘密鍵ファイルのパスワード除去

openssl rsa -in /etc/pki/tls/certs/newkey.pem -out /etc/pki/tls/certs/newkey.pem
[root@sv-neptune conf.d]# openssl rsa -in /etc/pki/tls/certs/newkey.pem -out /etc/pki/tls/certs/newkey.pem
Enter pass phrase for /etc/pki/tls/certs/newkey.pem:
writing RSA key ★★★秘密鍵のパスワード★★★

もういちど、Apacheの再起動

systemctl restart httpd
[root@sv-neptune conf.d]# systemctl restart httpd

再起動後のステータス確認

 systemctl status httpd
[root@sv-neptune conf.d]# systemctl status httpd
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
  Drop-In: /usr/lib/systemd/system/httpd.service.d
           mqphp-fpm.conf
   Active: active (running) since Mon 2020-09-14 21:19:58 JST; 11s ago
     Docs: man:httpd.service(8)
  Process: 164230 ExecReload=/usr/sbin/httpd $OPTIONS -k graceful (code=exited, status=0/SUCCESS)
 Main PID: 168200 (httpd)
   Status: "Running, listening on: port 443, port 80"
    Tasks: 213 (limit: 11032)
   Memory: 25.7M
   CGroup: /system.slice/httpd.service
           tq168200 /usr/sbin/httpd -DFOREGROUND
           tq168201 /usr/sbin/httpd -DFOREGROUND
           tq168202 /usr/sbin/httpd -DFOREGROUND
           tq168203 /usr/sbin/httpd -DFOREGROUND
           mq168204 /usr/sbin/httpd -DFOREGROUND

 914 21:19:58 sv-neptune systemd[1]: Starting The Apache HTTP Server...
 914 21:19:58 sv-neptune systemd[1]: Started The Apache HTTP Server.
 914 21:19:58 sv-neptune httpd[168200]: Server configured, listening on: port 443, port 80

少し長くなったので、続きはまた次の記事に書きます。

souiunogaii.hatenablog.com