天天看點

SSL、openSSL、CA前言1 X5092 SSL/openSSL/TLS3 HTTPS4 openSSL實作私有CA

  • 前言
  • X509
    • 1 X509證書格式
  • SSLopenSSLTLS
    • 1 簡單介紹
    • 2 openSSL常用指令
      • 21 基礎指令
      • 22 檔案加密解密
      • 23 計算特征碼
      • 24 生成密碼
      • 25 生成僞随機數
      • 26 生成秘鑰
      • 27 生成檢視X509證書
  • HTTPS
    • 1 HTTP VS HTTPS
    • 2 大緻過程
  • openSSL實作私有CA
    • 1 準備工作
    • 2 生成秘鑰
    • 3 生成自簽署的證書
    • 4 其他配置
    • 5 為應用程式配置SSL

前言

上一篇文章 http://blog.csdn.net/hylexus/article/details/53048305、http://www.jianshu.com/p/c929ac2d9134 中,最終得到的安全通信的結論的前提都是基于CA及CA頒發的證書是可靠的基礎上的,整個通信過程的安全性也都依賴于CA這個根源。本篇文章就來說說CA及與其相關的一些概念。

本文章中的諸多資訊都是來自大牛 馬哥 的linux視訊教程。

1 X509

X509,簡言之,也是個人了解:就是證書的中繼資料,也就是來約定證書格式的标準。

我們常見的證書的格式大都是基于X509的标準的。

1.1 X509證書格式

以下資訊來源于百度百科:

所有的X.509證書包含以下資料: 

  • X.509版本号:指出該證書使用了哪種版本的X.509标準,版本号會影響證書中的一些特定資訊。目前的版本是3。
  • 證書持有人的公鑰:包括證書持有人的公鑰、算法(指明密鑰屬于哪種密碼系統)的辨別符和其他相關的密鑰參數。
  • 證書的序列号:由CA給予每一個證書配置設定的唯一的數字型編号,當證書被取消時,實際上是将此證書序列号放入由CA簽發的CRL(Certificate Revocation List證書廢棄表,或證書黑名單表)中。這也是序列号唯一的原因。
  • 主題資訊:證書持有人唯一的辨別符(或稱DN-distinguished name)這個名字在 Internet上應該是唯一的。DN由許多部分組成,看起來象這樣:

    CN=Bob Allen, OU=Total Network Security Division

    O=Network Associates, Inc.

    C=US

    這些資訊指出該科目的通用名、組織機關、組織和國家或者證書持有人的姓名、服務處所等資訊。

  • 書的有效期:證書起始日期和時間以及終止日期和時間;指明證書在這兩個時間内有效。
  • 認證機構:證書釋出者,是簽發該證書的實體唯一的CA的X.509名字。使用該證書意味着信任簽發證書的實體。(注意:在某些情況下,比如根或頂級CA憑證,釋出者自己簽發證書)
  • 釋出者的數字簽名:這是使用釋出者私鑰生成的簽名,以確定這個證書在發放之後沒有被撰改過。
  • 簽名算法辨別符:用來指定CA簽署證書時所使用的簽名算法。算法辨別符用來指定CA簽發證書時所使用的公開密鑰算法和HASH算法。

2 SSL/openSSL/TLS

2.1 簡單介紹

先來看看這兩張來自百度的OSI七層模型圖和四層模型圖:

SSL、openSSL、CA前言1 X5092 SSL/openSSL/TLS3 HTTPS4 openSSL實作私有CA
SSL、openSSL、CA前言1 X5092 SSL/openSSL/TLS3 HTTPS4 openSSL實作私有CA

我們常見的一些協定,比如 http、smtp、telnet、ftp本身預設是不支援資料傳輸加密的。

SSL(Secure Socket Layer)就是在應用層和TCP/IP層之間加的層,好像和這個快被曆史遺忘了的牛逼的NetScape公司有關系。

有了SSL層,本來不支援加密傳輸的一些協定比如http就可以支援加密了即https,smtps,ftps等。

TLS(Transport Layer Security)安全傳輸層協定。TLS-v1相當于SSL-v3。

本文不加差別的使用SSL和TLS。

openSSL即是SSL的開源實作版本。

openSSL

- libcrypto:通用加密庫

- libssl:SSL/TLS的實作

- openssl:指令行工具

2.2 openSSL常用指令

2.2.1 基礎指令

# 檢視目前機器上安裝的openssl資訊
[[email protected] ~]# rpm -q openssl
openssl-.el6_8.x86_64

# 測試目前機器對常用加密算法的運算性能
[[email protected]_15_242_centos ~]# openssl speed
Doing md2 for s on  size blocks:  md2's in s
………………………………………………

