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 341 342 343 344 345 346 347 348 349 350 351 352 353 354
|
package dialers
import (
"errors"
"fmt"
"io/fs"
"net"
"os"
"os/user"
"path/filepath"
"runtime"
"strings"
"time"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"golang.org/x/crypto/ssh/knownhosts"
)
const (
// defaultSSHPort specifies the default ssh port.
defaultSSHPort = "22"
// defaultSSHTimeout specified the default ssh dial timeout.
defaultSSHTimeout = 20 * time.Second
)
// SSHAuthMethods maintains a priority list of allowed ssh auth methods.
type SSHAuthMethods struct {
authMethodGenerators []func(s *SSH) ssh.AuthMethod
signers []ssh.Signer
errors []error
}
// SSH implements connecting to a remote server's libvirt using ssh.
type SSH struct {
dialTimeout time.Duration
hostname, port string
username, password string
insecureIgnoreHostKey bool
acceptUnknownHostKey bool
keyFile string
knownHostsFile string
authMethods *SSHAuthMethods
remoteSocket string
}
// SSHOption is a function for setting ssh dialer options.
type SSHOption func(*SSH)
// UseSSHUsername uses the given username for the ssh connection.
func UseSSHUsername(username string) SSHOption {
return func(s *SSH) {
if username != "" {
s.username = username
}
}
}
// UseSSHPassword uses the given password for the ssh connection.
func UseSSHPassword(password string) SSHOption {
return func(s *SSH) {
if password != "" {
s.password = password
}
}
}
// UseSSHPort uses the given port for the ssh connection.
func UseSSHPort(port string) SSHOption {
return func(s *SSH) {
if port != "" {
s.port = port
}
}
}
// WithAcceptUnknownHostKey ignores the validity of the host certificate.
func WithAcceptUnknownHostKey() SSHOption {
return func(s *SSH) {
s.acceptUnknownHostKey = true
}
}
// WithInsecureIgnoreHostKey ignores the validity of the host certificate.
func WithInsecureIgnoreHostKey() SSHOption {
return func(s *SSH) {
s.insecureIgnoreHostKey = true
}
}
// UseKnownHostsFile uses a custom known_hosts file
func UseKnownHostsFile(filename string) SSHOption {
return func(s *SSH) {
s.knownHostsFile = filename
}
}
// UseKeyFile uses a custom key file
func UseKeyFile(filename string) SSHOption {
return func(s *SSH) {
s.keyFile = filename
}
}
// WithSSHAuthMethods uses the specified auth methods in priority order.
func WithSSHAuthMethods(methods *SSHAuthMethods) SSHOption {
return func(s *SSH) {
s.authMethods = methods
}
}
// WithRemoteSocket uses a custom remote socket
func WithRemoteSocket(socket string) SSHOption {
return func(s *SSH) {
s.remoteSocket = socket
}
}
// WithSystemSSHDefaults uses default values for the system ssh client,
// rather than the defaults that libvirtclient uses with libssh.
func WithSystemSSHDefaults(currentUser *user.User) SSHOption {
return UseKnownHostsFile(filepath.Join(currentUser.HomeDir,
".ssh",
"known_hosts"))
}
func defaultSSHKeyFile() string {
homeDir, err := os.UserHomeDir()
if err != nil {
return ""
}
for _, key := range []string{
"identity",
"id_dsa",
"id_ecdsa",
"id_ed25519",
"id_rsa",
} {
path := filepath.Join(homeDir, ".ssh", key)
if _, err := os.Stat(path); err == nil {
return path
}
}
return ""
}
func defaultSSHKnownHostsFile() string {
configDir, err := os.UserConfigDir()
if err == nil {
if runtime.GOOS != "windows" {
configDir = filepath.Join(configDir, "libvirt")
}
return filepath.Join(configDir, "known_hosts")
}
return ""
}
// PrivKey adds the Private Key auth method to the allowed list.
func (am *SSHAuthMethods) PrivKey() *SSHAuthMethods {
am.authMethodGenerators = append(am.authMethodGenerators,
func(s *SSH) ssh.AuthMethod {
key, err := os.ReadFile(s.keyFile)
if err != nil {
am.errors = append(am.errors,
fmt.Errorf("failed to read ssh key %v: %w", s.keyFile, err))
return nil
}
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
am.errors = append(am.errors,
fmt.Errorf("failed to parse ssh key %v: %w", s.keyFile, err))
return nil
}
// Only one callback of type "publickey" can be used, so the
// privkey and agent methods must share a callback.
first := len(am.signers) == 0
am.signers = append(am.signers, signer)
if first {
return ssh.PublicKeysCallback(am.getSigners)
}
return nil
})
return am
}
// Agent adds the ssh agent auth method to the allowed list.
func (am *SSHAuthMethods) Agent() *SSHAuthMethods {
am.authMethodGenerators = append(am.authMethodGenerators,
func(s *SSH) ssh.AuthMethod {
socket := os.Getenv("SSH_AUTH_SOCK")
if socket == "" {
return nil
}
conn, err := net.Dial("unix", socket)
if err != nil {
am.errors = append(am.errors,
fmt.Errorf("failed to connect to agent socket %v: %w", socket, err))
return nil
}
agentClient := agent.NewClient(conn)
if signers, err := agentClient.Signers(); err != nil {
am.errors = append(am.errors,
fmt.Errorf("failed to get signers from agent: %w", err))
} else {
// Only one callback of type "publickey" can be used, so the
// privkey and agent methods must share a callback.
first := len(am.signers) == 0
am.signers = append(am.signers, signers...)
if first && len(am.signers) > 0 {
return ssh.PublicKeysCallback(am.getSigners)
}
}
return nil
})
return am
}
// Password adds the password auth method to the allowed list.
func (am *SSHAuthMethods) Password() *SSHAuthMethods {
am.authMethodGenerators = append(am.authMethodGenerators,
func(s *SSH) ssh.AuthMethod {
if s.password == "" {
am.errors = append(am.errors,
errors.New("no ssh password set"))
return nil
}
return ssh.Password(s.password)
})
return am
}
// KeyboardInteractive adds the keyboard-interactive auth method to the
// allowed list (currently unimplemented).
func (am *SSHAuthMethods) KeyboardInteractive() *SSHAuthMethods {
// Not implemented
return am
}
func (am *SSHAuthMethods) getSigners() ([]ssh.Signer, error) {
return am.signers, nil
}
func (am *SSHAuthMethods) authMethods(s *SSH) []ssh.AuthMethod {
am.signers = nil
am.errors = nil
methods := []ssh.AuthMethod{}
for _, g := range am.authMethodGenerators {
if m := g(s); m != nil {
methods = append(methods, m)
}
}
return methods
}
// NewSSH returns an ssh dialer for connecting to libvirt running on another
// server.
func NewSSH(hostAddr string, opts ...SSHOption) *SSH {
defaultUsername := ""
if currentUser, err := user.Current(); err == nil {
defaultUsername = currentUser.Username
}
s := &SSH{
dialTimeout: defaultSSHTimeout,
username: defaultUsername,
hostname: hostAddr,
port: defaultSSHPort,
remoteSocket: defaultSocket,
knownHostsFile: defaultSSHKnownHostsFile(),
keyFile: defaultSSHKeyFile(),
authMethods: (&SSHAuthMethods{}).Agent().PrivKey().Password().KeyboardInteractive(),
}
for _, opt := range opts {
opt(s)
}
return s
}
func appendKnownHost(knownHostsFile string, host string, key ssh.PublicKey) {
if err := os.MkdirAll(filepath.Dir(knownHostsFile), 0700); err != nil {
return
}
f, err := os.OpenFile(knownHostsFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return
}
defer f.Close()
fmt.Fprintf(f, "%s\n", knownhosts.Line([]string{host}, key))
}
func (s *SSH) checkHostKey(host string, remote net.Addr, key ssh.PublicKey) error {
checkKnown, err := knownhosts.New(s.knownHostsFile)
if err != nil {
if errors.Is(err, fs.ErrNotExist) && s.acceptUnknownHostKey {
appendKnownHost(s.knownHostsFile, host, key)
return nil
}
return err
}
result := checkKnown(host, remote, key)
if keyErr, ok := result.(*knownhosts.KeyError); ok {
if len(keyErr.Want) == 0 && s.acceptUnknownHostKey {
appendKnownHost(s.knownHostsFile, host, key)
return nil
}
}
return result
}
func (s *SSH) config() (*ssh.ClientConfig, error) {
hostKeyCallback := s.checkHostKey
if s.insecureIgnoreHostKey {
hostKeyCallback = ssh.InsecureIgnoreHostKey() //nolint:gosec
}
return &ssh.ClientConfig{
User: s.username,
HostKeyCallback: hostKeyCallback,
Auth: s.authMethods.authMethods(s),
Timeout: s.dialTimeout,
}, nil
}
// Dial connects to libvirt running on another server over ssh.
func (s *SSH) Dial() (net.Conn, error) {
conf, err := s.config()
if err != nil {
return nil, err
}
sshClient, err := ssh.Dial("tcp", net.JoinHostPort(s.hostname, s.port),
conf)
if err != nil {
if strings.HasPrefix(err.Error(), "ssh: handshake failed: ssh: unable to authenticate") {
err = errors.Join(append([]error{err}, s.authMethods.errors...)...)
}
return nil, err
}
c, err := sshClient.Dial("unix", s.remoteSocket)
if err != nil {
return nil, fmt.Errorf("failed to connect to remote libvirt socket %s: %w", s.remoteSocket, err)
}
return c, nil
}
|