1. 程式人生 > >Nginx搭建HTTPS服務的自簽證書

Nginx搭建HTTPS服務的自簽證書

SSL證書

證書型別簡介

要設定安全伺服器,使用公共鑰建立一對公私鑰對。大多數情況下,傳送證書請求(包括自己的公鑰),你的公司證明材料以及費用到一個證書頒發機構(CA)。CA驗證證書請求及您的身份,然後將證書返回給您的安全伺服器。

但是內網實現一個伺服器端和客戶端傳輸內容的加密,可以自己給自己頒發證書,只需要忽略掉瀏覽器不信任的警報即可!

由CA簽署的證書為您的伺服器提供兩個重要的功能:

  • 瀏覽器會自動識別證書並且在不提示使用者的情況下允許建立一個安全連線。
  • 當一個CA生成一個簽署過的證書,它為提供網頁給瀏覽器的組織提供身份擔保。
  • 多數支援ssl的web伺服器都有一個CA列表,它們的證書會被自動接受。當一個瀏覽器遇到一個其授權CA並不在列表中的證書,瀏覽器將詢問使用者是否接受或拒絕連線。

製作CA證書

ca.key CA私鑰:

# openssl genrsa -des3 -out ca.key 2048 
Generating RSA private key, 2048 bit long modulus
......+++
.........+++
e is 65537 (0x10001)
Enter pass phrase for ca.key:
Verifying - Enter pass phrase for ca.key:

ca.crt CA根證書(公鑰)

