-
Notifications
You must be signed in to change notification settings - Fork 267
/
meekConn.go
1299 lines (1117 loc) · 42.8 KB
/
meekConn.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2015, Psiphon Inc.
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package psiphon
import (
"bytes"
"context"
"crypto/rand"
"crypto/tls"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/Psiphon-Labs/goarista/monotime"
"github.com/Psiphon-Labs/net/http2"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/nacl/box"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/obfuscator"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/upstreamproxy"
)
// MeekConn is based on meek-client.go from Tor and Psiphon:
//
// https://gitweb.torproject.org/pluggable-transports/meek.git/blob/HEAD:/meek-client/meek-client.go
// CC0 1.0 Universal
//
// https://bitbucket.org/psiphon/psiphon-circumvention-system/src/default/go/meek-client/meek-client.go
const (
MEEK_PROTOCOL_VERSION = 3
MEEK_MAX_REQUEST_PAYLOAD_LENGTH = 65536
)
// MeekConfig specifies the behavior of a MeekConn
type MeekConfig struct {
// ClientParameters is the active set of client parameters to use
// for the meek dial.
ClientParameters *parameters.ClientParameters
// DialAddress is the actual network address to dial to establish a
// connection to the meek server. This may be either a fronted or
// direct address. The address must be in the form "host:port",
// where host may be a domain name or IP address.
DialAddress string
// UseHTTPS indicates whether to use HTTPS (true) or HTTP (false).
UseHTTPS bool
// TLSProfile specifies the value for CustomTLSConfig.TLSProfile for all
// underlying TLS connections created by this meek connection.
TLSProfile string
// RandomizedTLSProfileSeed specifies the value for
// CustomTLSConfig.RandomizedTLSProfileSeed for all underlying TLS
// connections created by this meek connection.
RandomizedTLSProfileSeed *prng.Seed
// UseObfuscatedSessionTickets indicates whether to use obfuscated
// session tickets. Assumes UseHTTPS is true.
UseObfuscatedSessionTickets bool
// SNIServerName is the value to place in the TLS SNI server_name
// field when HTTPS is used.
SNIServerName string
// HostHeader is the value to place in the HTTP request Host header.
HostHeader string
// TransformedHostName records whether a hostname transformation is
// in effect. This value is used for stats reporting.
TransformedHostName bool
// ClientTunnelProtocol is the protocol the client is using. It's
// included in the meek cookie for optional use by the server, in
// cases where the server cannot unambiguously determine the
// tunnel protocol.
ClientTunnelProtocol string
// RoundTripperOnly sets the MeekConn to operate in round tripper
// mode, which is used for untunneled tactics requests. In this
// mode, a connection is established to the meek server as usual,
// but instead of relaying tunnel traffic, the RoundTrip function
// may be used to make requests. In this mode, no relay resources
// incuding buffers are allocated.
RoundTripperOnly bool
// The following values are used to create the obfuscated meek cookie.
MeekCookieEncryptionPublicKey string
MeekObfuscatedKey string
MeekObfuscatorPaddingSeed *prng.Seed
}
// MeekConn is a network connection that tunnels TCP over HTTP and supports "fronting". Meek sends
// client->server flow in HTTP request bodies and receives server->client flow in HTTP response bodies.
// Polling is used to achieve full duplex TCP.
//
// Fronting is an obfuscation technique in which the connection
// to a web server, typically a CDN, is indistinguishable from any other HTTPS connection to the generic
// "fronting domain" -- the HTTP Host header is used to route the requests to the actual destination.
// See https://trac.torproject.org/projects/tor/wiki/doc/meek for more details.
//
// MeekConn also operates in unfronted mode, in which plain HTTP connections are made without routing
// through a CDN.
type MeekConn struct {
clientParameters *parameters.ClientParameters
url *url.URL
additionalHeaders http.Header
cookie *http.Cookie
cachedTLSDialer *cachedTLSDialer
transport transporter
mutex sync.Mutex
isClosed bool
runCtx context.Context
stopRunning context.CancelFunc
relayWaitGroup *sync.WaitGroup
// For round tripper mode
roundTripperOnly bool
meekCookieEncryptionPublicKey string
meekObfuscatedKey string
meekObfuscatorPaddingSeed *prng.Seed
clientTunnelProtocol string
// For relay mode
fullReceiveBufferLength int
readPayloadChunkLength int
emptyReceiveBuffer chan *bytes.Buffer
partialReceiveBuffer chan *bytes.Buffer
fullReceiveBuffer chan *bytes.Buffer
emptySendBuffer chan *bytes.Buffer
partialSendBuffer chan *bytes.Buffer
fullSendBuffer chan *bytes.Buffer
}
// transporter is implemented by both http.Transport and upstreamproxy.ProxyAuthTransport.
type transporter interface {
CloseIdleConnections()
RoundTrip(req *http.Request) (resp *http.Response, err error)
}
// DialMeek returns an initialized meek connection. A meek connection is
// an HTTP session which does not depend on an underlying socket connection (although
// persistent HTTP connections are used for performance). This function does not
// wait for the connection to be "established" before returning. A goroutine
// is spawned which will eventually start HTTP polling.
// When frontingAddress is not "", fronting is used. This option assumes caller has
// already checked server entry capabilities.
func DialMeek(
ctx context.Context,
meekConfig *MeekConfig,
dialConfig *DialConfig) (meek *MeekConn, err error) {
runCtx, stopRunning := context.WithCancel(context.Background())
cleanupStopRunning := true
cleanupCachedTLSDialer := true
var cachedTLSDialer *cachedTLSDialer
// Cleanup in error cases
defer func() {
if cleanupStopRunning {
stopRunning()
}
if cleanupCachedTLSDialer && cachedTLSDialer != nil {
cachedTLSDialer.close()
}
}()
// Configure transport: HTTP or HTTPS
var scheme string
var transport transporter
var additionalHeaders http.Header
var proxyUrl func(*http.Request) (*url.URL, error)
if meekConfig.UseHTTPS {
// Custom TLS dialer:
//
// 1. ignores the HTTP request address and uses the fronting domain
// 2. optionally disables SNI -- SNI breaks fronting when used with certain CDNs.
// 3. skips verifying the server cert.
//
// Reasoning for #3:
//
// With a TLS MiM attack in place, and server certs verified, we'll fail to connect because the client
// will refuse to connect. That's not a successful outcome.
//
// With a MiM attack in place, and server certs not verified, we'll fail to connect if the MiM is actively
// targeting Psiphon and classifying the HTTP traffic by Host header or payload signature.
//
// However, in the case of a passive MiM that's just recording traffic or an active MiM that's targeting
// something other than Psiphon, the client will connect. This is a successful outcome.
//
// What is exposed to the MiM? The Host header does not contain a Psiphon server IP address, just an
// unrelated, randomly generated domain name which cannot be used to block direct connections. The
// Psiphon server IP is sent over meek, but it's in the encrypted cookie.
//
// The payload (user traffic) gets its confidentiality and integrity from the underlying SSH protocol.
// So, nothing is leaked to the MiM apart from signatures which could be used to classify the traffic
// as Psiphon to possibly block it; but note that not revealing that the client is Psiphon is outside
// our threat model; we merely seek to evade mass blocking by taking steps that require progressively
// more effort to block.
//
// There is a subtle attack remaining: an adversary that can MiM some CDNs but not others (and so can
// classify Psiphon traffic on some CDNs but not others) may throttle non-MiM CDNs so that our server
// selection always chooses tunnels to the MiM CDN (without any server cert verification, we won't
// exclusively connect to non-MiM CDNs); then the adversary kills the underlying TCP connection after
// some short period. This is partially mitigated by tactics mechanisms.
scheme = "https"
tlsConfig := &CustomTLSConfig{
ClientParameters: meekConfig.ClientParameters,
DialAddr: meekConfig.DialAddress,
Dial: NewTCPDialer(dialConfig),
SNIServerName: meekConfig.SNIServerName,
SkipVerify: true,
TLSProfile: meekConfig.TLSProfile,
RandomizedTLSProfileSeed: meekConfig.RandomizedTLSProfileSeed,
TrustedCACertificatesFilename: dialConfig.TrustedCACertificatesFilename,
}
tlsConfig.EnableClientSessionCache(meekConfig.ClientParameters)
if meekConfig.UseObfuscatedSessionTickets {
tlsConfig.ObfuscatedSessionTicketKey = meekConfig.MeekObfuscatedKey
}
tlsDialer := NewCustomTLSDialer(tlsConfig)
// Pre-dial one TLS connection in order to inspect the negotiated
// application protocol. Then we create an HTTP/2 or HTTP/1.1 transport
// depending on which protocol was negotiated. The TLS dialer
// is assumed to negotiate only "h2" or "http/1.1"; or not negotiate
// an application protocol.
//
// We cannot rely on net/http's HTTP/2 support since it's only
// activated when http.Transport.DialTLS returns a golang crypto/tls.Conn;
// e.g., https://github.com/golang/go/blob/c8aec4095e089ff6ac50d18e97c3f46561f14f48/src/net/http/transport.go#L1040
//
// The pre-dialed connection is stored in a cachedTLSDialer, which will
// return the cached pre-dialed connection to its first Dial caller, and
// use the tlsDialer for all other Dials.
//
// cachedTLSDialer.close() must be called on all exits paths from this
// function and in meek.Close() to ensure the cached conn is closed in
// any case where no Dial call is made.
//
// The pre-dial must be interruptible so that DialMeek doesn't block and
// hang/delay a shutdown or end of establishment. So the pre-dial uses
// the Controller's PendingConns, not the MeekConn PendingConns. For this
// purpose, a special preDialer is configured.
//
// Only one pre-dial attempt is made; there are no retries. This differs
// from relayRoundTrip, which retries and may redial for each retry.
// Retries at the pre-dial phase are less useful since there's no active
// session to preserve, and establishment will simply try another server.
// Note that the underlying TCPDial may still try multiple IP addreses when
// the destination is a domain and it resolves to multiple IP adresses.
// The pre-dial is made within the parent dial context, so that DialMeek
// may be interrupted. Subsequent dials are made within the meek round trip
// request context. Since http.DialTLS doesn't take a context argument
// (yet; as of Go 1.9 this issue is still open: https://github.com/golang/go/issues/21526),
// cachedTLSDialer is used as a conduit to send the request context.
// meekConn.relayRoundTrip sets its request context into cachedTLSDialer,
// and cachedTLSDialer.dial uses that context.
// As DialAddr is set in the CustomTLSConfig, no address is required here.
preConn, err := tlsDialer(ctx, "tcp", "")
if err != nil {
return nil, common.ContextError(err)
}
cachedTLSDialer = newCachedTLSDialer(preConn, tlsDialer)
if IsTLSConnUsingHTTP2(preConn) {
NoticeInfo("negotiated HTTP/2 for %s", meekConfig.DialAddress)
transport = &http2.Transport{
DialTLS: func(network, addr string, _ *tls.Config) (net.Conn, error) {
return cachedTLSDialer.dial(network, addr)
},
}
} else {
transport = &http.Transport{
DialTLS: func(network, addr string) (net.Conn, error) {
return cachedTLSDialer.dial(network, addr)
},
}
}
} else {
scheme = "http"
var dialer Dialer
// For HTTP, and when the meekConfig.DialAddress matches the
// meekConfig.HostHeader, we let http.Transport handle proxying.
// http.Transport will put the the HTTP server address in the HTTP
// request line. In this one case, we can use an HTTP proxy that does
// not offer CONNECT support.
if strings.HasPrefix(dialConfig.UpstreamProxyURL, "http://") &&
(meekConfig.DialAddress == meekConfig.HostHeader ||
meekConfig.DialAddress == meekConfig.HostHeader+":80") {
url, err := url.Parse(dialConfig.UpstreamProxyURL)
if err != nil {
return nil, common.ContextError(err)
}
proxyUrl = http.ProxyURL(url)
// Here, the dialer must use the address that http.Transport
// passes in (which will be proxy address).
copyDialConfig := new(DialConfig)
*copyDialConfig = *dialConfig
copyDialConfig.UpstreamProxyURL = ""
dialer = NewTCPDialer(copyDialConfig)
} else {
baseDialer := NewTCPDialer(dialConfig)
// The dialer ignores any address that http.Transport will pass in
// (derived from the HTTP request URL) and always dials
// meekConfig.DialAddress.
dialer = func(ctx context.Context, network, _ string) (net.Conn, error) {
return baseDialer(ctx, network, meekConfig.DialAddress)
}
}
httpTransport := &http.Transport{
Proxy: proxyUrl,
DialContext: dialer,
}
if proxyUrl != nil {
// Wrap transport with a transport that can perform HTTP proxy auth negotiation
transport, err = upstreamproxy.NewProxyAuthTransport(httpTransport, dialConfig.CustomHeaders)
if err != nil {
return nil, common.ContextError(err)
}
} else {
transport = httpTransport
}
}
url := &url.URL{
Scheme: scheme,
Host: meekConfig.HostHeader,
Path: "/",
}
if meekConfig.UseHTTPS {
host, _, err := net.SplitHostPort(meekConfig.DialAddress)
if err != nil {
return nil, common.ContextError(err)
}
additionalHeaders = map[string][]string{
"X-Psiphon-Fronting-Address": {host},
}
} else {
if proxyUrl == nil {
additionalHeaders = dialConfig.CustomHeaders
}
}
// The main loop of a MeekConn is run in the relay() goroutine.
// A MeekConn implements net.Conn concurrency semantics:
// "Multiple goroutines may invoke methods on a Conn simultaneously."
//
// Read() calls and relay() are synchronized by exchanging control of a single
// receiveBuffer (bytes.Buffer). This single buffer may be:
// - in the emptyReceiveBuffer channel when it is available and empty;
// - in the partialReadBuffer channel when it is available and contains data;
// - in the fullReadBuffer channel when it is available and full of data;
// - "checked out" by relay or Read when they are are writing to or reading from the
// buffer, respectively.
// relay() will obtain the buffer from either the empty or partial channel but block when
// the buffer is full. Read will obtain the buffer from the partial or full channel when
// there is data to read but block when the buffer is empty.
// Write() calls and relay() are synchronized in a similar way, using a single
// sendBuffer.
meek = &MeekConn{
clientParameters: meekConfig.ClientParameters,
url: url,
additionalHeaders: additionalHeaders,
cachedTLSDialer: cachedTLSDialer,
transport: transport,
isClosed: false,
runCtx: runCtx,
stopRunning: stopRunning,
relayWaitGroup: new(sync.WaitGroup),
roundTripperOnly: meekConfig.RoundTripperOnly,
}
// stopRunning and cachedTLSDialer will now be closed in meek.Close()
cleanupStopRunning = false
cleanupCachedTLSDialer = false
// Allocate relay resources, including buffers and running the relay
// go routine, only when running in relay mode.
if !meek.roundTripperOnly {
cookie, err := makeMeekCookie(
meek.clientParameters,
meekConfig.MeekCookieEncryptionPublicKey,
meekConfig.MeekObfuscatedKey,
meekConfig.MeekObfuscatorPaddingSeed,
meekConfig.ClientTunnelProtocol,
"")
if err != nil {
return nil, common.ContextError(err)
}
meek.cookie = cookie
p := meekConfig.ClientParameters.Get()
if p.Bool(parameters.MeekLimitBufferSizes) {
meek.fullReceiveBufferLength = p.Int(parameters.MeekLimitedFullReceiveBufferLength)
meek.readPayloadChunkLength = p.Int(parameters.MeekLimitedReadPayloadChunkLength)
} else {
meek.fullReceiveBufferLength = p.Int(parameters.MeekFullReceiveBufferLength)
meek.readPayloadChunkLength = p.Int(parameters.MeekReadPayloadChunkLength)
}
p = nil
meek.emptyReceiveBuffer = make(chan *bytes.Buffer, 1)
meek.partialReceiveBuffer = make(chan *bytes.Buffer, 1)
meek.fullReceiveBuffer = make(chan *bytes.Buffer, 1)
meek.emptySendBuffer = make(chan *bytes.Buffer, 1)
meek.partialSendBuffer = make(chan *bytes.Buffer, 1)
meek.fullSendBuffer = make(chan *bytes.Buffer, 1)
meek.emptyReceiveBuffer <- new(bytes.Buffer)
meek.emptySendBuffer <- new(bytes.Buffer)
meek.relayWaitGroup.Add(1)
go meek.relay()
} else {
meek.meekCookieEncryptionPublicKey = meekConfig.MeekCookieEncryptionPublicKey
meek.meekObfuscatedKey = meekConfig.MeekObfuscatedKey
meek.meekObfuscatorPaddingSeed = meekConfig.MeekObfuscatorPaddingSeed
meek.clientTunnelProtocol = meekConfig.ClientTunnelProtocol
}
return meek, nil
}
type cachedTLSDialer struct {
usedCachedConn int32
cachedConn net.Conn
requestCtx atomic.Value
dialer Dialer
}
func newCachedTLSDialer(cachedConn net.Conn, dialer Dialer) *cachedTLSDialer {
return &cachedTLSDialer{
cachedConn: cachedConn,
dialer: dialer,
}
}
func (c *cachedTLSDialer) setRequestContext(requestCtx context.Context) {
c.requestCtx.Store(requestCtx)
}
func (c *cachedTLSDialer) dial(network, addr string) (net.Conn, error) {
if atomic.CompareAndSwapInt32(&c.usedCachedConn, 0, 1) {
conn := c.cachedConn
c.cachedConn = nil
return conn, nil
}
ctx := c.requestCtx.Load().(context.Context)
if ctx == nil {
ctx = context.Background()
}
return c.dialer(ctx, network, addr)
}
func (c *cachedTLSDialer) close() {
if atomic.CompareAndSwapInt32(&c.usedCachedConn, 0, 1) {
c.cachedConn.Close()
c.cachedConn = nil
}
}
// Close terminates the meek connection. Close waits for the relay goroutine
// to stop (in relay mode) and releases HTTP transport resources.
// A mutex is required to support net.Conn concurrency semantics.
func (meek *MeekConn) Close() (err error) {
meek.mutex.Lock()
isClosed := meek.isClosed
meek.isClosed = true
meek.mutex.Unlock()
if !isClosed {
meek.stopRunning()
if meek.cachedTLSDialer != nil {
meek.cachedTLSDialer.close()
}
meek.relayWaitGroup.Wait()
meek.transport.CloseIdleConnections()
}
return nil
}
// IsClosed implements the Closer iterface. The return value
// indicates whether the MeekConn has been closed.
func (meek *MeekConn) IsClosed() bool {
meek.mutex.Lock()
isClosed := meek.isClosed
meek.mutex.Unlock()
return isClosed
}
// RoundTrip makes a request to the meek server and returns the response.
// A new, obfuscated meek cookie is created for every request. The specified
// end point is recorded in the cookie and is not exposed as plaintext in the
// meek traffic. The caller is responsible for obfuscating the request body.
//
// RoundTrip is not safe for concurrent use, and Close must not be called
// concurrently. The caller must ensure onlt one RoundTrip call is active
// at once and that it completes before calling Close.
//
// RoundTrip is only available in round tripper mode.
func (meek *MeekConn) RoundTrip(
ctx context.Context, endPoint string, requestBody []byte) ([]byte, error) {
if !meek.roundTripperOnly {
return nil, common.ContextError(errors.New("operation unsupported"))
}
cookie, err := makeMeekCookie(
meek.clientParameters,
meek.meekCookieEncryptionPublicKey,
meek.meekObfuscatedKey,
meek.meekObfuscatorPaddingSeed,
meek.clientTunnelProtocol,
endPoint)
if err != nil {
return nil, common.ContextError(err)
}
// Note:
//
// - multiple, concurrent RoundTrip calls are unsafe due to the
// meek.cachedTLSDialer.setRequestContext call in newRequest
//
// - concurrent Close and RoundTrip calls are unsafe as Close
// does not synchronize with RoundTrip before calling
// meek.transport.CloseIdleConnections(), so resources could
// be left open.
//
// At this time, RoundTrip is used for tactics in Controller and
// the concurrency constraints are satisfied.
request, cancelFunc, err := meek.newRequest(
ctx, cookie, bytes.NewReader(requestBody), 0)
if err != nil {
return nil, common.ContextError(err)
}
defer cancelFunc()
response, err := meek.transport.RoundTrip(request)
if err == nil {
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
err = fmt.Errorf("unexpected response status code: %d", response.StatusCode)
}
}
if err != nil {
return nil, common.ContextError(err)
}
responseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, common.ContextError(err)
}
return responseBody, nil
}
// Read reads data from the connection.
// net.Conn Deadlines are ignored. net.Conn concurrency semantics are supported.
func (meek *MeekConn) Read(buffer []byte) (n int, err error) {
if meek.roundTripperOnly {
return 0, common.ContextError(errors.New("operation unsupported"))
}
if meek.IsClosed() {
return 0, common.ContextError(errors.New("meek connection is closed"))
}
// Block until there is received data to consume
var receiveBuffer *bytes.Buffer
select {
case receiveBuffer = <-meek.partialReceiveBuffer:
case receiveBuffer = <-meek.fullReceiveBuffer:
case <-meek.runCtx.Done():
return 0, common.ContextError(errors.New("meek connection has closed"))
}
n, err = receiveBuffer.Read(buffer)
meek.replaceReceiveBuffer(receiveBuffer)
return n, err
}
// Write writes data to the connection.
// net.Conn Deadlines are ignored. net.Conn concurrency semantics are supported.
func (meek *MeekConn) Write(buffer []byte) (n int, err error) {
if meek.roundTripperOnly {
return 0, common.ContextError(errors.New("operation unsupported"))
}
if meek.IsClosed() {
return 0, common.ContextError(errors.New("meek connection is closed"))
}
// Repeats until all n bytes are written
n = len(buffer)
for len(buffer) > 0 {
// Block until there is capacity in the send buffer
var sendBuffer *bytes.Buffer
select {
case sendBuffer = <-meek.emptySendBuffer:
case sendBuffer = <-meek.partialSendBuffer:
case <-meek.runCtx.Done():
return 0, common.ContextError(errors.New("meek connection has closed"))
}
writeLen := MEEK_MAX_REQUEST_PAYLOAD_LENGTH - sendBuffer.Len()
if writeLen > 0 {
if writeLen > len(buffer) {
writeLen = len(buffer)
}
_, err = sendBuffer.Write(buffer[:writeLen])
buffer = buffer[writeLen:]
}
meek.replaceSendBuffer(sendBuffer)
}
return n, err
}
// LocalAddr is a stub implementation of net.Conn.LocalAddr
func (meek *MeekConn) LocalAddr() net.Addr {
return nil
}
// RemoteAddr is a stub implementation of net.Conn.RemoteAddr
func (meek *MeekConn) RemoteAddr() net.Addr {
return nil
}
// SetDeadline is a stub implementation of net.Conn.SetDeadline
func (meek *MeekConn) SetDeadline(t time.Time) error {
return common.ContextError(errors.New("not supported"))
}
// SetReadDeadline is a stub implementation of net.Conn.SetReadDeadline
func (meek *MeekConn) SetReadDeadline(t time.Time) error {
return common.ContextError(errors.New("not supported"))
}
// SetWriteDeadline is a stub implementation of net.Conn.SetWriteDeadline
func (meek *MeekConn) SetWriteDeadline(t time.Time) error {
return common.ContextError(errors.New("not supported"))
}
func (meek *MeekConn) replaceReceiveBuffer(receiveBuffer *bytes.Buffer) {
switch {
case receiveBuffer.Len() == 0:
meek.emptyReceiveBuffer <- receiveBuffer
case receiveBuffer.Len() >= meek.fullReceiveBufferLength:
meek.fullReceiveBuffer <- receiveBuffer
default:
meek.partialReceiveBuffer <- receiveBuffer
}
}
func (meek *MeekConn) replaceSendBuffer(sendBuffer *bytes.Buffer) {
switch {
case sendBuffer.Len() == 0:
meek.emptySendBuffer <- sendBuffer
case sendBuffer.Len() >= MEEK_MAX_REQUEST_PAYLOAD_LENGTH:
meek.fullSendBuffer <- sendBuffer
default:
meek.partialSendBuffer <- sendBuffer
}
}
// relay sends and receives tunneled traffic (payload). An HTTP request is
// triggered when data is in the write queue or at a polling interval.
// There's a geometric increase, up to a maximum, in the polling interval when
// no data is exchanged. Only one HTTP request is in flight at a time.
func (meek *MeekConn) relay() {
// Note: meek.Close() calls here in relay() are made asynchronously
// (using goroutines) since Close() will wait on this WaitGroup.
defer meek.relayWaitGroup.Done()
p := meek.clientParameters.Get()
interval := prng.JitterDuration(
p.Duration(parameters.MeekMinPollInterval),
p.Float(parameters.MeekMinPollIntervalJitter))
p = nil
timeout := time.NewTimer(interval)
defer timeout.Stop()
for {
timeout.Reset(interval)
// Block until there is payload to send or it is time to poll
var sendBuffer *bytes.Buffer
select {
case sendBuffer = <-meek.partialSendBuffer:
case sendBuffer = <-meek.fullSendBuffer:
case <-timeout.C:
// In the polling case, send an empty payload
case <-meek.runCtx.Done():
// Drop through to second Done() check
}
// Check Done() again, to ensure it takes precedence
select {
case <-meek.runCtx.Done():
return
default:
}
sendPayloadSize := 0
if sendBuffer != nil {
sendPayloadSize = sendBuffer.Len()
}
// relayRoundTrip will replace sendBuffer (by calling replaceSendBuffer). This
// is a compromise to conserve memory. Using a second buffer here, we could
// copy sendBuffer and immediately replace it, unblocking meekConn.Write() and
// allowing more upstream payload to immediately enqueue. Instead, the request
// payload is read directly from sendBuffer, including retries. Only once the
// server has acknowledged the request payload is sendBuffer replaced. This
// still allows meekConn.Write() to unblock before the round trip response is
// read.
receivedPayloadSize, err := meek.relayRoundTrip(sendBuffer)
if err != nil {
select {
case <-meek.runCtx.Done():
// In this case, meek.relayRoundTrip encountered Done(). Exit without
// logging error.
return
default:
}
NoticeAlert("%s", common.ContextError(err))
go meek.Close()
return
}
// Calculate polling interval. When data is received,
// immediately request more. Otherwise, schedule next
// poll with exponential back off. Jitter and coin
// flips are used to avoid trivial, static traffic
// timing patterns.
p := meek.clientParameters.Get()
if receivedPayloadSize > 0 || sendPayloadSize > 0 {
interval = 0
} else if interval == 0 {
interval = prng.JitterDuration(
p.Duration(parameters.MeekMinPollInterval),
p.Float(parameters.MeekMinPollIntervalJitter))
} else {
if p.WeightedCoinFlip(parameters.MeekApplyPollIntervalMultiplierProbability) {
interval =
time.Duration(float64(interval) *
p.Float(parameters.MeekPollIntervalMultiplier))
}
interval = prng.JitterDuration(
interval,
p.Float(parameters.MeekPollIntervalJitter))
if interval >= p.Duration(parameters.MeekMaxPollInterval) {
interval = prng.JitterDuration(
p.Duration(parameters.MeekMaxPollInterval),
p.Float(parameters.MeekMaxPollIntervalJitter))
}
}
p = nil
}
}
// readCloseSignaller is an io.ReadCloser wrapper for an io.Reader
// that is passed, as the request body, to http.Transport.RoundTrip.
// readCloseSignaller adds the AwaitClosed call, which is used
// to schedule recycling the buffer underlying the reader only after
// RoundTrip has called Close and will no longer use the buffer.
// See: https://golang.org/pkg/net/http/#RoundTripper
type readCloseSignaller struct {
context context.Context
reader io.Reader
closed chan struct{}
}
func NewReadCloseSignaller(
context context.Context,
reader io.Reader) *readCloseSignaller {
return &readCloseSignaller{
context: context,
reader: reader,
closed: make(chan struct{}, 1),
}
}
func (r *readCloseSignaller) Read(p []byte) (int, error) {
return r.reader.Read(p)
}
func (r *readCloseSignaller) Close() error {
select {
case r.closed <- *new(struct{}):
default:
}
return nil
}
func (r *readCloseSignaller) AwaitClosed() bool {
select {
case <-r.context.Done():
case <-r.closed:
return true
}
return false
}
// newRequest performs common request setup for both relay and round
// tripper modes.
//
// newRequest is not safe for concurrent calls due to its use of
// cachedTLSDialer.setRequestContext.
//
// The caller must call the returned cancelFunc.
func (meek *MeekConn) newRequest(
ctx context.Context,
cookie *http.Cookie,
body io.Reader,
contentLength int) (*http.Request, context.CancelFunc, error) {
var requestCtx context.Context
var cancelFunc context.CancelFunc
if ctx != nil {
requestCtx, cancelFunc = context.WithCancel(ctx)
} else {
// - meek.stopRunning() will abort a round trip in flight
// - round trip will abort if it exceeds timeout
requestCtx, cancelFunc = context.WithTimeout(
meek.runCtx,
meek.clientParameters.Get().Duration(parameters.MeekRoundTripTimeout))
}
// Ensure TLS dials are made within the current request context.
if meek.cachedTLSDialer != nil {
meek.cachedTLSDialer.setRequestContext(requestCtx)
}
request, err := http.NewRequest("POST", meek.url.String(), body)
if err != nil {
return nil, cancelFunc, common.ContextError(err)
}
request = request.WithContext(requestCtx)
// Content-Length may not be be set automatically due to the
// underlying type of requestBody.
if contentLength > 0 {
request.ContentLength = int64(contentLength)
}
meek.addAdditionalHeaders(request)
request.Header.Set("Content-Type", "application/octet-stream")
if cookie == nil {
cookie = meek.cookie
}
request.AddCookie(cookie)
return request, cancelFunc, nil
}
// relayRoundTrip configures and makes the actual HTTP POST request
func (meek *MeekConn) relayRoundTrip(sendBuffer *bytes.Buffer) (int64, error) {
// Retries are made when the round trip fails. This adds resiliency
// to connection interruption and intermittent failures.
//
// At least one retry is always attempted, and retries continue
// while still within a brief deadline -- 5 seconds, currently the
// deadline for an actively probed SSH connection to timeout. There
// is a brief delay between retries, allowing for intermittent
// failure states to resolve.
//
// Failure may occur at various stages of the HTTP request:
//
// 1. Before the request begins. In this case, the entire request
// may be rerun.
//
// 2. While sending the request payload. In this case, the client
// must resend its request payload. The server will not have
// relayed its partially received request payload.
//
// 3. After sending the request payload but before receiving
// a response. The client cannot distinguish between case 2 and
// this case, case 3. The client resends its payload and the
// server detects this and skips relaying the request payload.
//
// 4. While reading the response payload. The client will omit its
// request payload when retrying, as the server has already
// acknowledged it. The client will also indicate to the server
// the amount of response payload already received, and the
// server will skip resending the indicated amount of response
// payload.
//
// Retries are indicated to the server by adding a Range header,
// which includes the response payload resend position.
defer func() {
// Ensure sendBuffer is replaced, even in error code paths.
if sendBuffer != nil {
sendBuffer.Truncate(0)
meek.replaceSendBuffer(sendBuffer)
}
}()
retries := uint(0)
p := meek.clientParameters.Get()
retryDeadline := monotime.Now().Add(p.Duration(parameters.MeekRoundTripRetryDeadline))
retryDelay := p.Duration(parameters.MeekRoundTripRetryMinDelay)
retryMaxDelay := p.Duration(parameters.MeekRoundTripRetryMaxDelay)
retryMultiplier := p.Float(parameters.MeekRoundTripRetryMultiplier)
p = nil
serverAcknowledgedRequestPayload := false
receivedPayloadSize := int64(0)
for try := 0; ; try++ {
// Omit the request payload when retrying after receiving a
// partial server response.
var signaller *readCloseSignaller
var requestBody io.ReadCloser
contentLength := 0
if !serverAcknowledgedRequestPayload && sendBuffer != nil {