客戶端如何驗證HTTPS服務(wù)端證書信息

通過一個例子說明客戶端如何驗證HTTPS服務(wù)端的證書信息。
類型瀏覽器如何驗證WEB服務(wù)器的證書信息。

生成服務(wù)器端證書,以及CA證書

# generate ca certificate
$ openssl genrsa -out ca-key.pem 2048
$ openssl req -new -x509 -days 365 -key ca-key.pem -out ca-cert.pem -subj "/CN=ca"

# generate server certificate
$ openssl genrsa -out server-key.pem 2048
$ openssl req -new -key server-key.pem -out server-csr.pem -subj "/CN=localhost"
$ openssl x509 -req -days 3650 -in server-csr.pem -CA ca-cert.pem -CAkey ca-key.pem -CAcreateserial -out server-cert.pem

生成服務(wù)端證書server-cert.pem,(注意證書的common name是localhost),這個證書是通過CA證書ca-cert.pem簽名的。

服務(wù)器端代碼

$ cat server.go 
package main

import (
    "fmt"
    "log"
    "flag"
    "net/http"
    "crypto/tls"
    "encoding/json"
    "github.com/gorilla/mux"
)

var (
    port       int
    hostname   string 
    keyfile    string
    signcert   string
)

func init() {
    flag.IntVar(&port,          "port",     8080,       "The host port on which the REST server will listen")
    flag.StringVar(&hostname,   "hostname", "0.0.0.0",  "The host name on which the REST server will listen")
    flag.StringVar(&keyfile,    "key",      "",         "Path to file containing PEM-encoded key file for service")
    flag.StringVar(&signcert,   "signcert", "",         "Path to file containing PEM-encoded sign certificate for service")
}

func startHTTPSServer(address string, keyfile string, signcert string, router *mux.Router) {
    s := &http.Server{
            Addr:    address,
            Handler: router,
            TLSConfig: &tls.Config{
                MinVersion: tls.VersionTLS12,
            },
    }
    err := s.ListenAndServeTLS(signcert, keyfile)
    if err != nil {
        log.Fatalln("ListenAndServeTLS err:", err)
    }
}


func SayHello(w http.ResponseWriter, r *http.Request) {
    log.Println("Entry SayHello")
    res := map[string]string {"hello": "world"}

    b, err := json.Marshal(res)
    if err == nil {
        w.WriteHeader(http.StatusOK)
        w.Header().Set("Content-Type", "application/json")
        w.Write(b)
    }

    log.Println("Exit SayHello")
}

func main() {
    flag.Parse()

    router := mux.NewRouter().StrictSlash(true)
    router.HandleFunc("/service/hello", SayHello).Methods("GET")

    var address = fmt.Sprintf("%s:%d", hostname, port)
    fmt.Println("Server listen on", address)
    startHTTPSServer(address, keyfile, signcert, router)
    
    fmt.Println("Exit main")
}

編譯運行

$ go build
$ ./server -port 8080 -signcert ./server-cert.pem -key ./server-key.pem

運行服務(wù)器在端口8080,這個服務(wù)器提供驗證的證書是server-cert.pem,客戶端(瀏覽器將驗證這個證書的有效性)。

客戶端代碼

$ cat client.js 
fs = require('fs');
https = require('https');

options = {
    hostname: 'localhost',
    port    : 8080,
    path    : '/service/hello',
    method  : 'GET',
    ca      : fs.readFileSync('ca-cert.pem')
};

req = https.request(options, (res) => {
    console.log('statusCode:', res.statusCode);
    console.log('headers:', res.headers);

    res.on('data', (d) => {
        process.stdout.write(d);
    });
});

req.on('error', (e) => {
  console.error(e);
});

req.end();

運行

$ node client.js 
{"hello":"world"}

完整的訪問地址格式就是 https://localhost:8080/service/hello
這里客戶端必須提供CA證書ca-cert.pem,用他來驗證服務(wù)端的證書server-cert.pem是有效的。

另外這里客戶端訪問的地址是localhost,這個值和服務(wù)器證書server-cert.pem的common name域是一樣的,否則驗證就會失敗。

例如,我們修改客戶端請求中hostname值真實到機器名(假定機器名為saturn)。

options = {
    hostname: 'saturn',
    port    : 8080,
    path    : '/service/hello',
    method  : 'GET',
    ca      : fs.readFileSync('ca-cert.pem')
};

再運行(https://saturn:8080/service/hello),會得到如下錯誤:

$ node client.js 
{ Error: Hostname/IP doesn't match certificate's altnames: "Host: saturn. is not cert's CN: localhost"
    at Object.checkServerIdentity (tls.js:199:17)
    at TLSSocket.<anonymous> (_tls_wrap.js:1098:29)
    at emitNone (events.js:86:13)
    at TLSSocket.emit (events.js:185:7)
    at TLSSocket._finishInit (_tls_wrap.js:610:8)
    at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:440:38)

這說明client使用URL的主機名和證書的Common Name域進行比較,作為證書是否有效的一個證據(jù)。

另外Common Name可以是一個短名(saturn),也可以長域名(saturn.yourcomp.com.cn),但不管短名還是長名都必須是URL請求中的主機名一樣。即

SAN證書

SAN是另一種解決證書和URL主機名匹配的辦法。
SAN = subjectAltName = Subject Alternative Name

具體用法步驟:

修改openssl.cnf

[ req ]
req_extensions = v3_req

[ v3_req ]
# Extensions to add to a certificate request
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = saturn
DNS.2 = saturn.yourcomp.com.cn

生成證書

# generate ca certificate
openssl genrsa -out ca-key.pem 2048
openssl req -new -x509 -days 365 -key ca-key.pem -out ca-cert.pem -subj "/CN=ca"

# generate server certificate
openssl genrsa -out server-key.pem 2048
openssl req -new -key server-key.pem -out server-csr.pem -subj "/CN=localhost"
openssl x509 -req -days 3650 -in server-csr.pem -CA ca-cert.pem -CAkey ca-key.pem -CAcreateserial -out server-cert.pem -extensions v3_req -extfile openssl.cnf

對比和前面不使用SAN的差別。其實就是在使用CA根證書對服務(wù)器證書簽名的時候,指定extensions屬性。

運行客戶端

options = {
    hostname: 'localhost',
    port    : 8080,
    path    : '/service/hello',
    method  : 'GET',
    ca      : fs.readFileSync('ca-cert.pem')
};

$ node client.js
{ Error: Hostname/IP doesn't match certificate's altnames: "Host: localhost. is not in the cert's altnames: DNS:saturn"

看到了嗎?localhost已經(jīng)驗證不過了,盡管他在common name的值沒有變化,但是由于使用了SAN,證書驗證的時候就使用SAN的值,而忽略common name的值。

使用客戶端saturn

options = {
    hostname: 'saturn',
    port    : 8080,
    path    : '/service/hello',
    method  : 'GET',
    ca      : fs.readFileSync('ca-cert.pem')
};

$ node client.js 
{"hello":"world"}

使用saturn就通過了。當然使用saturn.yourcomp.com.cn也能通過。

總結(jié)

客戶端驗證服務(wù)端證書分兩種情況:

  1. 不使用SAN,那么驗證證書的common name和URL的主機名一致。
    主機名是否是common name中的一個。
  2. 使用SAN,那么驗證證書的SAN值和URL的主機名一致。
    主機名是否就是SAN值中的一個。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容