forked from pwaller/jump
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbastion.go
72 lines (61 loc) · 1.48 KB
/
bastion.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
package main
import (
"fmt"
"log"
"net"
"net/url"
"os"
"os/user"
"path/filepath"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"golang.org/x/crypto/ssh/knownhosts"
)
// BastionDialer returns a bastion
func BastionDialer(
bastionHost string,
) (func(network, addr string) (net.Conn, error), error) {
auths := []ssh.AuthMethod{}
auths = append(auths, agentAuth()...)
knownhostsPath := filepath.Join(os.Getenv("HOME"), ".ssh/known_hosts")
hostKeyCallback, err := knownhosts.New(knownhostsPath)
if err != nil {
log.Fatal(err)
}
config := &ssh.ClientConfig{
HostKeyCallback: hostKeyCallback,
}
config.SetDefaults()
u, err := url.Parse("//" + bastionHost)
if err != nil {
return nil, err
}
if u.User == nil || u.User.Username() == "" {
whoami, err := user.Current()
if err != nil {
return nil, err
}
u.User = url.User(whoami.Username)
}
_, _, err = net.SplitHostPort(u.Host)
if err != nil {
u.Host += ":22"
}
config.User = u.User.Username()
config.Auth = auths
log.Printf("Using bastion host: %v", u.Host)
conn, err := ssh.Dial("tcp", u.Host, config)
if err != nil {
return nil, fmt.Errorf("failed to connect to %q: %v", bastionHost, err)
}
return conn.Dial, nil
}
func agentAuth() (auths []ssh.AuthMethod) {
if sock := os.Getenv("SSH_AUTH_SOCK"); len(sock) > 0 {
if agconn, err := net.Dial("unix", sock); err == nil {
ag := agent.NewClient(agconn)
auths = append(auths, ssh.PublicKeysCallback(ag.Signers))
}
}
return auths
}