mihomo/transport/vmess/tls.go

71 lines
1.7 KiB
Go
Raw Normal View History

2020-04-03 16:04:24 +08:00
package vmess
import (
"context"
2020-04-03 16:04:24 +08:00
"crypto/tls"
"net"
tlsC "github.com/Dreamacro/clash/component/tls"
C "github.com/Dreamacro/clash/constant"
utls "github.com/refraction-networking/utls"
2020-04-03 16:04:24 +08:00
)
type TLSConfig struct {
Host string
SkipCertVerify bool
FingerPrint string
ClientFingerprint string
NextProtos []string
2020-04-03 16:04:24 +08:00
}
func StreamTLSConn(conn net.Conn, cfg *TLSConfig) (net.Conn, error) {
2022-07-11 13:42:28 +08:00
tlsConfig := &tls.Config{
2020-04-03 16:04:24 +08:00
ServerName: cfg.Host,
InsecureSkipVerify: cfg.SkipCertVerify,
NextProtos: cfg.NextProtos,
2022-07-11 13:42:28 +08:00
}
if len(cfg.FingerPrint) == 0 {
tlsConfig = tlsC.GetGlobalTLSConfig(tlsConfig)
2022-07-11 13:42:28 +08:00
} else {
var err error
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, cfg.FingerPrint); err != nil {
return nil, err
}
}
2020-04-03 16:04:24 +08:00
if len(cfg.ClientFingerprint) != 0 {
utlsConn, valid := GetUtlsConnWithClientFingerprint(conn, cfg.ClientFingerprint, tlsConfig)
if valid {
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
defer cancel()
err := utlsConn.(*UConn).HandshakeContext(ctx)
return utlsConn, err
}
}
2020-04-03 16:04:24 +08:00
tlsConn := tls.Client(conn, tlsConfig)
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
defer cancel()
err := tlsConn.HandshakeContext(ctx)
2020-04-03 16:04:24 +08:00
return tlsConn, err
}
func GetUtlsConnWithClientFingerprint(conn net.Conn, ClientFingerprint string, tlsConfig *tls.Config) (net.Conn, bool) {
if fingerprint, exists := GetFingerprint(ClientFingerprint); exists {
utlsConn := UClient(conn, tlsConfig, &utls.ClientHelloID{
Client: fingerprint.Client,
Version: fingerprint.Version,
Seed: nil,
})
return utlsConn, true
}
return nil, false
}