-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhost.go
More file actions
340 lines (303 loc) · 7.65 KB
/
host.go
File metadata and controls
340 lines (303 loc) · 7.65 KB
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
package ssh_client
import (
"errors"
"fmt"
"net"
"os"
"strings"
"github.com/skeema/knownhosts"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
type sshSettingsGetter interface {
Get(alias, key string) string
GetAll(alias, key string) []string
}
type Host struct {
Name string
Hostname string
Port string
User string
cfg sshSettingsGetter
*ssh.ClientConfig
}
func parseSshURI(uri string) (user, host, port string) {
// TODO: do we want regex here to validate the exact format ?
userHostPort := strings.TrimPrefix(uri, "ssh://")
atIdx := strings.IndexByte(userHostPort, '@')
if atIdx != -1 {
user = userHostPort[:atIdx]
}
hostPort := userHostPort[atIdx+1:]
colonIdx := strings.IndexByte(hostPort, ':')
if colonIdx != -1 {
port = hostPort[colonIdx+1:]
host = hostPort[:colonIdx]
} else {
host = hostPort
}
return
}
// ParseSshURI parse either [user@]host[:port] or an ssh URI ie ssh://[user@]host[:port].
func ParseSshURI(uri string) *Host {
u, h, p := parseSshURI(uri)
return &Host{
Name: h,
Hostname: h,
Port: p,
User: u,
}
}
func New(uri string, cfg sshSettingsGetter) (*Host, error) {
h := ParseSshURI(uri)
err := h.configure(cfg, currentUsername)
if err != nil {
return nil, err
}
return h, nil
}
func (h *Host) configure(cfg sshSettingsGetter, currentUsername func() string) error {
h.cfg = cfg
if h.Port == "" {
h.Port = cfg.Get(h.Name, "Port")
}
// Default to Name
if h.Hostname == "" {
h.Hostname = h.Name
}
if h.User == "" {
h.User = cfg.Get(h.Name, "User")
}
if h.User == "" {
h.User = currentUsername()
}
cfgHostname := h.ExpandTokens(cfg.Get(h.Name, "Hostname"))
if cfgHostname != "" {
h.Hostname = cfgHostname
}
return nil
}
func (h *Host) Configure(cfg sshSettingsGetter) error {
return h.configure(cfg, currentUsername)
}
func (h *Host) Addr() string {
return h.Hostname + ":" + h.Port
}
func (h *Host) ConfigGet(key string) string {
return h.cfg.Get(h.Name, key)
}
func (h *Host) ConfigGetAll(key string) []string {
return h.cfg.GetAll(h.Name, key)
}
func (h *Host) KnownHosts() []string {
u := h.ConfigGet("UserKnownHostsFile")
f := strings.Split(u, " ")
for i := range f {
f[i] = h.ExpandTokens(ExpandHome(f[i]))
}
g := h.ConfigGet("GlobalKnownHostsFile")
f = append(f, strings.Split(g, " ")...)
var knownHostFiles []string
for i := range f {
info, err := os.Stat(f[i])
if err != nil {
continue
}
if info.Mode().IsRegular() {
knownHostFiles = append(knownHostFiles, f[i])
}
}
return knownHostFiles
}
func (h *Host) AgentSockName() string {
n := h.ConfigGet("IdentityAgent")
// ssh_config does not handle IdentityAgent and its SSH_AUTH_SOCK default.
if n == "" {
n = "SSH_AUTH_SOCK"
}
n = ExpandHome(n)
n = h.ExpandTokens(n)
n = os.ExpandEnv(n)
if n == "SSH_AUTH_SOCK" {
n = os.Getenv("SSH_AUTH_SOCK")
}
return n
}
var ErrAgentDisabled = errors.New("SSH Agent Disabled")
// TODO once or cache
func (h *Host) Agent() (agent.ExtendedAgent, error) {
socket := h.AgentSockName()
if strings.ToLower(socket) == "none" {
return nil, ErrAgentDisabled
}
agentConn, err := net.Dial("unix", socket)
if err != nil {
return nil, fmt.Errorf("Failed to open Agent (on %s): %w", socket, err)
}
agentClient := agent.NewClient(agentConn)
return agentClient, nil
}
func (h *Host) IdentitiesOnly() bool {
switch strings.ToLower(h.ConfigGet("IdentitiesOnly")) {
case "true", "yes":
return true
case "false", "no":
return false
default:
// TODO: fail or at least log
return false
}
}
func (h *Host) IdentityPublicKeys() []ssh.PublicKey {
identityFiles := h.ConfigGetAll("IdentityFile")
var pubKeys []ssh.PublicKey
for _, file := range identityFiles {
fname := ExpandHome(file)
fname = h.ExpandTokens(fname)
fname += ".pub"
content, err := os.ReadFile(fname)
if err != nil {
// TODO slog and only when not from DefaultValues
// fmt.Printf("could not read %s: %v\n", fname, err)
continue
}
k, _, _, _, err := ssh.ParseAuthorizedKey(content)
if err != nil {
// TODO slog
fmt.Printf("could not parse %s: %v\n%s\n", fname, err, string(content))
continue
}
pubKeys = append(pubKeys, k)
}
return pubKeys
}
func (h *Host) GetSignersCallback() (func() ([]ssh.Signer, error), error) {
agentClient, err := h.Agent()
if err != nil {
return nil, fmt.Errorf("SSH Agent Required: %w", err)
}
if !h.IdentitiesOnly() {
// Ignore identities from config, loading privateKeys is not implemented, assume the required ones are loaded.
return agentClient.Signers, nil
}
// IdentitiesOnly=yes so we need to filter agent Signers according to identities in config.
hasKeys := make(map[string]bool)
for _, k := range h.IdentityPublicKeys() {
hash := string(k.Marshal())
hasKeys[hash] = true
}
cb := func() ([]ssh.Signer, error) {
agentSigners, err := agentClient.Signers()
if err != nil {
return nil, err
}
var signers []ssh.Signer
for i := range agentSigners {
hash := string(agentSigners[i].PublicKey().Marshal())
if hasKeys[hash] {
// fmt.Println("found matching pubkey in agent")
signers = append(signers, agentSigners[i])
}
}
return signers, nil
}
return cb, nil
}
func (h *Host) GetSigners() ([]ssh.Signer, error) {
cb, err := h.GetSignersCallback()
if err != nil {
return nil, err
}
return cb()
}
// TODO: add options to customize config
// TODO: make thread safe ?
func (h *Host) GetClientConfig() (*ssh.ClientConfig, error) {
if h.ClientConfig != nil {
return h.ClientConfig, nil
}
kh, err := knownhosts.NewDB(h.KnownHosts()...)
if err != nil {
return nil, fmt.Errorf("could not parse knownhosts: %w", err)
}
getSigners, err := h.GetSignersCallback()
if err != nil {
return nil, fmt.Errorf("could not create key signers callback: %w", err)
}
cfg := &ssh.ClientConfig{
User: h.User,
Auth: []ssh.AuthMethod{
ssh.PublicKeysCallback(getSigners),
},
HostKeyCallback: kh.HostKeyCallback(),
HostKeyAlgorithms: kh.HostKeyAlgorithms(h.Addr()),
}
h.ClientConfig = cfg
return cfg, nil
}
func (h *Host) ProxyJump() []string {
pJump := h.ConfigGet("ProxyJump")
if pJump == "" {
return nil
}
p := strings.Split(pJump, ",")
for i := range p {
p[i] = h.ExpandTokens(p[i])
}
return p
}
func (h *Host) ProxyJumpHosts() ([]*Host, error) {
p := h.ProxyJump()
ph := make([]*Host, len(p))
for i := range p {
nh, err := New(p[i], h.cfg)
if err != nil {
return nil, fmt.Errorf("Preparing ProxyJump[%d]: %w", i, err)
}
ph[i] = nh
}
return ph, nil
}
func (h *Host) Dial(network string) (*ssh.Client, error) {
pCmd := h.ConfigGet("ProxyCommand")
if pCmd != "" {
return nil, errors.New("ProxyCommand is not supported use ProxyJump instead where possible")
}
config, err := h.GetClientConfig()
if err != nil {
return nil, err
}
proxyJumpHosts, err := h.ProxyJumpHosts()
if err != nil {
return nil, err
}
// Full lust of hosts to connect
hosts := append(proxyJumpHosts, h)
// initial connection
conn, err := net.DialTimeout(network, hosts[0].Addr(), config.Timeout)
if err != nil {
return nil, err
}
for i, proxyHost := range proxyJumpHosts {
client, err := proxyHost.NewClient(conn)
if err != nil {
return nil, fmt.Errorf("ProxyJump[%d] '%s' Client: %w", i, proxyHost.Addr(), err)
}
conn, err = client.Dial(network, hosts[i+1].Addr())
if err != nil {
return nil, fmt.Errorf("ProxyJump[%d] '%s' Dial: %w", i, hosts[i+1].Addr(), err)
}
}
return h.NewClient(conn)
}
func (h *Host) NewClient(conn net.Conn) (*ssh.Client, error) {
config, err := h.GetClientConfig()
if err != nil {
return nil, err
}
c, chans, reqs, err := ssh.NewClientConn(conn, h.Addr(), config)
if err != nil {
return nil, err
}
return ssh.NewClient(c, chans, reqs), nil
}