-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
187 lines (161 loc) · 4.29 KB
/
connection.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
package rcom
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/user"
"path/filepath"
"strings"
"golang.org/x/crypto/ssh"
kh "golang.org/x/crypto/ssh/knownhosts"
)
type Connection struct {
*ssh.Client
config *Config
sessions []*ssh.Session
}
func (conn *Connection) Run(exec string, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
session, err := conn.Start(exec, stdin, stdout, stderr)
if err == nil {
err = session.Wait()
}
return err
}
func (conn *Connection) Start(exec string, stdin io.Reader, stdout io.Writer, stderr io.Writer) (*ssh.Session, error) {
session, err := conn.NewSession()
if err != nil {
Logger.Printf("Failed to create ssh session: %v", err)
return nil, err
}
session.Stdin = stdin
session.Stdout = stdout
session.Stderr = stderr
err = session.Start(exec)
if err != nil {
Logger.Printf("Failed to start remote command: %q: %v", exec, err)
}
return session, err
}
func (conn *Connection) AttachPTY(localDev string, exec string) error {
p, err := newPort(localDev)
if err != nil {
Logger.Printf("Failed to attach to port %s: %v", localDev, err)
p.ClosePTY()
return err
}
session, err := conn.Start(exec, p, p, os.Stderr)
if err == nil {
conn.sessions = append(conn.sessions, session)
} else {
p.ClosePTY()
}
return err
}
func (conn *Connection) Close() error {
for _, session := range conn.sessions {
if p, ok := session.Stdin.(*port); ok {
p.ClosePTY()
}
session.Signal(ssh.SIGINT)
session.Close()
}
conn.sessions = nil
return nil
}
func (conn *Connection) hostKeyCallback(hostname string, remote net.Addr, key ssh.PublicKey) error {
fields := strings.Split(hostname, ":")
if fields[1] == "22" {
hostname = fields[0]
} else {
hostname = fmt.Sprintf("[%s]:%s", fields[0], fields[1])
}
remoteAddr := remote.String()
fields = strings.Split(remoteAddr, ":")
if fields[1] == "22" {
remoteAddr = fields[0]
} else {
remoteAddr = fmt.Sprintf("[%s]:%s", fields[0], fields[1])
}
if _, err := os.Stat(conn.config.knownHosts); err != nil {
if os.IsNotExist(err) {
if conn.config.acceptNew {
if err := os.MkdirAll(filepath.Dir(conn.config.knownHosts), 0700); err != nil {
return err
}
line := kh.Line([]string{hostname}, key)
return ioutil.WriteFile(conn.config.knownHosts, append([]byte(line), []byte("\n")...), 0600)
} else {
return fmt.Errorf("Could not verify %s: known_hosts file not found", hostname)
}
} else {
return err
}
}
file, err := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts"))
if err != nil {
return err
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
_, hosts, pk, _, _, err := ssh.ParseKnownHosts(scanner.Bytes())
if err != nil {
return err
}
for _, host := range hosts {
if host == hostname || host == remoteAddr {
err = ssh.FixedHostKey(pk)(hostname, remote, key)
return err
}
}
}
if conn.config.acceptNew {
line := kh.Line([]string{hostname}, key)
f, err := os.OpenFile(conn.config.knownHosts, os.O_APPEND|os.O_WRONLY, 0600)
if err == nil {
_, err = f.WriteString(line + "\n")
}
f.Close()
return err
}
return fmt.Errorf("Hostkey verification failed, no entry in known_hosts")
}
func Connect(hostname string, options ...ConfigOption) (*Connection, error) {
config := &Config{
port: 22,
}
for _, option := range options {
option(config)
}
if config.identityAuth == nil || config.clientConfig.User == "" || config.knownHosts == "" {
u, err := user.Current()
if err != nil {
return nil, err
}
if config.identityAuth == nil {
err := DefaultIdentityFile(u.HomeDir)(config)
if err != nil {
return nil, err
}
}
if config.identityAuth != nil {
config.clientConfig.Auth = append(config.clientConfig.Auth, config.identityAuth)
}
if config.passwordAuth != nil {
config.clientConfig.Auth = append(config.clientConfig.Auth, config.passwordAuth)
}
if config.clientConfig.User == "" {
config.clientConfig.User = u.Username
}
if config.knownHosts == "" {
config.knownHosts = filepath.Join(u.HomeDir, ".ssh", "known_hosts")
}
}
conn := &Connection{config: config}
config.clientConfig.HostKeyCallback = conn.hostKeyCallback
var err error
conn.Client, err = ssh.Dial("tcp", fmt.Sprintf("%s:%d", hostname, config.port), &config.clientConfig)
return conn, err
}