信息安全實踐Lab1-自建CA證書搭建https服務器

信息安全實踐Lab1-自建CA證書搭建https服務器

搭建https服務器

本機環境: Ubuntu 20.04 OpenSSL 1.1.1f Firefox Browser 79.0(64-bit)

安裝OpenSSL

$sudo apt-get install openssl

自建CA

建立myCA目錄用於存放CA相關信息

cd && mkdir -p myCA/signedcerts && mkdir myCA/private && cd myCA

myCA 用於存放 CA 根證書,證書數據庫,以及後續服務器生成的證書,密鑰以及請求
signedcerts:保存簽名證書的 copy
private: 包含私鑰

配置myCA相關參數,在myCA目錄下進行

echo '01'>serial && touch index.txt

創建caconfig.cnf文件

sudo apt-get install vim
vim ~/myCA/caconfig.cnf

caconfig.cnf文件內容如下:

注意文件中兩個地方的username需要換成你自己的用戶名。


# My sample caconfig.cnf file.
#
# Default configuration to use when one is not provided on the command line.
#
[ ca ]
default_ca      = local_ca
#
#
# Default location of directories and files needed to generate certificates.
#
[ local_ca ]
dir             = /home/username/myCA                    # 這裏要將username替換爲你的用戶名
certificate     = $dir/cacert.pem
database        = $dir/index.txt
new_certs_dir   = $dir/signedcerts
private_key     = $dir/private/cakey.pem
serial          = $dir/serial
#       
#
# Default expiration and encryption policies for certificates.
#
default_crl_days        = 365
default_days            = 1825
default_md              = SHA256
#       
policy          = local_ca_policy
x509_extensions = local_ca_extensions
#       
#
# Default policy to use when generating server certificates.  The following
# fields must be defined in the server certificate.
#
[ local_ca_policy ]
commonName              = supplied
stateOrProvinceName     = supplied
countryName             = supplied
emailAddress            = supplied
organizationName        = supplied
organizationalUnitName  = supplied
#       
#
# x509 extensions to use when generating server certificates.
#
[ local_ca_extensions ]
subjectAltName          = DNS:localhost
basicConstraints        = CA:false
nsCertType              = server
#       
#
# The default root certificate generation policy.
#
[ req ]
default_bits    = 2048
default_keyfile = /home/username/myCA/private/cakey.pem  # 這裏要將username替換爲你的用戶名
default_md      = SHA256
#       
prompt                  = no
distinguished_name      = root_ca_distinguished_name
x509_extensions         = root_ca_extensions
#
#
# Root Certificate Authority distinguished name.  Change these fields to match
# your local environment!
#
[ root_ca_distinguished_name ]
commonName              = MyOwn Root Certificate Authority # CA機構名
stateOrProvinceName     = JS                               # CA所在省份
countryName             = CN                               # CA所在國家(僅限2個字符)
emailAddress            = [email protected]                     # 郵箱
organizationName        = XXX                              # 
organizationalUnitName  = XXX                              # 
#       
[ root_ca_extensions ]
basicConstraints        = CA:true

生成CA根證書和密鑰

export OPENSSL_CONF=~/myCA/caconfig.cnf       #該命令用於給環境變量 OPENSSL_CONF 賦值爲caconfig.cnf。
openssl req -x509 -newkey rsa:2048 -out cacert.pem -outform PEM -days 1825             # 生成 CA 根證書和密鑰

該命令需要用戶設置密碼。不要忘記。
以上步驟生成了 CA 自簽名根證書,和 RSA 公/私密鑰對。證書的格式是 PEM,有效期是1825天。

  • /myCA/cacert.pem: CA 根證書
  • /myCA/private/cakey.pem: CA 私鑰

創建服務器公私鑰

生成服務器配置文件exampleserver.cnf

vim ~/myCA/exampleserver.cnf

exampleserver.cnf文件內容如下


#
# exampleserver.cnf
#
[ req ]
prompt             = no
distinguished_name = server_distinguished_name
[ server_distinguished_name ]
commonName              = localhost          # 服務器域名
stateOrProvinceName     = JS                 # 服務器所在省份
countryName             = CN                 # 服務器所在國家(僅限2個字符)
emailAddress            = [email protected]       # 郵箱
organizationName        = XXX                # 
organizationalUnitName  = XXX                # 

生成服務器證書和密鑰

export OPENSSL_CONF =~/myCA/exampleserver.cnf   # 該命令設置環境變量 OPENSSL_CONF,使得 openssl 更換配置文件。
openssl req -newkey rsa:2048 -keyout tempkey.pem -keyform PEM -out tempreq.pem -outform PEM

