Search code examples
gosslserverclient-certificatesmutual-authentication

Golang - TLS mutual authentication - Dump client certificates


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)?


Solution

  • 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)
        }