2023-02-25 16:24:08 +08:00
|
|
|
//go:build with_utls
|
|
|
|
|
|
|
|
package tls
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2023-02-28 20:55:14 +08:00
|
|
|
"context"
|
2023-02-25 16:24:08 +08:00
|
|
|
"crypto/aes"
|
|
|
|
"crypto/cipher"
|
2023-12-09 12:11:21 +08:00
|
|
|
"crypto/ecdh"
|
2023-02-25 16:24:08 +08:00
|
|
|
"crypto/ed25519"
|
|
|
|
"crypto/hmac"
|
|
|
|
"crypto/sha256"
|
|
|
|
"crypto/sha512"
|
2023-02-28 20:55:14 +08:00
|
|
|
"crypto/tls"
|
2023-02-25 16:24:08 +08:00
|
|
|
"crypto/x509"
|
|
|
|
"encoding/base64"
|
|
|
|
"encoding/binary"
|
|
|
|
"encoding/hex"
|
|
|
|
"fmt"
|
2023-02-28 20:55:14 +08:00
|
|
|
"io"
|
|
|
|
mRand "math/rand"
|
2023-02-25 16:24:08 +08:00
|
|
|
"net"
|
2023-02-28 20:55:14 +08:00
|
|
|
"net/http"
|
2023-02-25 16:24:08 +08:00
|
|
|
"reflect"
|
2023-02-28 20:55:14 +08:00
|
|
|
"strings"
|
2023-02-25 16:24:08 +08:00
|
|
|
"time"
|
|
|
|
"unsafe"
|
|
|
|
|
|
|
|
"github.com/sagernet/sing-box/option"
|
|
|
|
"github.com/sagernet/sing/common/debug"
|
|
|
|
E "github.com/sagernet/sing/common/exceptions"
|
2023-02-28 20:55:14 +08:00
|
|
|
aTLS "github.com/sagernet/sing/common/tls"
|
2023-02-25 16:24:08 +08:00
|
|
|
utls "github.com/sagernet/utls"
|
|
|
|
|
|
|
|
"golang.org/x/crypto/hkdf"
|
2023-02-28 20:55:14 +08:00
|
|
|
"golang.org/x/net/http2"
|
2023-02-25 16:24:08 +08:00
|
|
|
)
|
|
|
|
|
2023-02-28 20:55:14 +08:00
|
|
|
var _ ConfigCompat = (*RealityClientConfig)(nil)
|
2023-02-25 16:24:08 +08:00
|
|
|
|
|
|
|
type RealityClientConfig struct {
|
|
|
|
uClient *UTLSClientConfig
|
|
|
|
publicKey []byte
|
2023-03-13 13:34:11 +08:00
|
|
|
shortID [8]byte
|
2023-02-25 16:24:08 +08:00
|
|
|
}
|
|
|
|
|
2023-08-29 13:43:42 +08:00
|
|
|
func NewRealityClient(ctx context.Context, serverAddress string, options option.OutboundTLSOptions) (*RealityClientConfig, error) {
|
2023-02-25 16:24:08 +08:00
|
|
|
if options.UTLS == nil || !options.UTLS.Enabled {
|
|
|
|
return nil, E.New("uTLS is required by reality client")
|
|
|
|
}
|
|
|
|
|
2023-08-29 13:43:42 +08:00
|
|
|
uClient, err := NewUTLSClient(ctx, serverAddress, options)
|
2023-02-25 16:24:08 +08:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
publicKey, err := base64.RawURLEncoding.DecodeString(options.Reality.PublicKey)
|
|
|
|
if err != nil {
|
|
|
|
return nil, E.Cause(err, "decode public_key")
|
|
|
|
}
|
|
|
|
if len(publicKey) != 32 {
|
|
|
|
return nil, E.New("invalid public_key")
|
|
|
|
}
|
2023-03-13 13:34:11 +08:00
|
|
|
var shortID [8]byte
|
|
|
|
decodedLen, err := hex.Decode(shortID[:], []byte(options.Reality.ShortID))
|
2023-02-25 16:24:08 +08:00
|
|
|
if err != nil {
|
|
|
|
return nil, E.Cause(err, "decode short_id")
|
|
|
|
}
|
2023-03-13 13:34:11 +08:00
|
|
|
if decodedLen > 8 {
|
2023-02-25 16:24:08 +08:00
|
|
|
return nil, E.New("invalid short_id")
|
|
|
|
}
|
|
|
|
return &RealityClientConfig{uClient, publicKey, shortID}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *RealityClientConfig) ServerName() string {
|
|
|
|
return e.uClient.ServerName()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *RealityClientConfig) SetServerName(serverName string) {
|
|
|
|
e.uClient.SetServerName(serverName)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *RealityClientConfig) NextProtos() []string {
|
|
|
|
return e.uClient.NextProtos()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *RealityClientConfig) SetNextProtos(nextProto []string) {
|
|
|
|
e.uClient.SetNextProtos(nextProto)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *RealityClientConfig) Config() (*STDConfig, error) {
|
|
|
|
return nil, E.New("unsupported usage for reality")
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *RealityClientConfig) Client(conn net.Conn) (Conn, error) {
|
2023-02-28 20:55:14 +08:00
|
|
|
return ClientHandshake(context.Background(), conn, e)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *RealityClientConfig) ClientHandshake(ctx context.Context, conn net.Conn) (aTLS.Conn, error) {
|
2023-02-25 16:24:08 +08:00
|
|
|
verifier := &realityVerifier{
|
|
|
|
serverName: e.uClient.ServerName(),
|
|
|
|
}
|
|
|
|
uConfig := e.uClient.config.Clone()
|
|
|
|
uConfig.InsecureSkipVerify = true
|
|
|
|
uConfig.SessionTicketsDisabled = true
|
|
|
|
uConfig.VerifyPeerCertificate = verifier.VerifyPeerCertificate
|
|
|
|
uConn := utls.UClient(conn, uConfig, e.uClient.id)
|
|
|
|
verifier.UConn = uConn
|
|
|
|
err := uConn.BuildHandshakeState()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-05-09 17:39:50 +08:00
|
|
|
|
|
|
|
if len(uConfig.NextProtos) > 0 {
|
|
|
|
for _, extension := range uConn.Extensions {
|
|
|
|
if alpnExtension, isALPN := extension.(*utls.ALPNExtension); isALPN {
|
|
|
|
alpnExtension.AlpnProtocols = uConfig.NextProtos
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-02-25 16:24:08 +08:00
|
|
|
hello := uConn.HandshakeState.Hello
|
|
|
|
hello.SessionId = make([]byte, 32)
|
|
|
|
copy(hello.Raw[39:], hello.SessionId)
|
|
|
|
|
|
|
|
var nowTime time.Time
|
|
|
|
if uConfig.Time != nil {
|
|
|
|
nowTime = uConfig.Time()
|
|
|
|
} else {
|
|
|
|
nowTime = time.Now()
|
|
|
|
}
|
|
|
|
binary.BigEndian.PutUint64(hello.SessionId, uint64(nowTime.Unix()))
|
|
|
|
|
|
|
|
hello.SessionId[0] = 1
|
2023-04-06 19:05:05 +08:00
|
|
|
hello.SessionId[1] = 8
|
2023-04-18 14:59:44 +08:00
|
|
|
hello.SessionId[2] = 1
|
2023-04-06 19:05:05 +08:00
|
|
|
binary.BigEndian.PutUint32(hello.SessionId[4:], uint32(time.Now().Unix()))
|
2023-03-13 13:34:11 +08:00
|
|
|
copy(hello.SessionId[8:], e.shortID[:])
|
2023-02-25 16:24:08 +08:00
|
|
|
if debug.Enabled {
|
|
|
|
fmt.Printf("REALITY hello.sessionId[:16]: %v\n", hello.SessionId[:16])
|
|
|
|
}
|
2023-12-09 12:11:21 +08:00
|
|
|
publicKey, err := ecdh.X25519().NewPublicKey(e.publicKey)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
ecdheKey := uConn.HandshakeState.State13.EcdheKey
|
|
|
|
if ecdheKey == nil {
|
|
|
|
return nil, E.New("nil ecdhe_key")
|
|
|
|
}
|
|
|
|
authKey, err := ecdheKey.ECDH(publicKey)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-02-25 16:24:08 +08:00
|
|
|
if authKey == nil {
|
|
|
|
return nil, E.New("nil auth_key")
|
|
|
|
}
|
|
|
|
verifier.authKey = authKey
|
|
|
|
_, err = hkdf.New(sha256.New, authKey, hello.Random[:20], []byte("REALITY")).Read(authKey)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
aesBlock, _ := aes.NewCipher(authKey)
|
|
|
|
aesGcmCipher, _ := cipher.NewGCM(aesBlock)
|
|
|
|
aesGcmCipher.Seal(hello.SessionId[:0], hello.Random[20:], hello.SessionId[:16], hello.Raw)
|
|
|
|
copy(hello.Raw[39:], hello.SessionId)
|
|
|
|
if debug.Enabled {
|
|
|
|
fmt.Printf("REALITY hello.sessionId: %v\n", hello.SessionId)
|
|
|
|
fmt.Printf("REALITY uConn.AuthKey: %v\n", authKey)
|
|
|
|
}
|
|
|
|
|
2023-02-28 20:55:14 +08:00
|
|
|
err = uConn.HandshakeContext(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if debug.Enabled {
|
|
|
|
fmt.Printf("REALITY Conn.Verified: %v\n", verifier.verified)
|
|
|
|
}
|
|
|
|
|
|
|
|
if !verifier.verified {
|
|
|
|
go realityClientFallback(uConn, e.uClient.ServerName(), e.uClient.id)
|
|
|
|
return nil, E.New("reality verification failed")
|
|
|
|
}
|
|
|
|
|
2023-02-25 16:24:08 +08:00
|
|
|
return &utlsConnWrapper{uConn}, nil
|
|
|
|
}
|
|
|
|
|
2023-02-28 20:55:14 +08:00
|
|
|
func realityClientFallback(uConn net.Conn, serverName string, fingerprint utls.ClientHelloID) {
|
|
|
|
defer uConn.Close()
|
|
|
|
client := &http.Client{
|
|
|
|
Transport: &http2.Transport{
|
|
|
|
DialTLSContext: func(ctx context.Context, network, addr string, config *tls.Config) (net.Conn, error) {
|
|
|
|
return uConn, nil
|
|
|
|
},
|
|
|
|
},
|
|
|
|
}
|
|
|
|
request, _ := http.NewRequest("GET", "https://"+serverName, nil)
|
|
|
|
request.Header.Set("User-Agent", fingerprint.Client)
|
|
|
|
request.AddCookie(&http.Cookie{Name: "padding", Value: strings.Repeat("0", mRand.Intn(32)+30)})
|
|
|
|
response, err := client.Do(request)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
_, _ = io.Copy(io.Discard, response.Body)
|
|
|
|
response.Body.Close()
|
|
|
|
}
|
|
|
|
|
2023-02-25 16:24:08 +08:00
|
|
|
func (e *RealityClientConfig) SetSessionIDGenerator(generator func(clientHello []byte, sessionID []byte) error) {
|
|
|
|
e.uClient.config.SessionIDGenerator = generator
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *RealityClientConfig) Clone() Config {
|
|
|
|
return &RealityClientConfig{
|
|
|
|
e.uClient.Clone().(*UTLSClientConfig),
|
|
|
|
e.publicKey,
|
|
|
|
e.shortID,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type realityVerifier struct {
|
|
|
|
*utls.UConn
|
|
|
|
serverName string
|
|
|
|
authKey []byte
|
|
|
|
verified bool
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *realityVerifier) VerifyPeerCertificate(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
|
|
|
|
p, _ := reflect.TypeOf(c.Conn).Elem().FieldByName("peerCertificates")
|
|
|
|
certs := *(*([]*x509.Certificate))(unsafe.Pointer(uintptr(unsafe.Pointer(c.Conn)) + p.Offset))
|
|
|
|
if pub, ok := certs[0].PublicKey.(ed25519.PublicKey); ok {
|
|
|
|
h := hmac.New(sha512.New, c.authKey)
|
|
|
|
h.Write(pub)
|
|
|
|
if bytes.Equal(h.Sum(nil), certs[0].Signature) {
|
|
|
|
c.verified = true
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
opts := x509.VerifyOptions{
|
|
|
|
DNSName: c.serverName,
|
|
|
|
Intermediates: x509.NewCertPool(),
|
|
|
|
}
|
|
|
|
for _, cert := range certs[1:] {
|
|
|
|
opts.Intermediates.AddCert(cert)
|
|
|
|
}
|
|
|
|
if _, err := certs[0].Verify(opts); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|