-
Notifications
You must be signed in to change notification settings - Fork 19
/
cli.go
277 lines (246 loc) · 7.98 KB
/
cli.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
package sshego
import (
"context"
"fmt"
"log"
"net"
"strings"
"time"
ssh "github.com/glycerine/sshego/xendor/github.com/glycerine/xcryptossh"
)
// DialConfig provides Dial() with what
// it needs in order to establish an encrypted
// and authenticated ssh connection.
//
type DialConfig struct {
// ClientKnownHostsPath is the path to the file
// on client's disk that holds the known server keys.
ClientKnownHostsPath string
// cached to avoid a disk read, we only read
// from ClientKnownHostsPath if KnownHosts is nil.
// Users of DialConfig can leave this nil and
// simply provide ClientKnownHostsPath. It is
// exposed in case you need to invalidate the
// cache and start again.
KnownHosts *KnownHosts
// the username to login under
Mylogin string
// the path on the local file system (client side) from
// which to read the client's RSA private key.
RsaPath string
// the time-based one-time password configuration
TotpUrl string
// Pw is the passphrase
Pw string
// which sshd to connect to, host and port.
Sshdhost string
Sshdport int64
// DownstreamHostPort is the host:port string of
// the tcp address to which the sshd should forward
// our connection to.
DownstreamHostPort string
// TofuAddIfNotKnown, for maximum security,
// should be always left false and
// the host key database should be configured
// manually. If true, the client trusts the server's
// provided key and stores it, which creates
// vulnerability to a MITM attack.
//
// TOFU stands for Trust-On-First-Use.
//
// If set to true, Dial() will stoop
// after storing a new key, or error
// out if the key is already known.
// In either case, a 2nd attempt at
// Dial is required wherein on the
// TofuAddIfNotKnown is set to false.
//
TofuAddIfNotKnown bool
// DoNotUpdateSshKnownHosts prevents writing
// to the file given by ClientKnownHostsPath, if true.
DoNotUpdateSshKnownHosts bool
Verbose bool
// test only; see SshegoConfig
TestAllowOneshotConnect bool
// SkipKeepAlive default to false and we send
// a keepalive every minute.
SkipKeepAlive bool
// CancelKeepAlive can be closed to cleanup the
// keepalive goroutine.
CancelKeepAlive chan struct{}
}
// Dial is a convenience method for contacting an sshd
// over tcp and creating a direct-tcpip encrypted stream.
// It is a simple two-step sequence of calling
// dc.Cfg.SSHConnect() and then calling Dial() on the
// returned *ssh.Client.
//
// PRE: dc.Cfg.KnownHosts should already be instantiated.
// To prevent MITM attacks, the host we contact at
// hostport must have its server key must be already
// in the KnownHosts.
//
// dc.RsaPath is the path to the our (the client's) rsa
// private key file.
//
// dc.DownstreamHostPort is the host:port tcp address string
// to which the sshd should forward our connection after successful
// authentication.
//
func (dc *DialConfig) Dial(parCtx context.Context) (net.Conn, *ssh.Client, error) {
cfg := NewSshegoConfig()
cfg.BitLenRSAkeys = 4096
cfg.DirectTcp = true
cfg.AddIfNotKnown = dc.TofuAddIfNotKnown
cfg.Debug = dc.Verbose
cfg.TestAllowOneshotConnect = dc.TestAllowOneshotConnect
var err error
p("DialConfig.Dial: dc= %#v\n", dc)
if dc.KnownHosts == nil {
dc.KnownHosts, err = NewKnownHosts(dc.ClientKnownHostsPath, KHSsh)
if err != nil {
return nil, nil, err
}
p("after NewKnownHosts: DialConfig.Dial: dc.KnownHosts = %#v\n", dc.KnownHosts)
dc.KnownHosts.NoSave = dc.DoNotUpdateSshKnownHosts
}
var sshClientConn *ssh.Client
p("about to SSHConnect to dc.Sshdhost='%s'", dc.Sshdhost)
p(" ...and SSHConnect called on cfg = '%#v'\n", cfg)
// connection refused errors are common enough
// that we do a simple retry logic after a brief pause here.
retryCount := 3
try := 0
var okCtx context.Context
for ; try < retryCount; try++ {
ctx, cancelctx := context.WithCancel(parCtx)
childHalt := ssh.NewHalter()
// the 2nd argument is the underlying most-basic
// TCP net.Conn. We don't need to retrieve here since
// ctx or cfg.Halt will close it for us if need be.
sshClientConn, _, err = cfg.SSHConnect(ctx, dc.KnownHosts,
dc.Mylogin, dc.RsaPath, dc.Sshdhost, dc.Sshdport,
dc.Pw, dc.TotpUrl, childHalt)
if err == nil {
// tie ctx and childHalt together
go ssh.MAD(ctx, cancelctx, childHalt)
okCtx = ctx
break
} else {
cancelctx()
childHalt.ReqStop.Close()
childHalt.Done.Close()
if strings.Contains(err.Error(), "getsockopt: connection refused") {
// simple connection error, just try again in a bit
time.Sleep(10 * time.Millisecond)
continue
}
break
}
}
if err != nil {
return nil, nil, err
}
// enforce safe known-hosts hygene
//cfg.TestAllowOneshotConnect = false
//cfg.AddIfNotKnown = false
//dc.TofuAddIfNotKnown = false
// Here is how to dial over an encrypted ssh channel.
// This produces direct-tcpip forwarding -- in other
// words we talk to the server at dest via the sshd,
// but no other port is opened and so we have
// exclusive access. This prevents other users and
// their processes on this localhost from also
// using the ssh connection (i.e. without authenticating).
hp := strings.Trim(dc.DownstreamHostPort, "\n\r\t ")
tryUnixDomain := false
var host string
if strings.HasSuffix(hp, ":-2") {
tryUnixDomain = true
host = hp[:len(hp)-3]
} else {
host, _, err = net.SplitHostPort(hp)
}
if err != nil {
if strings.Contains(err.Error(), "missing port in address") {
// probably unix-domain
tryUnixDomain = true
host = hp
} else {
log.Printf("error from net.SplitHostPort on '%s': '%v'",
hp, err)
return nil, nil, fmt.Errorf("error from net.SplitHostPort "+
"on '%s': '%v'", hp, err)
}
}
if tryUnixDomain || (len(host) > 0 && host[0] == '/') {
// a unix-domain socket request
nc, err := DialRemoteUnixDomain(okCtx, sshClientConn, host)
p("DialRemoteUnixDomain had error '%v'", err)
return nc, sshClientConn, err
}
sshClientConn.TmpCtx = okCtx
nc, err := sshClientConn.Dial("tcp", hp)
// Start keepalives on the tcp, unless turned off.
if err == nil {
if !dc.SkipKeepAlive {
err, cancel := StartKeepalives(okCtx, sshClientConn)
dc.CancelKeepAlive = cancel
panicOn(err)
}
}
return nc, sshClientConn, err
}
// StartKeepalives starts a background goroutine
// that will send a keepalive on sshClientConn
// every 60 seconds. Closing the returned
// channel will exit the goroutine.
func StartKeepalives(ctx context.Context, sshClientConn *ssh.Client) (error, chan struct{}) {
cancel := make(chan struct{})
_, _, err := sshClientConn.SendRequest(ctx, "keepalive@openssh.com", true, nil)
if err != nil {
return err, cancel
}
go func() {
for {
select {
case <-time.After(time.Minute):
sshClientConn.SendRequest(ctx, "keepalive@openssh.com", true, nil)
case <-cancel:
return
}
}
}()
return nil, cancel
}
// derived from ssh.NewClient: NewSSHClient creates a Client on top of the given connection.
func (cfg *SshegoConfig) NewSSHClient(ctx context.Context, c ssh.Conn, chans <-chan ssh.NewChannel, reqs <-chan *ssh.Request, halt *ssh.Halter) *ssh.Client {
conn := &ssh.Client{
Conn: c,
ChannelHandlers: make(map[string]chan ssh.NewChannel, 1),
Halt: halt,
}
go conn.HandleGlobalRequests(ctx, reqs)
go conn.HandleChannelOpens(ctx, chans)
go func() {
conn.Wait()
conn.Forwards.CloseAll()
}()
go conn.Forwards.HandleChannels(ctx, conn.HandleChannelOpen("forwarded-tcpip"), c)
go conn.Forwards.HandleChannels(ctx, conn.HandleChannelOpen("forwarded-streamlocal@openssh.com"), c)
// custom-inproc-stream is how reptile replication requests are sent,
// originating from the server and sent to the client.
if len(cfg.CustomChannelHandlers) > 0 && cfg.CustomChannelHandlers["custom-inproc-stream"] != nil {
var ca *ConnectionAlert
// or ???
// ca := &ConnectionAlert{
// PortOne: make(chan ssh.Channel),
// ShutDown: cfg.Halt.ReqStop.Chan,
// }
newChanChan := conn.HandleChannelOpen("custom-inproc-stream")
if newChanChan != nil {
go cfg.handleChannels(ctx, newChanChan, c, ca)
}
}
return conn
}