# openssl req -new -x509 -days 365 -key ca.key -out ca.crt
Enter pass phrase for ca.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:ShenZhang
Locality Name (eg, city) [Default City]:ShenZhang
Organization Name (eg, company) [Default Company Ltd]:HF
Organizational Unit Name (eg, section) []:Hf
Common Name (eg, your name or your server's hostname) []:www.jackyops.com
Email Address []:
[email protected]

製作網站的證書並用CA簽名認證

網站域名為www.jackyops.com,生成www.jackyops.com.key證書私鑰:

# openssl genrsa -des3 -out www.jackyops.com.pem 1024  
Generating RSA private key, 1024 bit long modulus
..................................................++++++
....................................................................................++++++
e is 65537 (0x10001)
Enter pass phrase for www.jackyops.com.pem:
Verifying - Enter pass phrase for www.jackyops.com.pem:
[
[email protected]
test]# ls ca.crt ca.key www.jackyops.com.pem

製作解密後的www.jackyops.com.pem證書私鑰:

# openssl rsa -in www.jackyops.com.pem -out www.jackyops.com.key  
Enter pass phrase for www.jackyops.com.pem:
writing RSA key
# ls
ca.crt  ca.key  www.jackyops.com.key  www.jackyops.com.pem

生成簽名請求:

#  openssl req -new -key www.jackyops.com.pem -out www.jackyops.com.csr
Enter pass phrase for www.jackyops.com.pem:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:ShenZhang
Locality Name (eg, city) [Default City]:ShenZhang
Organization Name (eg, company) [Default Company Ltd]:HF
Organizational Unit Name (eg, section) []:Hf
Common Name (eg, your name or your server's hostname) []:www.jackyops.com
Email Address []:[email protected]

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

可以在Common Name中填入網站域名,即可生產該網站的證書。

用CA進行簽名:

openssl ca -policy policy_anything -days 365 -cert ca.crt -keyfile ca.key -in www.jackyops.com.csr -out www.jackyops.com.crt  
Using configuration from /etc/pki/tls/openssl.cnf
Enter pass phrase for ca.key:
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Nov 13 09:33:37 2018 GMT
            Not After : Nov 13 09:33:37 2019 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = ShenZhang
            localityName              = ShenZhang
            organizationName          = HF
            organizationalUnitName    = Hf
            commonName                = www.jackyops.com
            emailAddress              = [email protected]
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                7E:4F:72:DA:1D:38:65:F3:1C:08:D8:FB:34:BE:6E:21:23:E8:F5:19
            X509v3 Authority Key Identifier: 
                keyid:79:FB:F1:D1:19:2F:C0:3D:49:7B:30:18:63:26:A8:E5:5F:8C:6F:29

Certificate is to be certified until Nov 13 09:33:37 2019 GMT (365 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

可能執行簽名時,會出現如下問題

Using configuration from /etc/pki/tls/openssl.cnf
Enter pass phrase for ca.key:
/etc/pki/CA/index.txt: No such file or directory
unable to open '/etc/pki/CA/index.txt'
47905929770128:error:02001002:system library:fopen:No such file or directory:bss_file.c:402:fopen('/etc/pki/CA/index.txt','r')
47905929770128:error:20074002:BIO routines:FILE_CTRL:system lib:bss_file.c:404:

解決方法:

touch /etc/pki/CA/index.txt

echo "01" > /etc/pki/CA/serial

 

基於Nginx搭建HTTPS虛擬主機

虛擬主機配置檔案

upstream sslfpm {  
    server 192.168.1.20:8080   weight=10   max_fails=3 fail_timeout=20s;  
}  
  
server {   
    listen       192.168.1.*:443;   
    server_name  192.168.1.*;   
      
    #為一個server開啟ssl支援  
    ssl                  on;  
    #為虛擬主機指定pem格式的證書檔案  
    ssl_certificate      /home/wangzhengyi/ssl/wangzhengyi.crt;   
    #為虛擬主機指定私鑰檔案  
    ssl_certificate_key  /home/wangzhengyi/ssl/wangzhengyi_nopass.key;   
    #客戶端能夠重複使用儲存在快取中的會話引數時間  
    ssl_session_timeout  5m;  
    #指定使用的ssl協議   
    ssl_protocols  SSLv3 TLSv1;   
    #指定許可的密碼描述  
    ssl_ciphers  ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;   
    #SSLv3和TLSv1協議的伺服器密碼需求優先順序高於客戶端密碼  
    ssl_prefer_server_ciphers   on;   
  
    location / {   
        root   /home/wangzhengyi/ssl/;  
        autoindex on;  
            autoindex_exact_size    off;  
            autoindex_localtime on;  
    }   
        # redirect server error pages to the static page /50x.html  
        #  
        error_page   500 502 503 504  /50x.html;  
        error_page   404 /404.html;  
  
    location = /50x.html {  
            root   /usr/share/nginx/www;  
        }  
    location = /404.html {  
            root   /usr/share/nginx/www;  
        }  
      
        # proxy the PHP scripts to fpm  
        location ~ \.php$ {  
        access_log  /var/log/nginx/ssl/ssl.access.log  main;  
        error_log /var/log/nginx/ssl/ssl.error.log;  
        root /home/wangzhengyi/ssl/;   
        fastcgi_param   HTTPS   on;  
            include /etc/nginx/fastcgi_params;    
            fastcgi_pass    sslfpm;  
        }  
}  

HTTPS伺服器優化
方法
SSL操作需要消耗CPU資源,所以在多處理器的系統,需要啟動多個工作程序,而且數量需要不少於可用CPU的個數。最消耗CPU資源的SSL操作是SSL握手,有兩種方法可以將每個客戶端的握手運算元量降到最低:
保持客戶端長連線,在一個SSL連線傳送多個請求
在併發的連線或者後續的連線中重用SSL會話引數,這樣可以避免SSL握手操作。
會話快取用於儲存SSL會話,這些快取在工作程序間共享,可以使用ssl_session_cache指令進行配置。1M快取可以存放約4000個會話。預設的快取超時時間是5m,可以使用ssl_session_timeout加大它。

ssl_session_cache指令
語法:ssl_session_cache off|none|builtin:size|shared:name:size  
使用環境:main,server  
快取型別:  
off -- 硬關閉,nginx明確告訴客戶端這個會話不可重用  
none -- 軟關閉,nginx告訴客戶端會話能夠被重用,但是nginx實際上不會重用它們  
bultin -- openssl內建快取,僅可用於一個工作程序.可能導致記憶體碎片  
shared -- 所有工作程序的共享快取。(1)快取大小用位元組數指定(2)每個快取必須擁有自己的名稱(3)同名的快取可用於多個虛擬主機  

 

#優化ssl服務
ssl_session_cache   shared:wzy:10m;   
#客戶端能夠重複使用儲存在快取中的會話引數時間  
ssl_session_timeout  10m; 

 通訊shell指令碼生成證書:

#!/bin/sh

# create self-signed server certificate:

read -p "Enter your domain [www.example.com]: " DOMAIN

echo "Create server key..."

openssl genrsa -des3 -out $DOMAIN.key 1024

echo "Create server certificate signing request..."

SUBJECT="/C=US/ST=Mars/L=iTranswarp/O=iTranswarp/OU=iTranswarp/CN=$DOMAIN"

openssl req -new -subj $SUBJECT -key $DOMAIN.key -out $DOMAIN.csr

echo "Remove password..."

mv $DOMAIN.key $DOMAIN.origin.key
openssl rsa -in $DOMAIN.origin.key -out $DOMAIN.key

echo "Sign SSL certificate..."

openssl x509 -req -days 3650 -in $DOMAIN.csr -signkey $DOMAIN.key -out $DOMAIN.crt

echo "TODO:"
echo "Copy $DOMAIN.crt to /etc/nginx/ssl/$DOMAIN.crt"
echo "Copy $DOMAIN.key to /etc/nginx/ssl/$DOMAIN.key"
echo "Add configuration in nginx:"
echo "server {"
echo "    ..."
echo "    listen 443 ssl;"
echo "    ssl_certificate     /etc/nginx/ssl/$DOMAIN.crt;"
echo "    ssl_certificate_key /etc/nginx/ssl/$DOMAIN.key;"
echo "}"

在當前目錄下會創建出4個檔案:

  • www.test.com.crt:自簽名的證書
  • www.test.com.csr:證書的請求
  • www.test.com.key:不帶口令的Key
  • www.test.com.origin.key:帶口令的Key

Web伺服器需要把www.test.com.crt發給瀏覽器驗證,然後用www.test.com.key解密瀏覽器傳送的資料,剩下兩個檔案不需要上傳到Web伺服器上。