client: -server-cert pins the server certificate

Accept the server only if it presents exactly the given certificate (PEM
or DER file), with no CA or hostname check, like the SoftEther client's
CheckServerCert + ServerCert. Lets a self-signed server certificate that
names no host be verified instead of turning verification off with
-insecure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Git Sagar 2026-10-28 15:27:36 -03:00
parent 4c2b4dcec1
commit bb92a9b954
4 changed files with 44 additions and 7 deletions

View file

@ -4,6 +4,8 @@ import (
"bufio"
"bytes"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io"
"net"
@ -32,17 +34,32 @@ type Conn struct {
// DialTLS establishes a TLS connection to a SoftEther server.
// SoftEther servers listen on port 443 (or 5555, etc.) and accept TLS connections
// that look like normal HTTPS traffic.
func DialTLS(host string, port int, insecureSkipVerify bool) (*Conn, error) {
//
// serverCert (DER) pins the server: the connection is accepted only if the server
// presents exactly this certificate, with no CA or hostname check — what the
// SoftEther client does with CheckServerCert + ServerCert, and the only way to
// verify a self-signed server certificate that names no host.
func DialTLS(host string, port int, insecureSkipVerify bool, serverCert []byte) (*Conn, error) {
addr := net.JoinHostPort(host, strconv.Itoa(port))
raw, err := net.Dial("tcp", addr)
if err != nil {
return nil, fmt.Errorf("tcp dial: %w", err)
}
tlsConn := tls.Client(raw, &tls.Config{
cfg := &tls.Config{
ServerName: host,
InsecureSkipVerify: insecureSkipVerify,
})
}
if serverCert != nil {
cfg.InsecureSkipVerify = true // replaced by the pin check below
cfg.VerifyPeerCertificate = func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
if len(rawCerts) == 0 || !bytes.Equal(rawCerts[0], serverCert) {
return errors.New("server certificate does not match the pinned certificate")
}
return nil
}
}
tlsConn := tls.Client(raw, cfg)
if err := tlsConn.Handshake(); err != nil {
raw.Close()