/
client.go
247 lines (220 loc) · 6.35 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
package reality
import (
"bytes"
"context"
"crypto/aes"
"crypto/cipher"
"crypto/ecdh"
"crypto/ed25519"
"crypto/hmac"
"crypto/sha256"
"crypto/sha512"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"fmt"
"io"
mRand "math/rand/v2"
"net"
"net/http"
"reflect"
"strings"
"time"
"unsafe"
"github.com/Asutorufa/yuhaiin/pkg/log"
"github.com/Asutorufa/yuhaiin/pkg/net/netapi"
"github.com/Asutorufa/yuhaiin/pkg/protos/node/point"
"github.com/Asutorufa/yuhaiin/pkg/protos/node/protocol"
"github.com/Asutorufa/yuhaiin/pkg/utils/relay"
utls "github.com/refraction-networking/utls"
"golang.org/x/crypto/chacha20poly1305"
"golang.org/x/crypto/hkdf"
"golang.org/x/net/http2"
)
//go:linkname aesgcmPreferred github.com/refraction-networking/utls.aesgcmPreferred
func aesgcmPreferred(ciphers []uint16) bool
type RealityClient struct {
netapi.EmptyDispatch
proxy netapi.Proxy
utls *utls.Config
publicKey []byte
shortID [8]byte
// TODO: remove debug log
Deubg bool
}
func init() {
point.RegisterProtocol(NewRealityClient)
}
func NewRealityClient(config *protocol.Protocol_Reality) point.WrapProxy {
return func(p netapi.Proxy) (netapi.Proxy, error) {
publicKey, err := base64.RawURLEncoding.DecodeString(config.Reality.PublicKey)
if err != nil {
return nil, fmt.Errorf("decode public_key failed: %w", err)
}
if len(publicKey) != 32 {
return nil, fmt.Errorf("invalid public_key")
}
var shortID [8]byte
decodedLen, err := hex.Decode(shortID[:], []byte(config.Reality.ShortId))
if err != nil {
return nil, fmt.Errorf("decode short_id failed: %w", err)
}
if decodedLen > 8 {
return nil, fmt.Errorf("invalid short_id")
}
return &RealityClient{
proxy: p,
utls: &utls.Config{
ServerName: config.Reality.ServerName,
},
publicKey: publicKey,
shortID: shortID,
Deubg: config.Reality.Debug,
}, nil
}
}
func (e *RealityClient) Conn(ctx context.Context, addr netapi.Address) (net.Conn, error) {
con, err := e.proxy.Conn(ctx, addr)
if err != nil {
return nil, err
}
conn, err := e.ClientHandshake(ctx, con)
if err != nil {
con.Close()
return nil, err
}
return conn, nil
}
func (e *RealityClient) PacketConn(ctx context.Context, addr netapi.Address) (net.PacketConn, error) {
return e.proxy.PacketConn(ctx, addr)
}
func (e *RealityClient) ClientHandshake(ctx context.Context, conn net.Conn) (net.Conn, error) {
verifier := &realityVerifier{
serverName: e.utls.ServerName,
}
uConfig := e.utls.Clone()
uConfig.InsecureSkipVerify = true
uConfig.SessionTicketsDisabled = true
uConfig.VerifyPeerCertificate = verifier.VerifyPeerCertificate
uConn := utls.UClient(conn, uConfig, utls.HelloChrome_Auto)
verifier.UConn = uConn
err := uConn.BuildHandshakeState()
if err != nil {
return nil, err
}
if len(uConfig.NextProtos) > 0 {
for _, extension := range uConn.Extensions {
if alpnExtension, isALPN := extension.(*utls.ALPNExtension); isALPN {
alpnExtension.AlpnProtocols = uConfig.NextProtos
break
}
}
}
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
hello.SessionId[1] = 8
hello.SessionId[2] = 1
binary.BigEndian.PutUint32(hello.SessionId[4:], uint32(time.Now().Unix()))
copy(hello.SessionId[8:], e.shortID[:])
if e.Deubg {
log.Debug("REALITY", "hello.sessionId[:16]", hello.SessionId[:16])
}
peerKey, err := ecdh.X25519().NewPublicKey(e.publicKey)
// peerKey, err := uConn.HandshakeState.State13.EcdheKey.Curve().NewPublicKey(e.publicKey)
if err != nil {
return nil, fmt.Errorf("new ecdhe public key failed: %w", err)
}
authKey, err := uConn.HandshakeState.State13.EcdheKey.ECDH(peerKey)
if err != nil {
return nil, fmt.Errorf("ecdh key failed: %w", err)
}
verifier.authKey = authKey
_, err = hkdf.New(sha256.New, authKey, hello.Random[:20], []byte("REALITY")).Read(authKey)
if err != nil {
return nil, err
}
var aead cipher.AEAD
if aesgcmPreferred(hello.CipherSuites) {
block, _ := aes.NewCipher(authKey)
aead, _ = cipher.NewGCM(block)
} else {
aead, _ = chacha20poly1305.New(authKey)
}
aead.Seal(hello.SessionId[:0], hello.Random[20:], hello.SessionId[:16], hello.Raw)
copy(hello.Raw[39:], hello.SessionId)
if e.Deubg {
log.Debug("REALITY", "hello.sessionId", hello.SessionId)
log.Debug("REALITY", "uConn.AuthKey", authKey)
}
err = uConn.HandshakeContext(ctx)
if err != nil {
return nil, fmt.Errorf("handshake failed: %w", err)
}
if e.Deubg {
log.Debug("REALITY", "Conn.Verified", verifier.verified)
}
if !verifier.verified {
go realityClientFallback(uConn, e.utls.ServerName, utls.HelloChrome_Auto)
return nil, fmt.Errorf("reality verification failed")
}
return uConn, nil
}
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
}
_, _ = relay.Copy(io.Discard, response.Body)
response.Body.Close()
}
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
}