forked from p4gefau1t/trojan-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
393 lines (363 loc) · 11.1 KB
/
server.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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package tls
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"github.com/faireal/trojan-go/common"
"github.com/faireal/trojan-go/config"
"github.com/faireal/trojan-go/log"
"github.com/faireal/trojan-go/redirector"
"github.com/faireal/trojan-go/tunnel"
"github.com/faireal/trojan-go/tunnel/shadowsocks"
"github.com/faireal/trojan-go/tunnel/tls/fingerprint"
"github.com/faireal/trojan-go/tunnel/transport"
"github.com/faireal/trojan-go/tunnel/trojan"
"github.com/faireal/trojan-go/tunnel/websocket"
"io"
"io/ioutil"
"net"
"os"
"strings"
"sync"
"sync/atomic"
"time"
)
// Server is a tls server
type Server struct {
fallbackAddress *tunnel.Address
verifySNI bool
sni string
alpn []string
PreferServerCipher bool
keyPair []tls.Certificate
keyPairLock sync.RWMutex
httpResp []byte
cipherSuite []uint16
sessionTicket bool
curve []tls.CurveID
keyLogger io.WriteCloser
connChan chan tunnel.Conn
wsChan chan tunnel.Conn
redir *redirector.Redirector
ctx context.Context
cancel context.CancelFunc
underlay tunnel.Server
nextProtocol int32 // 1 HTTP 2 WS 3 SS 4 TORJAN
portOverrider map[string]int
}
func (s *Server) Close() error {
s.cancel()
if s.keyLogger != nil {
s.keyLogger.Close()
}
return s.underlay.Close()
}
func isDomainNameMatched(pattern string, domainName string) bool {
if strings.HasPrefix(pattern, "*.") {
suffix := pattern[2:]
domainPrefixLen := len(domainName) - len(suffix) - 1
return strings.HasSuffix(domainName, suffix) && domainPrefixLen > 0 && !strings.Contains(domainName[:domainPrefixLen], ".")
}
return pattern == domainName
}
func (s *Server) acceptLoop() {
for {
conn, err := s.underlay.AcceptConn(&Tunnel{})
if err != nil {
select {
case <-s.ctx.Done():
default:
log.Fatal(common.NewError("transport accept error" + err.Error()))
}
return
}
go func(conn net.Conn) {
tlsConfig := &tls.Config{
CipherSuites: s.cipherSuite,
PreferServerCipherSuites: s.PreferServerCipher,
SessionTicketsDisabled: !s.sessionTicket,
NextProtos: s.alpn,
KeyLogWriter: s.keyLogger,
GetCertificate: func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
s.keyPairLock.RLock()
defer s.keyPairLock.RUnlock()
sni := s.keyPair[0].Leaf.Subject.CommonName
dnsNames := s.keyPair[0].Leaf.DNSNames
if s.sni != "" {
sni = s.sni
}
matched := isDomainNameMatched(sni, hello.ServerName)
for _, name := range dnsNames {
if isDomainNameMatched(name, hello.ServerName) {
matched = true
break
}
}
if s.verifySNI && !matched {
return nil, common.NewError("sni mismatched: " + hello.ServerName + ", expected: " + s.sni)
}
return &s.keyPair[0], nil
},
}
// ------------------------ WAR ZONE ----------------------------
handshakeRewindConn := common.NewRewindConn(conn)
handshakeRewindConn.SetBufferSize(2048)
tlsConn := tls.Server(handshakeRewindConn, tlsConfig)
err = tlsConn.Handshake()
handshakeRewindConn.StopBuffering()
if err != nil {
if strings.Contains(err.Error(), "first record does not look like a TLS handshake") {
// not a valid tls client hello
handshakeRewindConn.Rewind()
log.Error(common.NewError("failed to perform tls handshake with " + tlsConn.RemoteAddr().String() + ", redirecting").Base(err))
switch {
case s.fallbackAddress != nil:
s.redir.Redirect(&redirector.Redirection{
InboundConn: handshakeRewindConn,
RedirectTo: s.fallbackAddress,
})
case s.httpResp != nil:
handshakeRewindConn.Write(s.httpResp)
handshakeRewindConn.Close()
default:
handshakeRewindConn.Close()
}
} else {
// in other cases, simply close it
tlsConn.Close()
log.Error(common.NewError("tls handshake failed").Base(err))
}
return
}
log.Info("tls connection from", conn.RemoteAddr())
state := tlsConn.ConnectionState()
log.Trace("tls handshake", tls.CipherSuiteName(state.CipherSuite), state.DidResume, state.NegotiatedProtocol)
// we use a real http header parser to mimic a real http server
rewindConn := common.NewRewindConn(tlsConn)
rewindConn.SetBufferSize(1024)
rewindConn.Rewind()
rewindConn.StopBuffering()
switch atomic.LoadInt32(&s.nextProtocol) {
case 2:
log.Info("tls next is ws")
s.wsChan <- &transport.Conn{
Conn: rewindConn,
}
return
case 3, 4:
log.Info("tls next is ss or torjan")
s.connChan <- &transport.Conn{
Conn: rewindConn,
}
return
default:
log.Info("tls next is http")
s.redir.Redirect(&redirector.Redirection{
InboundConn: rewindConn,
RedirectTo: s.fallbackAddress,
})
return
}
}(conn)
}
}
func (s *Server) AcceptConn(overlay tunnel.Tunnel) (tunnel.Conn, error) {
if _, ok := overlay.(*websocket.Tunnel); ok {
atomic.StoreInt32(&s.nextProtocol, 2)
log.Debug("next proto websocket")
// websocket overlay
select {
case conn := <-s.wsChan:
return conn, nil
case <-s.ctx.Done():
return nil, common.NewError("transport server closed")
}
}
if _, ok := overlay.(*shadowsocks.Tunnel); ok {
atomic.StoreInt32(&s.nextProtocol, 3)
log.Info("next proto shadowsocks")
select {
case conn := <-s.connChan:
return conn, nil
case <-s.ctx.Done():
return nil, common.NewError("transport server closed")
}
}
if _, ok := overlay.(*trojan.Tunnel); ok {
atomic.StoreInt32(&s.nextProtocol, 4)
log.Info("next proto trojan")
select {
case conn := <-s.connChan:
return conn, nil
case <-s.ctx.Done():
return nil, common.NewError("transport server closed")
}
}
// http overlay
atomic.StoreInt32(&s.nextProtocol, 1)
log.Info("next proto http")
select {
case conn := <-s.connChan:
return conn, nil
case <-s.ctx.Done():
return nil, common.NewError("transport server closed")
}
}
func (s *Server) AcceptPacket(tunnel.Tunnel) (tunnel.PacketConn, error) {
panic("not supported")
}
func (s *Server) checkKeyPairLoop(checkRate time.Duration, keyPath string, certPath string, password string) {
var lastKeyBytes, lastCertBytes []byte
ticker := time.NewTicker(checkRate)
for {
log.Debug("checking cert...")
keyBytes, err := ioutil.ReadFile(keyPath)
if err != nil {
log.Error(common.NewError("tls failed to check key").Base(err))
continue
}
certBytes, err := ioutil.ReadFile(certPath)
if err != nil {
log.Error(common.NewError("tls failed to check cert").Base(err))
continue
}
if !bytes.Equal(keyBytes, lastKeyBytes) || !bytes.Equal(lastCertBytes, certBytes) {
log.Info("new key pair detected")
keyPair, err := loadKeyPair(keyPath, certPath, password)
if err != nil {
log.Error(common.NewError("tls failed to load new key pair").Base(err))
continue
}
s.keyPairLock.Lock()
s.keyPair = []tls.Certificate{*keyPair}
s.keyPairLock.Unlock()
lastKeyBytes = keyBytes
lastCertBytes = certBytes
}
select {
case <-ticker.C:
continue
case <-s.ctx.Done():
log.Debug("exiting")
ticker.Stop()
return
}
}
}
func loadKeyPair(keyPath string, certPath string, password string) (*tls.Certificate, error) {
if password != "" {
keyFile, err := ioutil.ReadFile(keyPath)
if err != nil {
return nil, common.NewError("failed to load key file").Base(err)
}
keyBlock, _ := pem.Decode(keyFile)
if keyBlock == nil {
return nil, common.NewError("failed to decode key file").Base(err)
}
decryptedKey, err := x509.DecryptPEMBlock(keyBlock, []byte(password))
if err == nil {
return nil, common.NewError("failed to decrypt key").Base(err)
}
certFile, err := ioutil.ReadFile(certPath)
certBlock, _ := pem.Decode(certFile)
if certBlock == nil {
return nil, common.NewError("failed to decode cert file").Base(err)
}
keyPair, err := tls.X509KeyPair(certBlock.Bytes, decryptedKey)
if err != nil {
return nil, err
}
keyPair.Leaf, err = x509.ParseCertificate(keyPair.Certificate[0])
if err != nil {
return nil, common.NewError("failed to parse leaf certificate").Base(err)
}
return &keyPair, nil
}
keyPair, err := tls.LoadX509KeyPair(certPath, keyPath)
if err != nil {
return nil, common.NewError("failed to load key pair").Base(err)
}
keyPair.Leaf, err = x509.ParseCertificate(keyPair.Certificate[0])
if err != nil {
return nil, common.NewError("failed to parse leaf certificate").Base(err)
}
return &keyPair, nil
}
// NewServer creates a tls layer server
func NewServer(ctx context.Context, underlay tunnel.Server) (*Server, error) {
cfg := config.FromContext(ctx, Name).(*Config)
var fallbackAddress *tunnel.Address
var httpResp []byte
if cfg.TLS.FallbackPort != 0 {
if cfg.TLS.FallbackHost == "" {
cfg.TLS.FallbackHost = cfg.RemoteHost
log.Warn("empty tls fallback address")
}
fallbackAddress = tunnel.NewAddressFromHostPort("tcp", cfg.TLS.FallbackHost, cfg.TLS.FallbackPort)
fallbackConn, err := net.Dial("tcp", fallbackAddress.String())
if err != nil {
return nil, common.NewError("invalid fallback address").Base(err)
}
fallbackConn.Close()
} else {
log.Warn("empty tls fallback port")
if cfg.TLS.HTTPResponseFileName != "" {
httpRespBody, err := ioutil.ReadFile(cfg.TLS.HTTPResponseFileName)
if err != nil {
return nil, common.NewError("invalid response file").Base(err)
}
httpResp = httpRespBody
} else {
log.Warn("empty tls http response")
}
}
keyPair, err := loadKeyPair(cfg.TLS.KeyPath, cfg.TLS.CertPath, cfg.TLS.KeyPassword)
if err != nil {
return nil, common.NewError("tls failed to load key pair")
}
var keyLogger io.WriteCloser
if cfg.TLS.KeyLogPath != "" {
log.Warn("tls key logging activated. USE OF KEY LOGGING COMPROMISES SECURITY. IT SHOULD ONLY BE USED FOR DEBUGGING.")
file, err := os.OpenFile(cfg.TLS.KeyLogPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
return nil, common.NewError("failed to open key log file").Base(err)
}
keyLogger = file
}
var cipherSuite []uint16
if len(cfg.TLS.Cipher) != 0 {
cipherSuite = fingerprint.ParseCipher(strings.Split(cfg.TLS.Cipher, ":"))
}
ctx, cancel := context.WithCancel(ctx)
server := &Server{
underlay: underlay,
fallbackAddress: fallbackAddress,
httpResp: httpResp,
verifySNI: cfg.TLS.VerifyHostName,
sni: cfg.TLS.SNI,
alpn: cfg.TLS.ALPN,
PreferServerCipher: cfg.TLS.PreferServerCipher,
sessionTicket: cfg.TLS.ReuseSession,
connChan: make(chan tunnel.Conn, 32),
wsChan: make(chan tunnel.Conn, 32),
redir: redirector.NewRedirector(ctx),
keyPair: []tls.Certificate{*keyPair},
keyLogger: keyLogger,
cipherSuite: cipherSuite,
ctx: ctx,
cancel: cancel,
}
go server.acceptLoop()
if cfg.TLS.CertCheckRate > 0 {
go server.checkKeyPairLoop(
time.Second*time.Duration(cfg.TLS.CertCheckRate),
cfg.TLS.KeyPath,
cfg.TLS.CertPath,
cfg.TLS.KeyPassword,
)
}
log.Debug("tls server created")
return server, nil
}