-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
native.go
226 lines (188 loc) · 6.11 KB
/
native.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
//go:build !excludenative
package ssh
import (
"errors"
"fmt"
"net"
"os"
"github.com/golang/glog"
"github.com/spf13/pflag"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"golang.org/x/term"
"k8s.io/client-go/tools/clientcmd"
"kubevirt.io/client-go/kubecli"
)
const (
wrapLocalSSHDefault = false
)
func additionalUsage() string {
return fmt.Sprintf(`
# Connect to 'testvmi' using the local ssh binary found in $PATH:
{{ProgramName}} ssh --%s=true jdoe@testvmi`,
wrapLocalSSHFlag,
)
}
func addAdditionalCommandlineArgs(flagset *pflag.FlagSet, opts *SSHOptions) {
flagset.StringArrayVarP(&opts.AdditionalSSHLocalOptions, additionalOpts, additionalOptsShort, opts.AdditionalSSHLocalOptions,
fmt.Sprintf(`--%s="-o StrictHostKeyChecking=no" : Additional options to be passed to the local ssh. This is applied only if local-ssh=true`, additionalOpts))
flagset.BoolVar(&opts.WrapLocalSSH, wrapLocalSSHFlag, opts.WrapLocalSSH,
fmt.Sprintf("--%s=true: Set this to true to use the SSH/SCP client available on your system by using this command as ProxyCommand; If set to false, this will establish a SSH/SCP connection with limited capabilities provided by this client", wrapLocalSSHFlag))
}
type NativeSSHConnection struct {
ClientConfig clientcmd.ClientConfig
Options SSHOptions
}
func (o *SSH) nativeSSH(kind, namespace, name string) error {
conn := NativeSSHConnection{
ClientConfig: o.clientConfig,
Options: o.options,
}
client, err := conn.PrepareSSHClient(kind, namespace, name)
if err != nil {
return err
}
return conn.StartSession(client, o.command)
}
func (o *NativeSSHConnection) PrepareSSHClient(kind, namespace, name string) (*ssh.Client, error) {
streamer, err := o.prepareSSHTunnel(kind, namespace, name)
if err != nil {
return nil, err
}
conn := streamer.AsConn()
addr := fmt.Sprintf("%s/%s.%s:%d", kind, name, namespace, o.Options.SSHPort)
authMethods := o.getAuthMethods(kind, namespace, name)
hostKeyCallback := ssh.InsecureIgnoreHostKey()
if len(o.Options.KnownHostsFilePath) > 0 {
hostKeyCallback, err = InteractiveHostKeyCallback(o.Options.KnownHostsFilePath)
if err != nil {
return nil, err
}
} else {
fmt.Println("WARNING: skipping hostkey check, provide --known-hosts to fix this")
}
sshConn, chans, reqs, err := ssh.NewClientConn(conn,
addr,
&ssh.ClientConfig{
HostKeyCallback: hostKeyCallback,
Auth: authMethods,
User: o.Options.SSHUsername,
},
)
if err != nil {
return nil, err
}
return ssh.NewClient(sshConn, chans, reqs), nil
}
func (o *NativeSSHConnection) getAuthMethods(kind, namespace, name string) []ssh.AuthMethod {
var methods []ssh.AuthMethod
methods = o.trySSHAgent(methods)
methods = o.tryPrivateKey(methods)
methods = append(methods, ssh.PasswordCallback(func() (secret string, err error) {
password, err := readPassword(fmt.Sprintf("%s@%s/%s.%s's password: ", o.Options.SSHUsername, kind, name, namespace))
fmt.Println()
return string(password), err
}))
return methods
}
func (o *NativeSSHConnection) trySSHAgent(methods []ssh.AuthMethod) []ssh.AuthMethod {
socket := os.Getenv("SSH_AUTH_SOCK")
if len(socket) < 1 {
return methods
}
conn, err := net.Dial("unix", socket)
if err != nil {
glog.Error("no connection to ssh agent, skipping agent authentication:", err)
return methods
}
agentClient := agent.NewClient(conn)
return append(methods, ssh.PublicKeysCallback(agentClient.Signers))
}
func (o *NativeSSHConnection) tryPrivateKey(methods []ssh.AuthMethod) []ssh.AuthMethod {
// If the identity file at the default does not exist but was
// not explicitly provided, don't add the authentication mechanism.
if !o.Options.IdentityFilePathProvided {
if _, err := os.Stat(o.Options.IdentityFilePath); errors.Is(err, os.ErrNotExist) {
glog.V(3).Infof("No ssh key at the default location %q found, skipping RSA authentication.", o.Options.IdentityFilePath)
return methods
}
}
callback := ssh.PublicKeysCallback(func() (signers []ssh.Signer, err error) {
key, err := os.ReadFile(o.Options.IdentityFilePath)
if err != nil {
return nil, err
}
signer, err := ssh.ParsePrivateKey(key)
if _, isPassErr := err.(*ssh.PassphraseMissingError); isPassErr {
signer, err = o.parsePrivateKeyWithPassphrase(key)
}
if err != nil {
return nil, err
}
return []ssh.Signer{signer}, nil
})
return append(methods, callback)
}
func (o *NativeSSHConnection) parsePrivateKeyWithPassphrase(key []byte) (ssh.Signer, error) {
password, err := readPassword(fmt.Sprintf("Key %s requires a password: ", o.Options.IdentityFilePath))
fmt.Println()
if err != nil {
return nil, err
}
return ssh.ParsePrivateKeyWithPassphrase(key, password)
}
func readPassword(reason string) ([]byte, error) {
fmt.Print(reason)
return term.ReadPassword(int(os.Stdin.Fd()))
}
func (o *NativeSSHConnection) StartSession(client *ssh.Client, command string) error {
session, err := client.NewSession()
if err != nil {
return err
}
defer session.Close()
session.Stdin = os.Stdin
session.Stderr = os.Stderr
session.Stdout = os.Stdout
if command != "" {
if err := session.Run(command); err != nil {
return err
}
return nil
}
restore, err := setupTerminal()
if err != nil {
return err
}
defer restore()
if err := requestPty(session); err != nil {
return err
}
if err := session.Shell(); err != nil {
return err
}
err = session.Wait()
if _, exited := err.(*ssh.ExitError); !exited {
return err
}
return nil
}
func (o *NativeSSHConnection) prepareSSHTunnel(kind, namespace, name string) (kubecli.StreamInterface, error) {
virtCli, err := kubecli.GetKubevirtClientFromClientConfig(o.ClientConfig)
if err != nil {
return nil, err
}
var stream kubecli.StreamInterface
if kind == "vmi" {
stream, err = virtCli.VirtualMachineInstance(namespace).PortForward(name, o.Options.SSHPort, "tcp")
if err != nil {
return nil, fmt.Errorf("can't access VMI %s: %w", name, err)
}
} else if kind == "vm" {
stream, err = virtCli.VirtualMachine(namespace).PortForward(name, o.Options.SSHPort, "tcp")
if err != nil {
return nil, fmt.Errorf("can't access VM %s: %w", name, err)
}
}
return stream, nil
}