gpt4 book ai didi

go - crypto/tls软件包中的自定义VerifyPeerCertificate

转载 作者:行者123 更新时间:2023-12-01 20:22:59 24 4
gpt4 key购买 nike

我正在尝试编写自定义VerifyPeerCertificate以获取证书,即使CN和FQDN不匹配也是如此。

我是golang的新手,所以我试图修改一些我发现的代码,并使它工作,但没有成功。

所以这是我的代码:

package main

import (
"fmt"
"log"
"crypto/tls"
"crypto/x509"
)

func main() {

customVerify := func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {

roots := x509.NewCertPool()
for _, rawCert := range rawCerts {
c, _ := x509.ParseCertificate(rawCert)

roots.AddCert(c)
}
cert, _ := x509.ParseCertificate(rawCerts[0])
fmt.Println("subject name is : ",cert.Subject.CommonName)
opts := x509.VerifyOptions{
DNSName: cert.Subject.CommonName,
Roots: roots,
}
if _, err := cert.Verify(opts); err != nil {
panic("failed to verify certificate: " + err.Error())
return err
}

return nil
}


log.SetFlags(log.Lshortfile)

conf := &tls.Config{
InsecureSkipVerify: true,
VerifyPeerCertificate: customVerify,
}

conn, err := tls.Dial("tcp", "127.0.0.1:9007", conf)


if err != nil {

log.Println(err)
return
}
defer conn.Close()

n, err := conn.Write([]byte("hello\n"))
if err != nil {
log.Println(n, err)
return
}

buf := make([]byte, 100)
n, err = conn.Read(buf)
if err != nil {
log.Println(n, err)
return
}

println(string(buf[:n]))
}

我正在尝试获取本地服务器的证书。

当我尝试运行代码时,出现此错误:
root@mymachine:~/Tproject# go run test.go
subject name is : dssdemo
test.go:50: remote error: tls: bad certificate

我试图模仿 example_Certificate_Verify

有人可以帮我弄这个吗 ?

先感谢您。

编辑:

相互的HTTPS导致: test.go:50: remote error: tls: bad certificate但是,仍然可以以某种方式返回服务器证书吗?

最佳答案

此自定义验证将忽略所有验证:

func ipSCert(host, port string) ([]*x509.Certificate, string, error) {

var ipcertchain []*x509.Certificate

customVerify := func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {

roots := x509.NewCertPool()
for _, rawCert := range rawCerts {

c, _ := x509.ParseCertificate(rawCert)
certItem, _ := x509.ParseCertificate(rawCert)
ipcertchain = append(ipcertchain, certItem)
roots.AddCert(c)

}
return nil

}

log.SetFlags(log.Lshortfile)

d := &net.Dialer{
Timeout: time.Duration(TimeoutSeconds) * time.Second,
}

cs, err := cipherSuite()
if err != nil {
return []*x509.Certificate{&x509.Certificate{}}, "", err
}

conf := &tls.Config{
InsecureSkipVerify: true,
VerifyPeerCertificate: customVerify,
CipherSuites: cs,
MaxVersion: tlsVersion(),
}

conn, err := tls.DialWithDialer(d, "tcp", host+":"+port, conf)

if err != nil {

return nil, "", err
}

conn.Close()

return ipcertchain, host, nil

}

关于go - crypto/tls软件包中的自定义VerifyPeerCertificate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60026307/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com