clash/transport/vmess/tls.go

66 lines
1.5 KiB
Go
Raw Normal View History

2020-04-03 08:04:24 +00:00
package vmess
import (
"context"
2020-04-03 08:04:24 +00:00
"crypto/tls"
2023-03-08 09:18:46 +00:00
"errors"
2020-04-03 08:04:24 +00:00
"net"
2023-09-22 06:45:34 +00:00
"github.com/Dreamacro/clash/component/ca"
tlsC "github.com/Dreamacro/clash/component/tls"
2020-04-03 08:04:24 +00:00
)
type TLSConfig struct {
Host string
SkipCertVerify bool
FingerPrint string
ClientFingerprint string
NextProtos []string
2023-03-08 09:18:46 +00:00
Reality *tlsC.RealityConfig
2020-04-03 08:04:24 +00:00
}
func StreamTLSConn(ctx context.Context, conn net.Conn, cfg *TLSConfig) (net.Conn, error) {
2022-07-11 05:42:28 +00:00
tlsConfig := &tls.Config{
2020-04-03 08:04:24 +00:00
ServerName: cfg.Host,
InsecureSkipVerify: cfg.SkipCertVerify,
NextProtos: cfg.NextProtos,
2022-07-11 05:42:28 +00:00
}
2023-09-22 06:45:34 +00:00
var err error
tlsConfig, err = ca.GetSpecifiedFingerprintTLSConfig(tlsConfig, cfg.FingerPrint)
if err != nil {
return nil, err
2022-07-11 05:42:28 +00:00
}
2020-04-03 08:04:24 +00:00
if len(cfg.ClientFingerprint) != 0 {
2023-03-08 09:18:46 +00:00
if cfg.Reality == nil {
utlsConn, valid := GetUTLSConn(conn, cfg.ClientFingerprint, tlsConfig)
if valid {
err := utlsConn.(*tlsC.UConn).HandshakeContext(ctx)
return utlsConn, err
}
} else {
return tlsC.GetRealityConn(ctx, conn, cfg.ClientFingerprint, tlsConfig, cfg.Reality)
}
}
2023-03-08 09:18:46 +00:00
if cfg.Reality != nil {
return nil, errors.New("REALITY is based on uTLS, please set a client-fingerprint")
}
2020-04-03 08:04:24 +00:00
tlsConn := tls.Client(conn, tlsConfig)
2023-09-22 06:45:34 +00:00
err = tlsConn.HandshakeContext(ctx)
2020-04-03 08:04:24 +00:00
return tlsConn, err
}
2023-03-08 09:18:46 +00:00
func GetUTLSConn(conn net.Conn, ClientFingerprint string, tlsConfig *tls.Config) (net.Conn, bool) {
if fingerprint, exists := tlsC.GetFingerprint(ClientFingerprint); exists {
utlsConn := tlsC.UClient(conn, tlsConfig, fingerprint)
return utlsConn, true
}
return nil, false
}