Golang – TLS双向认证 – 导出客户端证书

huangapple go评论97阅读模式
英文:

Golang - TLS mutual authentication - Dump client certificates

问题

我有一个带有双向认证的TLS服务器。如果握手错误,我想要转储客户端证书。我在http.Server结构中使用ErrorLog,但是这个记录器无法获取有关客户端证书的信息。我尝试在tls.Config结构中使用VerifyConnection函数,但它在正确的握手之后才开始执行。我该如何转储客户端证书(错误和正确的证书)?

英文:

I have TLS server with mutual authentication. I want to dump client certificates if handshake error. I use ErrorLog in http.Server struct, but this logger doesn't get the information about client certificates. I tried to use the VerifyConnection function in tls.Config struct, but it starts after the correct handshake. How can I dump the client certificates(wrong and corrects)?

答案1

得分: 1

你可以在TLS握手完成后,通过tls.Conn.ConnectionState来获取客户端证书。

以下是代码片段:

	config := tls.Config{
		Certificates:       []tls.Certificate{yourServerCert},
		ClientAuth:         tls.RequestClientCert,
		InsecureSkipVerify: true,
	}

	listener, err := tls.Listen("tcp", "localhost:8080", &config)
	if err != nil {
		fmt.Println("server: listen err %+v \n", err)
		return
	}

	conn, err := listener.Accept()
	if err != nil {
		fmt.Println("server: accept err %+v \n", err)
		return
	}

	tlsConn, ok := conn.(*tls.Conn)
	if !ok {
		fmt.Println("server: invalid tls connection")
		return
	}

	if err := tlsConn.Handshake(); err != nil {
		fmt.Println("server: client handshake err %+v \n", err)
		return
	}

	state := tlsConn.ConnectionState()
	for _, v := range state.PeerCertificates {
		fmt.Printf("server: remote client cert %+v \n", v)
	}

希望对你有帮助!

英文:

You could dump the client certificates through tls Conn.ConnectionState after Conn.HandShake as long as the handshake of TLS is done.

Here are code snippets

	config := tls.Config{
		Certificates:       []tls.Certificate{yourServerCert},
		ClientAuth:         tls.RequestClientCert,
		InsecureSkipVerify: true,
	}

	listener, err := tls.Listen("tcp", "localhost:8080", &config)
	if err != nil {
		fmt.Println("server: listen err %+v \n", err)
		return
	}

	conn, err := listener.Accept()
	if err != nil {
		fmt.Println("server: accept err %+v \n", err)
		return
	}

	tlsConn, ok := conn.(*tls.Conn)
	if !ok {
		fmt.Println("server: invalid tls connection")
		return
	}

	if err := tlsConn.Handshake(); err != nil {
		fmt.Println("server: client handshake err %+v \n", err)
		return
	}

	state := tlsConn.ConnectionState()
	for _, v := range state.PeerCertificates {
		fmt.Printf("server: remote client cert %+v \n", v)
	}

huangapple
  • 本文由 发表于 2022年8月31日 16:41:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/73553140.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定