Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 95 additions & 34 deletions libv2ray_certSha256.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,20 @@ import (
"encoding/json"
"errors"
"net"
"net/netip"
"strconv"
"strings"
"time"
"unicode"

quic "github.com/apernet/quic-go"
)

const (
defaultCertProbeTimeout = 5 * time.Second
maxCertProbeTimeout = time.Minute
)

type certSha256Request struct {
Address string `json:"address"`
Port int `json:"port"`
Expand All @@ -36,41 +44,44 @@ func FetchQuicCertSha256(requestJSON string) string {

func fetchCertSha256(
requestJSON string,
fetcher func(certSha256Request) (string, error),
fetcher func(context.Context, certSha256Request) (string, error),
) string {
var request certSha256Request
if err := json.Unmarshal([]byte(requestJSON), &request); err != nil {
return marshalCertSha256Result(certSha256Result{Error: err.Error()})
}
request, err := normalizeCertRequest(request)
if err != nil {
return marshalCertSha256Result(certSha256Result{Error: err.Error()})
}

sha256Value, err := fetcher(request)
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(request.TimeoutMs)*time.Millisecond)
defer cancel()
sha256Value, err := fetcher(ctx, request)
if err != nil {
return marshalCertSha256Result(certSha256Result{Error: err.Error()})
}

return marshalCertSha256Result(certSha256Result{Sha256: sha256Value})
}

func fetchTLSCertSha256(request certSha256Request) (string, error) {
address, serverName, timeout, err := normalizeCertRequest(request)
func fetchTLSCertSha256(ctx context.Context, request certSha256Request) (string, error) {
var dialer net.Dialer
socket, err := dialer.DialContext(ctx, "tcp", net.JoinHostPort(request.Address, strconv.Itoa(request.Port)))
if err != nil {
return "", err
}

conn, err := tls.DialWithDialer(
&net.Dialer{Timeout: timeout},
"tcp",
address,
&tls.Config{
ServerName: serverName,
InsecureSkipVerify: true,
MinVersion: tls.VersionTLS12,
},
)
if err != nil {
// The probe ends after the handshake and does not exchange application data.
defer socket.Close()
conn := tls.Client(socket, &tls.Config{
ServerName: request.ServerName,
// Report the certificate presented by the peer for manual pinning.
InsecureSkipVerify: true,
MinVersion: tls.VersionTLS12,
})
if err := conn.HandshakeContext(ctx); err != nil {
return "", err
}
defer conn.Close()

state := conn.ConnectionState()
if len(state.PeerCertificates) == 0 {
Expand All @@ -80,27 +91,42 @@ func fetchTLSCertSha256(request certSha256Request) (string, error) {
return rawCertSHA256Hex(state.PeerCertificates[0].Raw), nil
}

func fetchQUICCertSha256(request certSha256Request) (string, error) {
address, serverName, timeout, err := normalizeCertRequest(request)
func fetchQUICCertSha256(ctx context.Context, request certSha256Request) (string, error) {
// Resolve within the same deadline as the handshake. DialAddr resolves without it.
addrs, err := net.DefaultResolver.LookupIPAddr(ctx, request.Address)
if err != nil {
return "", err
}
if len(addrs) == 0 {
return "", errors.New("address has no IP records")
}
addr := addrs[0]
for _, candidate := range addrs {
if candidate.IP.To4() != nil {
addr = candidate
break
}
}

ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
socket, err := net.ListenUDP("udp", nil)
if err != nil {
return "", err
}
defer socket.Close()

conn, err := quic.DialAddr(
conn, err := quic.Dial(
ctx,
address,
socket,
&net.UDPAddr{IP: addr.IP, Port: request.Port, Zone: addr.Zone},
&tls.Config{
ServerName: serverName,
ServerName: request.ServerName,
// Report the certificate presented by the peer for manual pinning.
InsecureSkipVerify: true,
MinVersion: tls.VersionTLS12,
MinVersion: tls.VersionTLS13,
NextProtos: []string{"h3"},
},
&quic.Config{
HandshakeIdleTimeout: timeout,
MaxIdleTimeout: timeout,
HandshakeIdleTimeout: time.Duration(request.TimeoutMs) * time.Millisecond,
},
)
if err != nil {
Expand All @@ -116,19 +142,54 @@ func fetchQUICCertSha256(request certSha256Request) (string, error) {
return rawCertSHA256Hex(state.TLS.PeerCertificates[0].Raw), nil
}

func normalizeCertRequest(req certSha256Request) (string, string, time.Duration, error) {
func normalizeCertRequest(req certSha256Request) (certSha256Request, error) {
req.Address = strings.TrimSpace(req.Address)
if req.Address == "" {
return "", "", 0, errors.New("address is empty")
return req, errors.New("address is empty")
}
req.Address = certProbeHost(req.Address)
if req.Address == "" {
return req, errors.New("address must be a host without a port")
}

port := req.Port
if port <= 0 {
port = 443
if req.Port < 0 || req.Port > 65535 {
return req, errors.New("port must be 0 (default) or between 1 and 65535")
}
if req.Port == 0 {
req.Port = 443
}
if req.TimeoutMs < 0 || req.TimeoutMs > maxCertProbeTimeout.Milliseconds() {
return req, errors.New("timeout is outside 0–60000 ms")
}
if req.TimeoutMs == 0 {
req.TimeoutMs = defaultCertProbeTimeout.Milliseconds()
}

timeout := time.Duration(req.TimeoutMs) * time.Millisecond
req.ServerName = strings.TrimSpace(req.ServerName)
if req.ServerName == "" {
req.ServerName = req.Address
} else if req.ServerName = certProbeHost(req.ServerName); req.ServerName == "" {
return req, errors.New("server name must be a host without a port")
}
return req, nil
}

return net.JoinHostPort(req.Address, strconv.Itoa(port)), req.ServerName, timeout, nil
func certProbeHost(host string) string {
if strings.ContainsAny(host, ":[]") {
if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
host = host[1 : len(host)-1]
}
ip, err := netip.ParseAddr(host)
if err != nil || !ip.Is6() {
return ""
}
}
if len(host) > 254 || strings.ContainsAny(host, "[]/?#@\\") || strings.ContainsFunc(host, func(r rune) bool {
return unicode.IsSpace(r) || unicode.IsControl(r)
}) {
return ""
}
return host
}

func rawCertSHA256Hex(raw []byte) string {
Expand Down