登录
首页 >  Golang >  Go问答

在 Go 中创建一个带有客户端身份验证的 TLS 测试服务器的方法

来源:stackoverflow

时间:2024-03-06 16:12:24 248浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《在 Go 中创建一个带有客户端身份验证的 TLS 测试服务器的方法》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

问题内容

我想为 http 处理程序编写一个单元测试,该处理程序从设备的证书中提取某些信息。我找到了这个要点,https://gist.github.com/ncw/9253562,它使用 openssl 生成证书,并简单地读取其 client.goserver.go 中的结果文件。不过,为了让事情更加透明,我想使用 go 的标准库生成证书。

这是我迄今为止在单元测试中的尝试(可在 https://github.com/kurtpeek/client-auth-test 获取):

package main

import (
    "crypto"
    "crypto/rand"
    "crypto/rsa"
    "crypto/sha1"
    "crypto/tls"
    "crypto/x509"
    "crypto/x509/pkix"
    "encoding/asn1"
    "encoding/pem"
    "io"
    "math/big"
    "net"
    "net/http"
    "net/http/httptest"
    "testing"
    "time"

    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/require"
)

func testdevicefromtls(t *testing.t) {
    devicekeypem, csrpem := generatekeyandcsr(t)

    cakey, cakeypem := generatekey(t)
    cacert, cacertpem := generaterootcert(t, cakey)

    devicecertpem := signcsr(t, csrpem, cakey, cacert)

    servercert, err := tls.x509keypair(cacertpem, cakeypem)
    require.noerror(t, err)

    clientpool := x509.newcertpool()
    clientpool.addcert(cacert)

    ts := httptest.newunstartedserver(http.handlerfunc(func(w http.responsewriter, r *http.request) {
        assert.len(t, r.tls.peercertificates, 1)
    }))
    ts.tls = &tls.config{
        certificates: []tls.certificate{servercert},
        clientauth:   tls.requireandverifyclientcert,
        clientcas:    clientpool,
    }
    ts.starttls()
    defer ts.close()

    devicecert, err := tls.x509keypair(devicecertpem, devicekeypem)
    require.noerror(t, err)

    pool := x509.newcertpool()
    pool.addcert(cacert)

    client := ts.client()
    client.transport.(*http.transport).tlsclientconfig = &tls.config{
        certificates: []tls.certificate{devicecert},
        rootcas:      pool,
    }

    req, err := http.newrequest(http.methodput, ts.url, nil)
    resp, err := client.do(req)
    require.noerror(t, err)
    defer resp.body.close()

    assert.exactly(t, http.statusok, resp.statuscode)
}

func generatekeyandcsr(t *testing.t) ([]byte, []byte) {
    rsakey, err := rsa.generatekey(rand.reader, 1024)
    require.noerror(t, err)

    key := pem.encodetomemory(&pem.block{
        type:  "rsa private key",
        bytes: x509.marshalpkcs1privatekey(rsakey),
    })

    template := &x509.certificaterequest{
        subject: pkix.name{
            country:      []string{"us"},
            locality:     []string{"san francisco"},
            organization: []string{"awesomeness, inc."},
            province:     []string{"california"},
        },
        signaturealgorithm: x509.sha256withrsa,
        ipaddresses:        []net.ip{net.parseip("127.0.0.1")},
    }

    req, err := x509.createcertificaterequest(rand.reader, template, rsakey)
    require.noerror(t, err)

    csr := pem.encodetomemory(&pem.block{
        type:  "certificate request",
        bytes: req,
    })

    return key, csr
}

func generaterootcert(t *testing.t, key crypto.signer) (*x509.certificate, []byte) {
    subjectkeyidentifier := calculatesubjectkeyidentifier(t, key.public())

    template := &x509.certificate{
        serialnumber: generateserial(t),
        subject: pkix.name{
            organization: []string{"awesomeness, inc."},
            country:      []string{"us"},
            locality:     []string{"san francisco"},
        },
        notbefore:             time.now(),
        notafter:              time.now().adddate(10, 0, 0),
        subjectkeyid:          subjectkeyidentifier,
        authoritykeyid:        subjectkeyidentifier,
        keyusage:              x509.keyusagedigitalsignature | x509.keyusagecertsign,
        extkeyusage:           []x509.extkeyusage{x509.extkeyusageserverauth, x509.extkeyusageclientauth},
        basicconstraintsvalid: true,
        isca:                  true,
        maxpathlenzero:        true,
    }

    der, err := x509.createcertificate(rand.reader, template, template, key.public(), key)
    require.noerror(t, err)

    rootcert, err := x509.parsecertificate(der)
    require.noerror(t, err)

    rootcertpem := pem.encodetomemory(&pem.block{
        type:  "certificate",
        bytes: der,
    })

    return rootcert, rootcertpem
}

// generateserial generates a serial number using the maximum number of octets (20) allowed by rfc 5280 4.1.2.2
// (adapted from https://github.com/cloudflare/cfssl/blob/828c23c22cbca1f7632b9ba85174aaa26e745340/signer/local/local.go#l407-l418)
func generateserial(t *testing.t) *big.int {
    serialnumber := make([]byte, 20)
    _, err := io.readfull(rand.reader, serialnumber)
    require.noerror(t, err)

    return new(big.int).setbytes(serialnumber)
}

// calculatesubjectkeyidentifier implements a common method to generate a key identifier
// from a public key, namely, by composing it from the 160-bit sha-1 hash of the bit string
// of the public key (cf. https://tools.ietf.org/html/rfc5280#section-4.2.1.2).
// (adapted from https://github.com/jsha/minica/blob/master/main.go).
func calculatesubjectkeyidentifier(t *testing.t, pubkey crypto.publickey) []byte {
    spkiasn1, err := x509.marshalpkixpublickey(pubkey)
    require.noerror(t, err)

    var spki struct {
        algorithm        pkix.algorithmidentifier
        subjectpublickey asn1.bitstring
    }
    _, err = asn1.unmarshal(spkiasn1, &spki)
    require.noerror(t, err)

    skid := sha1.sum(spki.subjectpublickey.bytes)
    return skid[:]
}

// signcsr signs a certificate signing request with the given ca certificate and private key
func signcsr(t *testing.t, csr []byte, cakey crypto.signer, cacert *x509.certificate) []byte {
    block, _ := pem.decode(csr)
    require.notnil(t, block, "failed to decode csr")

    certificaterequest, err := x509.parsecertificaterequest(block.bytes)
    require.noerror(t, err)

    require.noerror(t, certificaterequest.checksignature())

    template := x509.certificate{
        subject:               certificaterequest.subject,
        publickeyalgorithm:    certificaterequest.publickeyalgorithm,
        publickey:             certificaterequest.publickey,
        signaturealgorithm:    certificaterequest.signaturealgorithm,
        signature:             certificaterequest.signature,
        serialnumber:          generateserial(t),
        issuer:                cacert.issuer,
        notbefore:             time.now(),
        notafter:              time.now().adddate(10, 0, 0),
        keyusage:              x509.keyusagedigitalsignature | x509.keyusagekeyencipherment,
        extkeyusage:           []x509.extkeyusage{x509.extkeyusageclientauth},
        subjectkeyid:          calculatesubjectkeyidentifier(t, certificaterequest.publickey),
        basicconstraintsvalid: true,
        ipaddresses:           certificaterequest.ipaddresses,
    }

    derbytes, err := x509.createcertificate(rand.reader, &template, cacert, certificaterequest.publickey, cakey)
    require.noerror(t, err)

    return pem.encodetomemory(&pem.block{type: "certificate", bytes: derbytes})
}

// generatekey generates a 1024-bit rsa private key
func generatekey(t *testing.t) (crypto.signer, []byte) {
    key, err := rsa.generatekey(rand.reader, 1024)
    require.noerror(t, err)

    keypem := pem.encodetomemory(&pem.block{
        type:  "rsa private key",
        bytes: x509.marshalpkcs1privatekey(key),
    })

    return key, keypem
}

但是,当我运行它时,出现以下错误:

> go test ./...
2020/04/06 15:12:30 http: TLS handshake error from 127.0.0.1:58685: remote error: tls: bad certificate
--- FAIL: TestDeviceFromTLS (0.05s)
    main_test.go:64: 
            Error Trace:    main_test.go:64
            Error:          Received unexpected error:
                            Put https://127.0.0.1:58684: x509: cannot validate certificate for 127.0.0.1 because it doesn't contain any IP SANs
            Test:           TestDeviceFromTLS
FAIL
FAIL    github.com/kurtpeek/client-auth-test    0.379s

我不太确定错误消息的含义

无法验证 127.0.0.1 的证书,因为它不包含任何 ip san

因为我在创建证书时传入了 ipaddresses 字段。关于这里出了什么问题有什么想法吗?


解决方案


我不太确定错误消息的含义

无法验证 127.0.0.1 的证书,因为它不包含 任何 ip san

因为我在传递 ipaddresses 字段时 创建证书。关于这里出了什么问题有什么想法吗?

问题在于,您在创建客户端证书时传入了 ipaddresses 字段,但在创建服务器证书时则没有传入,因为您的服务器只是使用 ca 证书作为自己的证书,并且 ca 证书(正确地)不包含 ip 地址,因此错误消息是正确的:

caKey, caKeyPEM := generateKey(t)
caCert, caCertPEM := generateRootCert(t, caKey)

serverCert, err := tls.X509KeyPair(caCertPEM, caKeyPEM)

您应该以与创建客户端证书相同的方式创建由 ca(或a ca)签名的服务器证书,并将其用于测试服务器。

一般来说,以您现在的方式让单个密钥作为 ca 和 tls 服务器执行双重职责是自找麻烦,而且没有充分的理由在这里这样做;虽然 rfc5280 实际上并没有禁止这种做法,但至少看起来不鼓励这种做法,除非特殊情况需要。

但就目前情况而言,您使用 ca 证书的方式在技术上不符合 rfc5280,因为它包含仅指定 tls 客户端和服务器身份验证的扩展密钥使用扩展,但您使用它来签署证书。这可能是宽容的,但在缺少 anyextendedkeyusage 关键用途 x509.createcertificate 的情况下,这里确实应该失败。

该错误与 x509 证书中存在的 san 字段扩展有关。 x509 证书中的 san 字段可以包含以下类型的条目;

  1. dns 名称
  2. ip 地址
  3. uri

详情可拨打here

通常在证书验证过程中,可以在某些系统上执行 san 扩展验证。因此你会看到这样的错误消息

您有两种选择来避免此错误消息,

  1. 在您的证书中添加 san ip 字段
  2. 跳过证书验证步骤 [这是您通过注释掉所做的事情]

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《在 Go 中创建一个带有客户端身份验证的 TLS 测试服务器的方法》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>