同樣的,需要輸入密碼短語。
之後,有2種對臨時祕鑰的操作,選擇其一即可
1.將臨時私鑰轉換爲 unencrypted key,即祕鑰不加密狀態。

openssl rsa -in tempkey.pem -out server_key.pem

需要輸入密碼短語。

2.如果希望將 key 保持爲加密狀態,直接改名

mv tempkey.pem server_key.pem

兩者的區別是,第二種需要在服務器啓動時輸入私鑰的密碼短語,否則會導致服務器啓動失敗,但第二種安全性高於第一種,可以更好的保護祕鑰。

使用CA key對服務器證書籤名

export OPENSSL_CONF=~/myCA/caconfig.cnf
openssl ca -in tempreq.pem -out server_crt.pem

刪除臨時證書和密碼文件

rm -f tempkey.pem && rm -f tempreq.pem

現在,自簽名的服務器證書和密鑰對便產生了:

  • server_crt.pem : 服務器證書文件
  • server_key.pem : 服務器密鑰文件

配置Apache

安裝apache2

sudo apt-get update
sudo apt-get install apache2

建立ssl配置文件,lab-ssl.conf

sudo vim /etc/apache2/sites-available/lab-ssl.conf

lab-ssl.conf文件內容如下:

注意這裏有兩處username需要換成你的用戶名。

<IfModule mod_ssl.c>
	<VirtualHost _default_:443>
		ServerAdmin webmaster@localhost

		DocumentRoot /var/www/html

		# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
		# error, crit, alert, emerg.
		# It is also possible to configure the loglevel for particular
		# modules, e.g.
		#LogLevel info ssl:warn

		ErrorLog ${APACHE_LOG_DIR}/error.log
		CustomLog ${APACHE_LOG_DIR}/access.log combined

		# For most configuration files from conf-available/, which are
		# enabled or disabled at a global level, it is possible to
		# include a line for only one particular virtual host. For example the
		# following line enables the CGI configuration for this host only
		# after it has been globally disabled with "a2disconf".
		#Include conf-available/serve-cgi-bin.conf

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

		#   A self-signed (snakeoil) certificate can be created by installing
		#   the ssl-cert package. See
		#   /usr/share/doc/apache2/README.Debian.gz for more info.
		#   If both key and certificate are stored in the same file, only the
		#   SSLCertificateFile directive is needed.
		#SSLCertificateFile	/etc/ssl/certs/ssl-cert-snakeoil.pem
		#SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key

		# 網站證書和私鑰地址
		SSLCertificateFile    /home/username/myCA/server_crt.pem # 這裏的username需要換成你的用戶名
		SSLCertificateKeyFile /home/username/myCA/server_key.pem # 這裏的username需要換成你的用戶名

		#   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 convinience.
		#SSLCertificateChainFile /etc/apache2/ssl.crt/server-ca.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)
		#   Note: Inside SSLCACertificatePath you need hash symlinks
		#		 to point to the certificate files. Use the provided
		#		 Makefile to update the hash symlinks after changes.
		#SSLCACertificatePath /etc/ssl/certs/
		#SSLCACertificateFile /etc/apache2/ssl.crt/ca-bundle.crt

		#   Certificate Revocation Lists (CRL):
		#   Set the CA revocation path where to find CA CRLs for client
		#   authentication or alternatively one huge file containing all
		#   of them (file must be PEM encoded)
		#   Note: Inside SSLCARevocationPath you need hash symlinks
		#		 to point to the certificate files. Use the provided
		#		 Makefile to update the hash symlinks after changes.
		#SSLCARevocationPath /etc/apache2/ssl.crl/
		#SSLCARevocationFile /etc/apache2/ssl.crl/ca-bundle.crl

		#   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

		#   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 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 /usr/lib/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 send or allowed to 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 send 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-6]" \
		#		nokeepalive ssl-unclean-shutdown \
		#		downgrade-1.0 force-response-1.0

	</VirtualHost>
</IfModule>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

啓動ssl服務

sudo a2ensit /etc/apache2/sites-available/lab-ssl.conf
sudo a2enmod ssl

讓瀏覽器信任我們自建的CA

打開 FireFox 瀏覽器,依次選擇“編輯”----“首選項”----“隱私與安全”----“證書”----“查看證書”----“證書機構”,點擊導入,選擇 myCA 目錄下的根證書“cacert.pem”, 導入。

在瀏覽器地址欄輸入 https://localhost

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章