# 測試目前機器對指定算法的運算性能
[[email protected] ~]# openssl speed md5
Doing md5 for s on  size blocks:  md5's in s
Doing md5 for s on  size blocks:  md5's in s
Doing md5 for s on  size blocks:  md5's in s
Doing md5 for s on  size blocks:  md5's in s
Doing md5 for s on  size blocks:  md5's in s
OpenSSL e-fips  Feb 
…………………………………………………………………………………………
           

2.2.2 檔案加密/解密

# 加密檔案
openssl enc -des3 -salt -a -in /etc/passwd -out /root/passwd.enc
    -des3:des加密方式
    -salt:加鹽
    -a:基于base64編碼處理
    -in:輸入檔案
    -out:加密結果輸出至何處
           
# 解密檔案
openssl enc -des3 -d -salt -a -in /root/passwd.enc -out /root/passwd.plaintext
    -des3:des加密方式
    -d:解密
    -salt:加鹽
    -a:基于base64編碼處理
    -in:輸入檔案
    -out:加密結果輸出至何處
           

2.2.3 計算特征碼

[root@h1 ~]# openssl dgst -sha1 /etc/passwd
SHA1(/etc/passwd)= cda7fc123305e443155760afa8789b8e757d819a
[root@h1 ~]# openssl dgst -md5 /etc/passwd
MD5(/etc/passwd)= eaa520eb398cfedf2bdd7d785e5dcd78

# 和以下指令的計算結果一緻
[root@h1 ~]# md5sum /etc/passwd
eaa520eb398cfedf2bdd7d785e5dcd78  /etc/passwd
[root@h1 ~]# sha1sum /etc/passwd
cda7fc123305e443155760afa8789b8e757d819a  /etc/passwd
           

2.2.4 生成密碼

# 和passwd指令類似
[root@h1 ~]# openssl  passwd -1
Password: 
Verifying - Password: 
$1$THXDghVa$jF7Ds7zDQpaIDbUEFZZMF1
           

2.2.5 生成僞随機數

man sslrand 檢視幫助

[root@h1 ~]# openssl rand -base64 22
UESrys2wxAQKBa2ofpcxC06/Q+vg==
[root@h1 ~]# openssl rand -hex 22
eda2a48cbc437578b41d5ec1ddc3e42fdf5a7bc9be
           

2.2.6 生成秘鑰

# 生成1024位的rsa秘鑰儲存至檔案server.pri.1024中
[[email protected] ~]# openssl genrsa 1024 > server.pri.1024
Generating RSA private key, 1024 bit long modulus
.................................................++++++
........++++++
e is 65537 (0x10001)


# 或者直接用以下指令在子shell中執行以便直接将mod設定為600
(umask 077;openssl genrsa -out server.pri )

# 可以用以下指令提取檢視公鑰
openssl rsa -in server.pri -pubout
           

2.2.7 生成/檢視X509證書

