2020-04-03 16:04:24 +08:00
|
|
|
package vmess
|
|
|
|
|
|
|
|
import (
|
2022-01-15 19:33:21 +08:00
|
|
|
"context"
|
2020-04-03 16:04:24 +08:00
|
|
|
"crypto/tls"
|
2023-03-08 17:18:46 +08:00
|
|
|
"errors"
|
2020-04-03 16:04:24 +08:00
|
|
|
"net"
|
2022-01-15 19:33:21 +08:00
|
|
|
|
2023-11-03 21:01:45 +08:00
|
|
|
"github.com/metacubex/mihomo/component/ca"
|
|
|
|
tlsC "github.com/metacubex/mihomo/component/tls"
|
2020-04-03 16:04:24 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type TLSConfig struct {
|
2023-02-01 22:16:06 +08:00
|
|
|
Host string
|
|
|
|
SkipCertVerify bool
|
|
|
|
FingerPrint string
|
|
|
|
ClientFingerprint string
|
|
|
|
NextProtos []string
|
2023-03-08 17:18:46 +08:00
|
|
|
Reality *tlsC.RealityConfig
|
2020-04-03 16:04:24 +08:00
|
|
|
}
|
|
|
|
|
2023-05-18 13:15:08 +08:00
|
|
|
func StreamTLSConn(ctx context.Context, 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,
|
2020-09-26 20:33:57 +08:00
|
|
|
NextProtos: cfg.NextProtos,
|
2022-07-11 13:42:28 +08:00
|
|
|
}
|
|
|
|
|
2023-09-22 14:45:34 +08:00
|
|
|
var err error
|
|
|
|
tlsConfig, err = ca.GetSpecifiedFingerprintTLSConfig(tlsConfig, cfg.FingerPrint)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2022-07-11 13:42:28 +08:00
|
|
|
}
|
2020-04-03 16:04:24 +08:00
|
|
|
|
2023-02-01 22:16:06 +08:00
|
|
|
if len(cfg.ClientFingerprint) != 0 {
|
2023-03-08 17:18:46 +08: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-02-01 22:16:06 +08:00
|
|
|
}
|
|
|
|
}
|
2023-03-08 17:18:46 +08:00
|
|
|
if cfg.Reality != nil {
|
|
|
|
return nil, errors.New("REALITY is based on uTLS, please set a client-fingerprint")
|
|
|
|
}
|
|
|
|
|
2020-04-03 16:04:24 +08:00
|
|
|
tlsConn := tls.Client(conn, tlsConfig)
|
2022-01-15 19:33:21 +08:00
|
|
|
|
2023-09-22 14:45:34 +08:00
|
|
|
err = tlsConn.HandshakeContext(ctx)
|
2020-04-03 16:04:24 +08:00
|
|
|
return tlsConn, err
|
|
|
|
}
|
2023-02-05 17:31:58 +08:00
|
|
|
|
2023-03-08 17:18:46 +08:00
|
|
|
func GetUTLSConn(conn net.Conn, ClientFingerprint string, tlsConfig *tls.Config) (net.Conn, bool) {
|
2023-02-05 17:31:58 +08:00
|
|
|
|
2023-02-07 16:08:59 +08:00
|
|
|
if fingerprint, exists := tlsC.GetFingerprint(ClientFingerprint); exists {
|
2023-02-07 17:51:37 +08:00
|
|
|
utlsConn := tlsC.UClient(conn, tlsConfig, fingerprint)
|
2023-02-05 17:31:58 +08:00
|
|
|
|
|
|
|
return utlsConn, true
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, false
|
|
|
|
}
|