forked from Psiphon-Labs/psiphon-tunnel-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tunnel.go
1601 lines (1353 loc) · 51.1 KB
/
tunnel.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"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"sync"
"sync/atomic"
"time"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/ssh"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/marionette"
"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/common/quic"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tapdance"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/transferstats"
)
// Tunneler specifies the interface required by components that use a tunnel.
// Components which use this interface may be serviced by a single Tunnel instance,
// or a Controller which manages a pool of tunnels, or any other object which
// implements Tunneler.
type Tunneler interface {
// Dial creates a tunneled connection.
//
// alwaysTunnel indicates that the connection should always be tunneled. If this
// is not set, the connection may be made directly, depending on split tunnel
// classification, when that feature is supported and active.
//
// downstreamConn is an optional parameter which specifies a connection to be
// explicitly closed when the Dialed connection is closed. For instance, this
// is used to close downstreamConn App<->LocalProxy connections when the related
// LocalProxy<->SshPortForward connections close.
Dial(remoteAddr string, alwaysTunnel bool, downstreamConn net.Conn) (conn net.Conn, err error)
DirectDial(remoteAddr string) (conn net.Conn, err error)
SignalComponentFailure()
}
// TunnelOwner specifies the interface required by Tunnel to notify its
// owner when it has failed. The owner may, as in the case of the Controller,
// remove the tunnel from its list of active tunnels.
type TunnelOwner interface {
SignalSeededNewSLOK()
SignalTunnelFailure(tunnel *Tunnel)
}
// Tunnel is a connection to a Psiphon server. An established
// tunnel includes a network connection to the specified server
// and an SSH session built on top of that transport.
type Tunnel struct {
mutex *sync.Mutex
config *Config
isActivated bool
isDiscarded bool
isClosed bool
dialParams *DialParameters
livenessTestMetrics *livenessTestMetrics
serverContext *ServerContext
monitoringStartTime time.Time
conn *common.BurstMonitoredConn
sshClient *ssh.Client
sshServerRequests <-chan *ssh.Request
operateWaitGroup *sync.WaitGroup
operateCtx context.Context
stopOperate context.CancelFunc
signalPortForwardFailure chan struct{}
totalPortForwardFailures int
adjustedEstablishStartTime time.Time
establishDuration time.Duration
establishedTime time.Time
handledSSHKeepAliveFailure int32
inFlightConnectedRequestSignal chan struct{}
}
// getCustomParameters helpers wrap the verbose function call chain required
// to get a current snapshot of the parameters.Parameters customized with the
// dial parameters associated with a tunnel.
func (tunnel *Tunnel) getCustomParameters() parameters.ParametersAccessor {
return getCustomParameters(tunnel.config, tunnel.dialParams)
}
func getCustomParameters(
config *Config, dialParams *DialParameters) parameters.ParametersAccessor {
return config.GetParameters().GetCustom(dialParams.NetworkLatencyMultiplier)
}
// ConnectTunnel first makes a network transport connection to the
// Psiphon server and then establishes an SSH client session on top of
// that transport. The SSH server is authenticated using the public
// key in the server entry.
// Depending on the server's capabilities, the connection may use
// plain SSH over TCP, obfuscated SSH over TCP, or obfuscated SSH over
// HTTP (meek protocol).
// When requiredProtocol is not blank, that protocol is used. Otherwise,
// the a random supported protocol is used.
//
// Call Activate on a connected tunnel to complete its establishment
// before using.
//
// Tunnel establishment is split into two phases: connection, and
// activation. The Controller will run many ConnectTunnel calls
// concurrently and then, to avoid unnecessary overhead from making
// handshake requests and starting operateTunnel from tunnels which
// may be discarded, call Activate on connected tunnels sequentially
// as necessary.
//
func ConnectTunnel(
ctx context.Context,
config *Config,
adjustedEstablishStartTime time.Time,
dialParams *DialParameters) (*Tunnel, error) {
// Build transport layers and establish SSH connection. Note that
// dialConn and monitoredConn are the same network connection.
dialResult, err := dialTunnel(ctx, config, dialParams)
if err != nil {
return nil, errors.Trace(err)
}
// The tunnel is now connected
return &Tunnel{
mutex: new(sync.Mutex),
config: config,
dialParams: dialParams,
livenessTestMetrics: dialResult.livenessTestMetrics,
monitoringStartTime: dialResult.monitoringStartTime,
conn: dialResult.monitoredConn,
sshClient: dialResult.sshClient,
sshServerRequests: dialResult.sshRequests,
// A buffer allows at least one signal to be sent even when the receiver is
// not listening. Senders should not block.
signalPortForwardFailure: make(chan struct{}, 1),
adjustedEstablishStartTime: adjustedEstablishStartTime,
}, nil
}
// Activate completes the tunnel establishment, performing the handshake
// request and starting operateTunnel, the worker that monitors the tunnel
// and handles periodic management.
func (tunnel *Tunnel) Activate(
ctx context.Context, tunnelOwner TunnelOwner) (retErr error) {
// Ensure that, unless the base context is cancelled, any replayed dial
// parameters are cleared, no longer to be retried, if the tunnel fails to
// activate.
activationSucceeded := false
baseCtx := ctx
defer func() {
if !activationSucceeded && baseCtx.Err() == nil {
tunnel.dialParams.Failed(tunnel.config)
_ = RecordFailedTunnelStat(
tunnel.config,
tunnel.dialParams,
tunnel.livenessTestMetrics,
-1,
-1,
retErr)
}
}()
// Create a new Psiphon API server context for this tunnel. This includes
// performing a handshake request. If the handshake fails, this activation
// fails.
var serverContext *ServerContext
if !tunnel.config.DisableApi {
NoticeInfo(
"starting server context for %s",
tunnel.dialParams.ServerEntry.GetDiagnosticID())
// Call NewServerContext in a goroutine, as it blocks on a network operation,
// the handshake request, and would block shutdown. If the shutdown signal is
// received, close the tunnel, which will interrupt the handshake request
// that may be blocking NewServerContext.
//
// Timeout after PsiphonApiServerTimeoutSeconds. NewServerContext may not
// return if the tunnel network connection is unstable during the handshake
// request. At this point, there is no operateTunnel monitor that will detect
// this condition with SSH keep alives.
timeout := tunnel.getCustomParameters().Duration(
parameters.PsiphonAPIRequestTimeout)
if timeout > 0 {
var cancelFunc context.CancelFunc
ctx, cancelFunc = context.WithTimeout(ctx, timeout)
defer cancelFunc()
}
type newServerContextResult struct {
serverContext *ServerContext
err error
}
resultChannel := make(chan newServerContextResult)
go func() {
serverContext, err := NewServerContext(tunnel)
resultChannel <- newServerContextResult{
serverContext: serverContext,
err: err,
}
}()
var result newServerContextResult
select {
case result = <-resultChannel:
case <-ctx.Done():
result.err = ctx.Err()
// Interrupt the goroutine
tunnel.Close(true)
<-resultChannel
}
if result.err != nil {
return errors.Trace(result.err)
}
serverContext = result.serverContext
}
// The activation succeeded.
activationSucceeded = true
tunnel.mutex.Lock()
// It may happen that the tunnel gets closed while Activate is running.
// In this case, abort here, to ensure that the operateTunnel goroutine
// will not be launched after Close is called.
if tunnel.isClosed {
return errors.TraceNew("tunnel is closed")
}
tunnel.isActivated = true
tunnel.serverContext = serverContext
// establishDuration is the elapsed time between the controller starting tunnel
// establishment and this tunnel being established. The reported value represents
// how long the user waited between starting the client and having a usable tunnel;
// or how long between the client detecting an unexpected tunnel disconnect and
// completing automatic reestablishment.
//
// This time period may include time spent unsuccessfully connecting to other
// servers. Time spent waiting for network connectivity is excluded.
tunnel.establishDuration = time.Since(tunnel.adjustedEstablishStartTime)
tunnel.establishedTime = time.Now()
// Use the Background context instead of the controller run context, as tunnels
// are terminated when the controller calls tunnel.Close.
tunnel.operateCtx, tunnel.stopOperate = context.WithCancel(context.Background())
tunnel.operateWaitGroup = new(sync.WaitGroup)
// Spawn the operateTunnel goroutine, which monitors the tunnel and handles periodic
// stats updates.
tunnel.operateWaitGroup.Add(1)
go tunnel.operateTunnel(tunnelOwner)
tunnel.mutex.Unlock()
return nil
}
// Close stops operating the tunnel and closes the underlying connection.
// Supports multiple and/or concurrent calls to Close().
// When isDiscarded is set, operateTunnel will not attempt to send final
// status requests.
func (tunnel *Tunnel) Close(isDiscarded bool) {
tunnel.mutex.Lock()
tunnel.isDiscarded = isDiscarded
isActivated := tunnel.isActivated
isClosed := tunnel.isClosed
tunnel.isClosed = true
tunnel.mutex.Unlock()
if !isClosed {
// Signal operateTunnel to stop before closing the tunnel -- this
// allows a final status request to be made in the case of an orderly
// shutdown.
// A timer is set, so if operateTunnel takes too long to stop, the
// tunnel is closed, which will interrupt any slow final status request.
if isActivated {
timeout := tunnel.getCustomParameters().Duration(
parameters.TunnelOperateShutdownTimeout)
afterFunc := time.AfterFunc(
timeout,
func() { tunnel.conn.Close() })
tunnel.stopOperate()
tunnel.operateWaitGroup.Wait()
afterFunc.Stop()
}
tunnel.sshClient.Close()
// tunnel.conn.Close() may get called multiple times, which is allowed.
tunnel.conn.Close()
err := tunnel.sshClient.Wait()
if err != nil {
NoticeWarning("close tunnel ssh error: %s", err)
}
}
// Log burst metrics now that the BurstMonitoredConn is closed.
// Metrics will be empty when burst monitoring is disabled.
if !isDiscarded && isActivated {
burstMetrics := tunnel.conn.GetMetrics(tunnel.monitoringStartTime)
if len(burstMetrics) > 0 {
NoticeBursts(
tunnel.dialParams.ServerEntry.GetDiagnosticID(),
burstMetrics)
}
}
}
// SetInFlightConnectedRequest checks if a connected request can begin and
// sets the channel used to signal that the request is complete.
//
// The caller must not initiate a connected request when
// SetInFlightConnectedRequest returns false. When SetInFlightConnectedRequest
// returns true, the caller must call SetInFlightConnectedRequest(nil) when
// the connected request completes.
func (tunnel *Tunnel) SetInFlightConnectedRequest(requestSignal chan struct{}) bool {
tunnel.mutex.Lock()
defer tunnel.mutex.Unlock()
// If already closing, don't start a connected request: the
// TunnelOperateShutdownTimeout period may be nearly expired.
if tunnel.isClosed {
return false
}
if requestSignal == nil {
// Not already in-flight (not expected)
if tunnel.inFlightConnectedRequestSignal == nil {
return false
}
} else {
// Already in-flight (not expected)
if tunnel.inFlightConnectedRequestSignal != nil {
return false
}
}
tunnel.inFlightConnectedRequestSignal = requestSignal
return true
}
// AwaitInFlightConnectedRequest waits for the signal that any in-flight
// connected request is complete.
//
// AwaitInFlightConnectedRequest may block until the connected request is
// aborted by terminating the tunnel.
func (tunnel *Tunnel) AwaitInFlightConnectedRequest() {
tunnel.mutex.Lock()
requestSignal := tunnel.inFlightConnectedRequestSignal
tunnel.mutex.Unlock()
if requestSignal != nil {
<-requestSignal
}
}
// IsActivated returns the tunnel's activated flag.
func (tunnel *Tunnel) IsActivated() bool {
tunnel.mutex.Lock()
defer tunnel.mutex.Unlock()
return tunnel.isActivated
}
// IsDiscarded returns the tunnel's discarded flag.
func (tunnel *Tunnel) IsDiscarded() bool {
tunnel.mutex.Lock()
defer tunnel.mutex.Unlock()
return tunnel.isDiscarded
}
// SendAPIRequest sends an API request as an SSH request through the tunnel.
// This function blocks awaiting a response. Only one request may be in-flight
// at once; a concurrent SendAPIRequest will block until an active request
// receives its response (or the SSH connection is terminated).
func (tunnel *Tunnel) SendAPIRequest(
name string, requestPayload []byte) ([]byte, error) {
ok, responsePayload, err := tunnel.sshClient.Conn.SendRequest(
name, true, requestPayload)
if err != nil {
return nil, errors.Trace(err)
}
if !ok {
return nil, errors.TraceNew("API request rejected")
}
return responsePayload, nil
}
// Dial establishes a port forward connection through the tunnel
// This Dial doesn't support split tunnel, so alwaysTunnel is not referenced
func (tunnel *Tunnel) Dial(
remoteAddr string, alwaysTunnel bool, downstreamConn net.Conn) (net.Conn, error) {
channel, err := tunnel.dialChannel("tcp", remoteAddr)
if err != nil {
return nil, errors.Trace(err)
}
netConn, ok := channel.(net.Conn)
if !ok {
return nil, errors.Tracef("unexpected channel type: %T", channel)
}
conn := &TunneledConn{
Conn: netConn,
tunnel: tunnel,
downstreamConn: downstreamConn}
return tunnel.wrapWithTransferStats(conn), nil
}
func (tunnel *Tunnel) DialPacketTunnelChannel() (net.Conn, error) {
channel, err := tunnel.dialChannel(protocol.PACKET_TUNNEL_CHANNEL_TYPE, "")
if err != nil {
return nil, errors.Trace(err)
}
sshChannel, ok := channel.(ssh.Channel)
if !ok {
return nil, errors.Tracef("unexpected channel type: %T", channel)
}
NoticeInfo("DialPacketTunnelChannel: established channel")
conn := newChannelConn(sshChannel)
// wrapWithTransferStats will track bytes transferred for the
// packet tunnel. It will count packet overhead (TCP/UDP/IP headers).
//
// Since the data in the channel is not HTTP or TLS, no domain bytes
// counting is expected.
//
// transferstats are also used to determine that there's been recent
// activity and skip periodic SSH keep alives; see Tunnel.operateTunnel.
return tunnel.wrapWithTransferStats(conn), nil
}
func (tunnel *Tunnel) dialChannel(channelType, remoteAddr string) (interface{}, error) {
if !tunnel.IsActivated() {
return nil, errors.TraceNew("tunnel is not activated")
}
// Note: there is no dial context since SSH port forward dials cannot
// be interrupted directly. Closing the tunnel will interrupt the dials.
// A timeout is set to unblock this function, but the goroutine may
// not exit until the tunnel is closed.
type channelDialResult struct {
channel interface{}
err error
}
// Use a buffer of 1 as there are two senders and only one guaranteed receive.
results := make(chan *channelDialResult, 1)
afterFunc := time.AfterFunc(
tunnel.getCustomParameters().Duration(
parameters.TunnelPortForwardDialTimeout),
func() {
results <- &channelDialResult{
nil, errors.Tracef("channel dial timeout: %s", channelType)}
})
defer afterFunc.Stop()
go func() {
result := new(channelDialResult)
if channelType == "tcp" {
result.channel, result.err =
tunnel.sshClient.Dial("tcp", remoteAddr)
} else {
var sshRequests <-chan *ssh.Request
result.channel, sshRequests, result.err =
tunnel.sshClient.OpenChannel(channelType, nil)
if result.err == nil {
go ssh.DiscardRequests(sshRequests)
}
}
if result.err != nil {
result.err = errors.Trace(result.err)
}
results <- result
}()
result := <-results
if result.err != nil {
// TODO: conditional on type of error or error message?
select {
case tunnel.signalPortForwardFailure <- struct{}{}:
default:
}
return nil, errors.Trace(result.err)
}
return result.channel, nil
}
func (tunnel *Tunnel) wrapWithTransferStats(conn net.Conn) net.Conn {
// Tunnel does not have a serverContext when DisableApi is set. We still use
// transferstats.Conn to count bytes transferred for monitoring tunnel
// quality.
var regexps *transferstats.Regexps
if tunnel.serverContext != nil {
regexps = tunnel.serverContext.StatsRegexps()
}
return transferstats.NewConn(
conn, tunnel.dialParams.ServerEntry.IpAddress, regexps)
}
// SignalComponentFailure notifies the tunnel that an associated component has failed.
// This will terminate the tunnel.
func (tunnel *Tunnel) SignalComponentFailure() {
NoticeWarning("tunnel received component failure signal")
tunnel.Close(false)
}
// TunneledConn implements net.Conn and wraps a port forward connection.
// It is used to hook into Read and Write to observe I/O errors and
// report these errors back to the tunnel monitor as port forward failures.
// TunneledConn optionally tracks a peer connection to be explicitly closed
// when the TunneledConn is closed.
type TunneledConn struct {
net.Conn
tunnel *Tunnel
downstreamConn net.Conn
}
func (conn *TunneledConn) Read(buffer []byte) (n int, err error) {
n, err = conn.Conn.Read(buffer)
if err != nil && err != io.EOF {
// Report new failure. Won't block; assumes the receiver
// has a sufficient buffer for the threshold number of reports.
// TODO: conditional on type of error or error message?
select {
case conn.tunnel.signalPortForwardFailure <- struct{}{}:
default:
}
}
return
}
func (conn *TunneledConn) Write(buffer []byte) (n int, err error) {
n, err = conn.Conn.Write(buffer)
if err != nil && err != io.EOF {
// Same as TunneledConn.Read()
select {
case conn.tunnel.signalPortForwardFailure <- struct{}{}:
default:
}
}
return
}
func (conn *TunneledConn) Close() error {
if conn.downstreamConn != nil {
conn.downstreamConn.Close()
}
return conn.Conn.Close()
}
type dialResult struct {
dialConn net.Conn
monitoringStartTime time.Time
monitoredConn *common.BurstMonitoredConn
sshClient *ssh.Client
sshRequests <-chan *ssh.Request
livenessTestMetrics *livenessTestMetrics
}
// dialTunnel is a helper that builds the transport layers and establishes the
// SSH connection. When additional dial configuration is used, dial metrics
// are recorded and returned.
func dialTunnel(
ctx context.Context,
config *Config,
dialParams *DialParameters) (_ *dialResult, retErr error) {
// Return immediately when overall context is canceled or timed-out. This
// avoids notice noise.
err := ctx.Err()
if err != nil {
return nil, errors.Trace(err)
}
p := getCustomParameters(config, dialParams)
timeout := p.Duration(parameters.TunnelConnectTimeout)
rateLimits := p.RateLimits(parameters.TunnelRateLimits)
obfuscatedSSHMinPadding := p.Int(parameters.ObfuscatedSSHMinPadding)
obfuscatedSSHMaxPadding := p.Int(parameters.ObfuscatedSSHMaxPadding)
livenessTestMinUpstreamBytes := p.Int(parameters.LivenessTestMinUpstreamBytes)
livenessTestMaxUpstreamBytes := p.Int(parameters.LivenessTestMaxUpstreamBytes)
livenessTestMinDownstreamBytes := p.Int(parameters.LivenessTestMinDownstreamBytes)
livenessTestMaxDownstreamBytes := p.Int(parameters.LivenessTestMaxDownstreamBytes)
burstUpstreamTargetBytes := int64(p.Int(parameters.ClientBurstUpstreamTargetBytes))
burstUpstreamDeadline := p.Duration(parameters.ClientBurstUpstreamDeadline)
burstDownstreamTargetBytes := int64(p.Int(parameters.ClientBurstDownstreamTargetBytes))
burstDownstreamDeadline := p.Duration(parameters.ClientBurstDownstreamDeadline)
p.Close()
// Ensure that, unless the base context is cancelled, any replayed dial
// parameters are cleared, no longer to be retried, if the tunnel fails to
// connect.
//
// Limitation: dials that fail to connect due to the server being in a
// load-limiting state are not distinguished and excepted from this
// logic.
dialSucceeded := false
baseCtx := ctx
var failedTunnelLivenessTestMetrics *livenessTestMetrics
defer func() {
if !dialSucceeded && baseCtx.Err() == nil {
dialParams.Failed(config)
_ = RecordFailedTunnelStat(
config,
dialParams,
failedTunnelLivenessTestMetrics,
-1,
-1,
retErr)
}
}()
var cancelFunc context.CancelFunc
ctx, cancelFunc = context.WithTimeout(ctx, timeout)
defer cancelFunc()
// DialDuration is the elapsed time for both successful and failed tunnel
// dials. For successful tunnels, it includes any the network protocol
// handshake(s), obfuscation protocol handshake(s), SSH handshake, and
// liveness test, when performed.
//
// Note: ensure DialDuration is set before calling any function which logs
// dial_duration.
startDialTime := time.Now()
defer func() {
dialParams.DialDuration = time.Since(startDialTime)
}()
// Note: dialParams.MeekResolvedIPAddress isn't set until the dial begins,
// so it will always be blank in NoticeConnectingServer.
NoticeConnectingServer(dialParams)
// Create the base transport: meek or direct connection
var dialConn net.Conn
if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
dialConn, err = DialMeek(
ctx,
dialParams.GetMeekConfig(),
dialParams.GetDialConfig())
if err != nil {
return nil, errors.Trace(err)
}
} else if protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
packetConn, remoteAddr, err := NewUDPConn(
ctx,
dialParams.DirectDialAddress,
dialParams.GetDialConfig())
if err != nil {
return nil, errors.Trace(err)
}
dialConn, err = quic.Dial(
ctx,
packetConn,
remoteAddr,
dialParams.QUICDialSNIAddress,
dialParams.QUICVersion,
dialParams.ServerEntry.SshObfuscatedKey,
dialParams.ObfuscatedQUICPaddingSeed)
if err != nil {
return nil, errors.Trace(err)
}
} else if protocol.TunnelProtocolUsesMarionette(dialParams.TunnelProtocol) {
dialConn, err = marionette.Dial(
ctx,
NewNetDialer(dialParams.GetDialConfig()),
dialParams.ServerEntry.MarionetteFormat,
dialParams.DirectDialAddress)
if err != nil {
return nil, errors.Trace(err)
}
} else if protocol.TunnelProtocolUsesTapdance(dialParams.TunnelProtocol) {
dialConn, err = tapdance.Dial(
ctx,
config.EmitTapdanceLogs,
config.GetTapdanceDirectory(),
NewNetDialer(dialParams.GetDialConfig()),
dialParams.DirectDialAddress)
if err != nil {
return nil, errors.Trace(err)
}
} else {
dialConn, err = DialTCP(
ctx,
dialParams.DirectDialAddress,
dialParams.GetDialConfig())
if err != nil {
return nil, errors.Trace(err)
}
}
// Some conns report additional metrics. fragmentor.Conns report
// fragmentor configs.
//
// Limitation: for meek, GetMetrics from underlying fragmentor.Conn(s)
// should be called in order to log fragmentor metrics for meek sessions.
if metricsSource, ok := dialConn.(common.MetricsSource); ok {
dialParams.DialConnMetrics = metricsSource
}
// If dialConn is not a Closer, tunnel failure detection may be slower
if _, ok := dialConn.(common.Closer); !ok {
NoticeWarning("tunnel.dialTunnel: dialConn is not a Closer")
}
cleanupConn := dialConn
defer func() {
// Cleanup on error
if cleanupConn != nil {
cleanupConn.Close()
}
}()
monitoringStartTime := time.Now()
monitoredConn := common.NewBurstMonitoredConn(
dialConn,
false,
burstUpstreamTargetBytes, burstUpstreamDeadline,
burstDownstreamTargetBytes, burstDownstreamDeadline)
// Apply throttling (if configured)
throttledConn := common.NewThrottledConn(
monitoredConn,
rateLimits)
// Add obfuscated SSH layer
var sshConn net.Conn = throttledConn
if protocol.TunnelProtocolUsesObfuscatedSSH(dialParams.TunnelProtocol) {
obfuscatedSSHConn, err := obfuscator.NewClientObfuscatedSSHConn(
throttledConn,
dialParams.ServerEntry.SshObfuscatedKey,
dialParams.ObfuscatorPaddingSeed,
&obfuscatedSSHMinPadding,
&obfuscatedSSHMaxPadding)
if err != nil {
return nil, errors.Trace(err)
}
sshConn = obfuscatedSSHConn
dialParams.ObfuscatedSSHConnMetrics = obfuscatedSSHConn
}
// Now establish the SSH session over the conn transport
expectedPublicKey, err := base64.StdEncoding.DecodeString(
dialParams.ServerEntry.SshHostKey)
if err != nil {
return nil, errors.Trace(err)
}
sshCertChecker := &ssh.CertChecker{
HostKeyFallback: func(addr string, remote net.Addr, publicKey ssh.PublicKey) error {
if !bytes.Equal(expectedPublicKey, publicKey.Marshal()) {
return errors.TraceNew("unexpected host public key")
}
return nil
},
}
sshPasswordPayload := &protocol.SSHPasswordPayload{
SessionId: config.SessionID,
SshPassword: dialParams.ServerEntry.SshPassword,
ClientCapabilities: []string{protocol.CLIENT_CAPABILITY_SERVER_REQUESTS},
}
payload, err := json.Marshal(sshPasswordPayload)
if err != nil {
return nil, errors.Trace(err)
}
sshClientConfig := &ssh.ClientConfig{
User: dialParams.ServerEntry.SshUsername,
Auth: []ssh.AuthMethod{
ssh.Password(string(payload)),
},
HostKeyCallback: sshCertChecker.CheckHostKey,
ClientVersion: dialParams.SSHClientVersion,
}
sshClientConfig.KEXPRNGSeed = dialParams.SSHKEXSeed
if protocol.TunnelProtocolUsesObfuscatedSSH(dialParams.TunnelProtocol) {
if config.ObfuscatedSSHAlgorithms != nil {
sshClientConfig.KeyExchanges = []string{config.ObfuscatedSSHAlgorithms[0]}
sshClientConfig.Ciphers = []string{config.ObfuscatedSSHAlgorithms[1]}
sshClientConfig.MACs = []string{config.ObfuscatedSSHAlgorithms[2]}
sshClientConfig.HostKeyAlgorithms = []string{config.ObfuscatedSSHAlgorithms[3]}
} else {
// With Encrypt-then-MAC hash algorithms, packet length is
// transmitted in plaintext, which aids in traffic analysis.
//
// TUNNEL_PROTOCOL_SSH is excepted since its KEX appears in plaintext,
// and the protocol is intended to look like SSH on the wire.
sshClientConfig.NoEncryptThenMACHash = true
}
} else {
// For TUNNEL_PROTOCOL_SSH only, the server is expected to randomize
// its KEX; setting PeerKEXPRNGSeed will ensure successful negotiation
// betweem two randomized KEXes.
if dialParams.ServerEntry.SshObfuscatedKey != "" {
sshClientConfig.PeerKEXPRNGSeed, err = protocol.DeriveSSHServerKEXPRNGSeed(
dialParams.ServerEntry.SshObfuscatedKey)
if err != nil {
return nil, errors.Trace(err)
}
}
}
// The ssh session establishment (via ssh.NewClientConn) is wrapped
// in a timeout to ensure it won't hang. We've encountered firewalls
// that allow the TCP handshake to complete but then send a RST to the
// server-side and nothing to the client-side, and if that happens
// while ssh.NewClientConn is reading, it may wait forever. The timeout
// closes the conn, which interrupts it.
// Note: TCP handshake timeouts are provided by TCPConn, and session
// timeouts *after* ssh establishment are provided by the ssh keep alive
// in operate tunnel.
type sshNewClientResult struct {
sshClient *ssh.Client
sshRequests <-chan *ssh.Request
livenessTestMetrics *livenessTestMetrics
err error
}
resultChannel := make(chan sshNewClientResult)
// Call NewClientConn in a goroutine, as it blocks on SSH handshake network
// operations, and would block canceling or shutdown. If the parent context
// is canceled, close the net.Conn underlying SSH, which will interrupt the
// SSH handshake that may be blocking NewClientConn.
go func() {
// The following is adapted from ssh.Dial(), here using a custom conn
// The sshAddress is passed through to host key verification callbacks; we don't use it.
sshAddress := ""
sshClientConn, sshChannels, sshRequests, err := ssh.NewClientConn(
sshConn, sshAddress, sshClientConfig)
var sshClient *ssh.Client
var metrics *livenessTestMetrics
if err == nil {
// sshRequests is handled by operateTunnel.
// ssh.NewClient also expects to handle the sshRequests
// value from ssh.NewClientConn and will spawn a goroutine
// to handle the <-chan *ssh.Request, so we must provide
// a closed channel to ensure that goroutine halts instead
// of hanging on a nil channel.
noRequests := make(chan *ssh.Request)
close(noRequests)
sshClient = ssh.NewClient(sshClientConn, sshChannels, noRequests)
if livenessTestMaxUpstreamBytes > 0 || livenessTestMaxDownstreamBytes > 0 {
// When configured, perform a liveness test which sends and
// receives bytes through the tunnel to ensure the tunnel had
// not been blocked upon or shortly after connecting. This
// test is performed concurrently for each establishment
// candidate before selecting a successful tunnel.
//
// Note that the liveness test is subject to the
// TunnelConnectTimeout, which should be adjusted
// accordinging.
metrics, err = performLivenessTest(
sshClient,
livenessTestMinUpstreamBytes, livenessTestMaxUpstreamBytes,
livenessTestMinDownstreamBytes, livenessTestMaxDownstreamBytes,
dialParams.LivenessTestSeed)
// Skip notice when cancelling.
if baseCtx.Err() == nil {
NoticeLivenessTest(
dialParams.ServerEntry.GetDiagnosticID(), metrics, err == nil)
}
}
}
resultChannel <- sshNewClientResult{sshClient, sshRequests, metrics, err}
}()
var result sshNewClientResult
select {
case result = <-resultChannel:
case <-ctx.Done():
// Interrupt the goroutine and capture its error context to
// distinguish point of failure.
err := ctx.Err()
sshConn.Close()
result = <-resultChannel
if result.err != nil {
result.err = fmt.Errorf("%s: %s", err, result.err)
} else {
result.err = err
}
}
if result.err != nil {
failedTunnelLivenessTestMetrics = result.livenessTestMetrics
return nil, errors.Trace(result.err)
}
dialSucceeded = true
NoticeConnectedServer(dialParams)
cleanupConn = nil
// Note: dialConn may be used to close the underlying network connection
// but should not be used to perform I/O as that would interfere with SSH
// (and also bypasses throttling).
return &dialResult{
dialConn: dialConn,
monitoringStartTime: monitoringStartTime,
monitoredConn: monitoredConn,
sshClient: result.sshClient,
sshRequests: result.sshRequests,
livenessTestMetrics: result.livenessTestMetrics},
nil
}