# 新生成一個x509格式的證書儲存至檔案server.crt中,有效期365天
[[email protected] ~]# openssl req -new -x509 -key ./server.pri.1024 -out server.crt -days 365
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.
-----
# 國家代碼:CN
Country Name ( letter code) [XX]:CN
# 省份
State or Province Name (full name) []:ShangHai
# 城市
Locality Name (eg, city) [Default City]:ShangHai
# 組織機構名稱
Organization Name (eg, company) [Default Company Ltd]:KKBC
# 部門
Organizational Unit Name (eg, section) []:develop
# 主機名
Common Name (eg, your name or your server's hostname) []:h1.hylexus.tech
# 電子郵件   
Email Address []:[email protected]
[[email protected] ~]# 
           
檢視證書資訊
[[email protected] ~]# openssl x509 -text -in server.crt 
Certificate:
    Data:
        Version:  ()
        Serial Number:  ()
    Signature Algorithm: sha1WithRSAEncryption
        Issuer: C=CN, ST=ShangHai, L=ShangHai, O=KKBC, OU=develop, CN=h1.hylexus.tech/[email protected]
        Validity
            Not Before: Nov   ::  GMT
            Not After : Nov   ::  GMT
        Subject: C=CN, ST=ShangHai, L=ShangHai, O=KKBC, OU=develop, CN=h1.hylexus.tech/[email protected]
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: ( bit)
                Modulus:
                    :c2:e:f4:e9:::a:a::c::f::cb:
                    b2:df:d3:f8::e:d:c1:ff::b7:ed:c3:a7:f:
                    b:ef:b6::da:df:d:a:b:b0::cb:e:a3::
                    d3:da:::a5:::ac:ec:cd:e8:c7:cc:aa:b9:
                    :d1:fe:f::e3:f7::fb:cd::a:ae:::
                    c0:a0::b9:e4:bd:e2::::b3:ef:e4:eb::
                    fc:a:ce:f:a8:d7:e:bd:ec:::b1:bd::ee:
                    dc:::b::a4:b9:fe:f:be:f3:de:c4::bc:
                    d1::d9:b:e5:a6::c:
                Exponent:  ()
        X509v3 extensions:
            X509v3 Subject Key Identifier: 
                ::FC:F4:B::B1:CA:C3::B::E:B:BE::::CA:D
            X509v3 Authority Key Identifier: 
                keyid:::FC:F4:B::B1:CA:C3::B::E:B:BE::::CA:D

            X509v3 Basic Constraints: 
                CA:TRUE
    Signature Algorithm: sha1WithRSAEncryption
         b::c:a1:be:ec:a::fc:e2::a9:d3::::d:db:
         ::bc:c7:a9:a::a:e:f::f::b:a7:a2:a::
         ce:bc:f5::a7::b:e:d5:ad::a7::a:a2:c9::eb:
         b8:f:::ba:dd:f8:b7:d:::e9:::e0::df:fa:
         fa:ab:e4::a::::ce:ac:b:b0:c:::d:::
         :f9:ee:b1::a2:b:ec:b6::b5:d::a1::b::f:
         :e4:cf:f:ab:d7:::e5:c7::a:b:f6::f:f9:fb:
         da:e
-----BEGIN CERTIFICATE-----
MIIC7DCCAlWgAwIBAgIJAOwWo9W1KBynMA0GCSqGSIb3DQEBBQUAMIGOMQswCQYD
VQQGEwJDTjERMA8GA1UECAwIU2hhbmdIYWkxETAPBgNVBAcMCFNoYW5nSGFpMQ0w
CwYDVQQKDARLS0JDMRAwDgYDVQQLDAdkZXZlbG9wMRgwFgYDVQQDDA9oMS5oeWxl
eHVzLnRlY2gxHjAcBgkqhkiG9w0BCQEWD2h5bGV4dXNAMTYzLmNvbTAeFw0xNjEx
MDYxNDA0NDJaFw0xNzExMDYxNDA0NDJaMIGOMQswCQYDVQQGEwJDTjERMA8GA1UE
CAwIU2hhbmdIYWkxETAPBgNVBAcMCFNoYW5nSGFpMQ0wCwYDVQQKDARLS0JDMRAw
DgYDVQQLDAdkZXZlbG9wMRgwFgYDVQQDDA9oMS5oeWxleHVzLnRlY2gxHjAcBgkq
hkiG9w0BCQEWD2h5bGV4dXNAMTYzLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAw
gYkCgYEAwo706SEGSoojfBVvcMuy39P4IS4Nwf8Wt+Dp49L77Z12t8NSiuwJst+
oxbT2hVnpSF0rOzN6MfMqrl40f4vEeP3cvvNCIquV1PAoGG55L3iJUMDs+/k6zb8
es5PqNc+vew2ObG9Fe7ckgB7caS5/n++EQ7zRUtkb5aZ0DAcCAwEAAaNQME4w
HQYDVR0OBBYEFFc0/PQbUrHKw3A7eR5rvklTB8o9MB8GA1UdIwQYMBaAFFc0/PQb
UrHKw3A7eR5rvklTB8o9MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEA
O5Ysob7simj84mmp04MkAh3bFBm8x6kqU1p+b3YfaJunoppizrz1Eqc5K37VrTan
dkqiyTjruB9gcbrd+LcthgHpN3Tgh9/+qvkiBpYhQjOrCuwDJUCTWZCAfnusYai
K+y2YrWdlKEZW5YPk+TPP6vXWYXlx0MKO/YgL/n72h4=
-----END CERTIFICATE-----
           

3 HTTPS

HTTPS(Hyper Text Transfer Protocol over Secure Socket Layer)即HTTP在SSL/TLS基礎上的安全版本。

3.1 HTTP VS HTTPS

以下對比來自于百度百科:

  • https協定需要到ca申請證書,一般免費證書很少,需要交費。
  • http是超文本傳輸協定,資訊是明文傳輸,https 則是具有安全性的ssl加密傳輸協定。
  • http和https使用的是完全不同的連接配接方式,用的端口也不一樣,前者是80,後者是443。
  • http的連接配接很簡單,是無狀态的;HTTPS協定是由SSL+HTTP協定建構的可進行加密傳輸、身份認證的網絡協定,比http協定安全。

3.2 大緻過程

  • 三次握手當然是必不可少的了

既然是安全的,當然就得加密傳輸資料了。

怎麼加密傳輸呢?

非對稱加密代價太大,HTTPS使用的方式大緻和上篇文章中所說的

[第二種安全通信方式:http://blog.csdn.net/hylexus/article/details/53048305#72-方式二](“http://blog.csdn.net/hylexus/article/details/53048305#72-方式二” “”) 類似。

用戶端和服務端需要協商通信的對稱加密的加密算法等資訊。一般并不是基于IKE實作的。

4 openSSL實作私有CA

4.1 準備工作

先檢視或按需修改/etc/pki/tls/openssl.cnf檔案内容,其中有以下一些配置項:

####################################################################
[ CA_default ]

dir             = /etc/pki/CA           # Where everything is kept
certs           = $dir/certs            # Where the issued certs are kept
crl_dir         = $dir/crl              # Where the issued crl are kept
database        = $dir/index.txt        # database index file.
#unique_subject = no                    # Set to 'no' to allow creation of
                                        # several ctificates with same subject.
new_certs_dir   = $dir/newcerts         # default place for new certs.

certificate     = $dir/cacert.pem       # The CA certificate
serial          = $dir/serial           # The current serial number
crlnumber       = $dir/crlnumber        # the current crl number
                                        # must be commented out to leave a V1 CRL
crl             = $dir/crl.pem          # The current CRL
private_key     = $dir/private/cakey.pem# The private key
RANDFILE        = $dir/private/.rand    # private random number file
           

為友善,此處直接cd至/etc/pki/CA目錄進行後續操作

4.2 生成秘鑰

[root@h1 CA]# pwd
/etc/pki/CA
# 注意此處的輸出位置應該和/etc/pki/tls/openssl.cnf中的配置相對應
[root@h1 CA]# (umask 77;openssl genrsa -out private/cakey.pem )
Generating RSA private key,  bit long modulus
................................+++
...........................................................................................................+++
e is  (x10001)
[root@h1 CA]# 
           

4.3 生成自簽署的證書

注意此處的證書是CA自己的證書。

[[email protected] CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 365
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 ( letter code) [CN]:
State or Province Name (full name) [ShangHai]:
Locality Name (eg, city) [ShangHai]:
Organization Name (eg, company) [Default Company Ltd]:KKBC
Organizational Unit Name (eg, section) [dev]:
Common Name (eg, your name or your server's hostname) []:h1.hylexus.tech
Email Address []:[email protected]
[[email protected] CA]# 
           

4.4 其他配置

# 此時的目錄大概是這個樣子,具體應該和/etc/pki/tls/openssl.cnf中的配置相對應
[root@h1 CA]# tree
.
├── cacert.pem
├── certs
├── crl
├── newcerts
└── private
    └── cakey.pem


# 建立 database index file.
[root@h1 CA]# touch index.txt
# The current serial number
[root@h1 CA]# echo 01 > serial


# 最終的目錄結構大概是這個樣子,具體應該和/etc/pki/tls/openssl.cnf中的配置相對應
[root@h1 CA]# tree
.
├── cacert.pem
├── certs
├── crl
├── index.txt
├── newcerts
├── private
│   └── cakey.pem
└── serial
           

4.5 為應用程式配置SSL

此處本人在/etc/nginx/ssl目錄下操作,隻是示例而已:

生成私鑰(應用程式自己的私鑰,不要和上面的CA的私鑰混了)
[root@h1 ssl]# cd /etc/nginx/
[root@h1 nginx]# mkdir ssl ; cd ssl
[root@h1 ssl]# pwd
/etc/nginx/ssl

# 生成私鑰
[root@h1 ssl]# (umask 077;openssl genrsa -out nginx.key)
Generating RSA private key,  bit long modulus
.......................++++++
................++++++
e is  ()
           
生成證書頒發請求
# csr====Certificate Signature Request
[[email protected] ssl]# openssl req -new -key nginx.key -out nginx.csr
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 ( letter code) [CN]:
State or Province Name (full name) [ShangHai]:
Locality Name (eg, city) [ShangHai]:
Organization Name (eg, company) [Default Company Ltd]:KKBC
Organizational Unit Name (eg, section) [dev]:
Common Name (eg, your name or your server's hostname) []:h2.hylexus.tech
Email Address []:[email protected]

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
           
将證書頒發請求發送給CA,讓CA簽署(CA簽名認證)

此處CA和應用都在同一台主機上,直接操作即可

[root@h1 ssl]# openssl ca -in nginx.csr -out nginx.crt -days 3650
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number:  ()
        Validity
            Not Before: Nov   ::  GMT
            Not After : Nov   ::  GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = ShangHai
            organizationName          = KKBC
            organizationalUnitName    = dev
            commonName                = h2.hylexus.tech
            emailAddress              = [email protected]
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                :E2::E3:::B:E4::0B::D:E2::F4:FC:CB:C3::
            X509v3 Authority Key Identifier: 
                keyid:D8:E5:FB:::D:A6:ED:FB:D1:D6::B5::FF:D:E8::E0:

Certificate is to be certified until Nov   ::  GMT ( days)
Sign the certificate? [y/n]:y


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

繼續閱讀