| 1 | |
| 2 | |
| 3 | |
| 4 | package sshutil |
| 5 | |
| 6 | import ( |
| 7 | "bytes" |
| 8 | "context" |
| 9 | "encoding/base64" |
| 10 | "encoding/binary" |
| 11 | "errors" |
| 12 | "fmt" |
| 13 | "io/fs" |
| 14 | "net" |
| 15 | "os" |
| 16 | "os/exec" |
| 17 | "path/filepath" |
| 18 | "regexp" |
| 19 | "runtime" |
| 20 | "slices" |
| 21 | "strings" |
| 22 | "sync" |
| 23 | "time" |
| 24 | |
| 25 | "github.com/coreos/go-semver/semver" |
| 26 | "github.com/mattn/go-shellwords" |
| 27 | "github.com/sirupsen/logrus" |
| 28 | "golang.org/x/sys/cpu" |
| 29 | |
| 30 | "github.com/lima-vm/lima/v2/pkg/fsutil" |
| 31 | "github.com/lima-vm/lima/v2/pkg/limatype/dirnames" |
| 32 | "github.com/lima-vm/lima/v2/pkg/limatype/filenames" |
| 33 | "github.com/lima-vm/lima/v2/pkg/lockutil" |
| 34 | "github.com/lima-vm/lima/v2/pkg/osutil" |
| 35 | ) |
| 36 | |
| 37 | |
| 38 | |
| 39 | const EnvShellSSH = "SSH" |
| 40 | |
| 41 | type SSHExe struct { |
| 42 | Exe string |
| 43 | Args []string |
| 44 | } |
| 45 | |
| 46 | func NewSSHExe() (SSHExe, error) { |
| 47 | var sshExe SSHExe |
| 48 | |
| 49 | if sshShell := os.Getenv(EnvShellSSH); sshShell != "" { |
| 50 | sshShellFields, err := shellwords.Parse(sshShell) |
| 51 | switch { |
| 52 | case err != nil: |
| 53 | logrus.WithError(err).Warnf("Failed to split %s variable into shell tokens. "+ |
| 54 | "Falling back to 'ssh' command", EnvShellSSH) |
| 55 | case len(sshShellFields) > 0: |
| 56 | sshExe.Exe = sshShellFields[0] |
| 57 | if len(sshShellFields) > 1 { |
| 58 | sshExe.Args = sshShellFields[1:] |
| 59 | } |
| 60 | return sshExe, nil |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | if runtime.GOOS == "windows" { |
| 65 | if exe := pickCompleteSSHOnWindows(); exe != "" { |
| 66 | sshExe.Exe = exe |
| 67 | return sshExe, nil |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | executable, err := exec.LookPath("ssh") |
| 72 | if err != nil { |
| 73 | return SSHExe{}, err |
| 74 | } |
| 75 | sshExe.Exe = executable |
| 76 | |
| 77 | return sshExe, nil |
| 78 | } |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | |
| 84 | |
| 85 | |
| 86 | func pickCompleteSSHOnWindows() string { |
| 87 | for _, dir := range filepath.SplitList(os.Getenv("PATH")) { |
| 88 | if dir == "" { |
| 89 | continue |
| 90 | } |
| 91 | sshPath := filepath.Join(dir, "ssh.exe") |
| 92 | if _, err := os.Stat(sshPath); err != nil { |
| 93 | continue |
| 94 | } |
| 95 | if missing := missingSiblings(dir, "scp.exe", "ssh-keygen.exe"); len(missing) > 0 { |
| 96 | logrus.Debugf("skipping ssh at %#q: missing %v in same directory (likely MinGit or another partial install)", sshPath, missing) |
| 97 | continue |
| 98 | } |
| 99 | return sshPath |
| 100 | } |
| 101 | nativeDir := filepath.Join(systemRoot(), "System32", "OpenSSH") |
| 102 | nativeSSH := filepath.Join(nativeDir, "ssh.exe") |
| 103 | if _, err := os.Stat(nativeSSH); err == nil { |
| 104 | if missing := missingSiblings(nativeDir, "scp.exe", "ssh-keygen.exe"); len(missing) > 0 { |
| 105 | logrus.Debugf("skipping native ssh at %#q: missing %v in same directory", nativeSSH, missing) |
| 106 | return "" |
| 107 | } |
| 108 | return nativeSSH |
| 109 | } |
| 110 | |
| 111 | return "" |
| 112 | } |
| 113 | |
| 114 | |
| 115 | |
| 116 | func systemRoot() string { |
| 117 | if r := os.Getenv("SystemRoot"); r != "" { |
| 118 | return r |
| 119 | } |
| 120 | return `C:\Windows` |
| 121 | } |
| 122 | |
| 123 | |
| 124 | |
| 125 | func missingSiblings(dir string, siblings ...string) []string { |
| 126 | var missing []string |
| 127 | for _, s := range siblings { |
| 128 | if _, err := os.Stat(filepath.Join(dir, s)); err != nil { |
| 129 | missing = append(missing, s) |
| 130 | } |
| 131 | } |
| 132 | return missing |
| 133 | } |
| 134 | |
| 135 | var ( |
| 136 | |
| 137 | |
| 138 | cygwinDetectCache = map[string]string{} |
| 139 | cygwinDetectCacheRW sync.RWMutex |
| 140 | ) |
| 141 | |
| 142 | |
| 143 | |
| 144 | |
| 145 | func resolvedSSHPath(sshExe SSHExe) (string, bool) { |
| 146 | if sshExe.Exe == "" { |
| 147 | return "", false |
| 148 | } |
| 149 | path := sshExe.Exe |
| 150 | if !filepath.IsAbs(path) { |
| 151 | resolved, err := exec.LookPath(path) |
| 152 | if err != nil { |
| 153 | logrus.WithError(err).Debugf("cannot resolve ssh at %#q via PATH", path) |
| 154 | return "", false |
| 155 | } |
| 156 | path = resolved |
| 157 | } |
| 158 | if resolved, err := filepath.EvalSymlinks(path); err == nil { |
| 159 | path = resolved |
| 160 | } |
| 161 | return path, true |
| 162 | } |
| 163 | |
| 164 | |
| 165 | |
| 166 | |
| 167 | |
| 168 | func companionForSSH(sshExe SSHExe, tool string) string { |
| 169 | if runtime.GOOS != "windows" { |
| 170 | return tool |
| 171 | } |
| 172 | path, ok := resolvedSSHPath(sshExe) |
| 173 | if !ok { |
| 174 | return tool |
| 175 | } |
| 176 | companion := filepath.Join(filepath.Dir(path), tool+".exe") |
| 177 | if _, err := os.Stat(companion); err != nil { |
| 178 | logrus.Debugf("no %#q beside ssh at %#q; resolving %#q from PATH", companion, path, tool) |
| 179 | return tool |
| 180 | } |
| 181 | return companion |
| 182 | } |
| 183 | |
| 184 | |
| 185 | |
| 186 | |
| 187 | |
| 188 | |
| 189 | func cygpathForSSH(sshExe SSHExe) (string, bool) { |
| 190 | if runtime.GOOS != "windows" { |
| 191 | return "", false |
| 192 | } |
| 193 | path, ok := resolvedSSHPath(sshExe) |
| 194 | if !ok { |
| 195 | return "", false |
| 196 | } |
| 197 | cygwinDetectCacheRW.RLock() |
| 198 | cached, ok := cygwinDetectCache[path] |
| 199 | cygwinDetectCacheRW.RUnlock() |
| 200 | if ok { |
| 201 | return cached, cached != "" |
| 202 | } |
| 203 | cygpathExe := filepath.Join(filepath.Dir(path), "cygpath.exe") |
| 204 | if _, err := os.Stat(cygpathExe); err != nil { |
| 205 | logrus.Debugf("ssh at %#q detected as native Windows OpenSSH (no cygpath.exe alongside)", path) |
| 206 | cygpathExe = "" |
| 207 | } else { |
| 208 | logrus.Debugf("ssh at %#q detected as Cygwin-based (found %#q alongside)", path, cygpathExe) |
| 209 | } |
| 210 | cygwinDetectCacheRW.Lock() |
| 211 | cygwinDetectCache[path] = cygpathExe |
| 212 | cygwinDetectCacheRW.Unlock() |
| 213 | |
| 214 | return cygpathExe, cygpathExe != "" |
| 215 | } |
| 216 | |
| 217 | |
| 218 | |
| 219 | |
| 220 | |
| 221 | |
| 222 | func PathForSSH(ctx context.Context, sshExe SSHExe, orig string) (string, error) { |
| 223 | if runtime.GOOS != "windows" { |
| 224 | return orig, nil |
| 225 | } |
| 226 | if cygpathExe, ok := cygpathForSSH(sshExe); ok { |
| 227 | return fsutil.WindowsSubsystemPathWithCygpath(ctx, cygpathExe, orig) |
| 228 | } |
| 229 | return filepath.ToSlash(orig), nil |
| 230 | } |
| 231 | |
| 232 | |
| 233 | |
| 234 | |
| 235 | |
| 236 | |
| 237 | |
| 238 | func SftpServerForSSH(ctx context.Context, sshExe SSHExe) string { |
| 239 | if runtime.GOOS != "windows" || sshExe.Exe == "" { |
| 240 | return "" |
| 241 | } |
| 242 | if cygpathExe, ok := cygpathForSSH(sshExe); ok { |
| 243 | out, err := exec.CommandContext(ctx, cygpathExe, "-w", "/usr/lib/ssh/sftp-server").Output() |
| 244 | if err != nil { |
| 245 | return "" |
| 246 | } |
| 247 | |
| 248 | |
| 249 | |
| 250 | |
| 251 | candidate := strings.TrimSpace(string(out)) |
| 252 | sftpServer, err := exec.LookPath(candidate) |
| 253 | if err != nil { |
| 254 | logrus.WithError(err).Debugf("cannot use the sftp-server at %#q that cygpath resolved", candidate) |
| 255 | return "" |
| 256 | } |
| 257 | return sftpServer |
| 258 | } |
| 259 | path, ok := resolvedSSHPath(sshExe) |
| 260 | if !ok { |
| 261 | return "" |
| 262 | } |
| 263 | sftpServer, err := exec.LookPath(filepath.Join(filepath.Dir(path), "sftp-server.exe")) |
| 264 | if err != nil { |
| 265 | return "" |
| 266 | } |
| 267 | return sftpServer |
| 268 | } |
| 269 | |
| 270 | type PubKey struct { |
| 271 | Filename string |
| 272 | Content string |
| 273 | } |
| 274 | |
| 275 | func readPublicKey(f string) (PubKey, error) { |
| 276 | entry := PubKey{ |
| 277 | Filename: f, |
| 278 | } |
| 279 | content, err := os.ReadFile(f) |
| 280 | if err == nil { |
| 281 | entry.Content = strings.TrimSpace(string(content)) |
| 282 | } else { |
| 283 | err = fmt.Errorf("failed to read ssh public key %#q: %w", f, err) |
| 284 | } |
| 285 | return entry, err |
| 286 | } |
| 287 | |
| 288 | |
| 289 | |
| 290 | |
| 291 | |
| 292 | |
| 293 | func DefaultPubKeys(ctx context.Context, loadDotSSH bool) ([]PubKey, error) { |
| 294 | |
| 295 | configDir, err := dirnames.LimaConfigDir() |
| 296 | if err != nil { |
| 297 | return nil, err |
| 298 | } |
| 299 | _, err = os.Stat(filepath.Join(configDir, filenames.UserPrivateKey)) |
| 300 | if err != nil { |
| 301 | if !errors.Is(err, os.ErrNotExist) { |
| 302 | return nil, err |
| 303 | } |
| 304 | if err := os.MkdirAll(configDir, 0o700); err != nil { |
| 305 | return nil, fmt.Errorf("could not create %#q directory: %w", configDir, err) |
| 306 | } |
| 307 | if err := lockutil.WithDirLock(configDir, func() error { |
| 308 | |
| 309 | privPath := filepath.Join(configDir, filenames.UserPrivateKey) |
| 310 | keygenExe := "ssh-keygen" |
| 311 | if runtime.GOOS == "windows" { |
| 312 | sshExe, sshErr := NewSSHExe() |
| 313 | if sshErr != nil { |
| 314 | return sshErr |
| 315 | } |
| 316 | keygenExe = companionForSSH(sshExe, "ssh-keygen") |
| 317 | privPath, err = PathForSSH(ctx, sshExe, privPath) |
| 318 | if err != nil { |
| 319 | return err |
| 320 | } |
| 321 | } |
| 322 | keygenCmd := exec.CommandContext(ctx, keygenExe, "-t", "ed25519", "-q", "-N", "", |
| 323 | "-C", "lima", "-f", privPath) |
| 324 | logrus.Debugf("executing %v", keygenCmd.Args) |
| 325 | if out, err := keygenCmd.CombinedOutput(); err != nil { |
| 326 | return fmt.Errorf("failed to run %v: %#q: %w", keygenCmd.Args, string(out), err) |
| 327 | } |
| 328 | return nil |
| 329 | }); err != nil { |
| 330 | return nil, err |
| 331 | } |
| 332 | } |
| 333 | entry, err := readPublicKey(filepath.Join(configDir, filenames.UserPublicKey)) |
| 334 | if err != nil { |
| 335 | return nil, err |
| 336 | } |
| 337 | res := []PubKey{entry} |
| 338 | |
| 339 | if !loadDotSSH { |
| 340 | return res, nil |
| 341 | } |
| 342 | |
| 343 | |
| 344 | homeDir, err := os.UserHomeDir() |
| 345 | if err != nil { |
| 346 | return nil, err |
| 347 | } |
| 348 | files, err := filepath.Glob(filepath.Join(homeDir, ".ssh/*.pub")) |
| 349 | if err != nil { |
| 350 | panic(err) |
| 351 | } |
| 352 | for _, f := range files { |
| 353 | if !strings.HasSuffix(f, ".pub") { |
| 354 | panic(fmt.Errorf("unexpected ssh public key filename %#q", f)) |
| 355 | } |
| 356 | entry, err := readPublicKey(f) |
| 357 | if err == nil { |
| 358 | if !detectValidPublicKey(entry.Content) { |
| 359 | logrus.Warnf("public key %#q doesn't seem to be in ssh format", entry.Filename) |
| 360 | } else { |
| 361 | res = append(res, entry) |
| 362 | } |
| 363 | } else if !errors.Is(err, os.ErrNotExist) { |
| 364 | return nil, err |
| 365 | } |
| 366 | } |
| 367 | return res, nil |
| 368 | } |
| 369 | |
| 370 | type openSSHInfo struct { |
| 371 | |
| 372 | Version semver.Version |
| 373 | |
| 374 | |
| 375 | GSSAPISupported bool |
| 376 | } |
| 377 | |
| 378 | var sshInfo struct { |
| 379 | sync.Once |
| 380 | |
| 381 | |
| 382 | aesAccelerated bool |
| 383 | |
| 384 | |
| 385 | openSSH openSSHInfo |
| 386 | } |
| 387 | |
| 388 | |
| 389 | |
| 390 | |
| 391 | |
| 392 | |
| 393 | func CommonOpts(ctx context.Context, sshExe SSHExe, useDotSSH bool) ([]string, error) { |
| 394 | configDir, err := dirnames.LimaConfigDir() |
| 395 | if err != nil { |
| 396 | return nil, err |
| 397 | } |
| 398 | privateKeyPath := filepath.Join(configDir, filenames.UserPrivateKey) |
| 399 | _, err = os.Stat(privateKeyPath) |
| 400 | if err != nil { |
| 401 | return nil, err |
| 402 | } |
| 403 | var opts []string |
| 404 | idf, err := identityFileEntry(ctx, sshExe, privateKeyPath) |
| 405 | if err != nil { |
| 406 | return nil, err |
| 407 | } |
| 408 | opts = []string{idf} |
| 409 | |
| 410 | |
| 411 | |
| 412 | if useDotSSH { |
| 413 | homeDir, err := os.UserHomeDir() |
| 414 | if err != nil { |
| 415 | return nil, err |
| 416 | } |
| 417 | files, err := filepath.Glob(filepath.Join(homeDir, ".ssh/*.pub")) |
| 418 | if err != nil { |
| 419 | panic(err) |
| 420 | } |
| 421 | for _, f := range files { |
| 422 | if !strings.HasSuffix(f, ".pub") { |
| 423 | panic(fmt.Errorf("unexpected ssh public key filename %#q", f)) |
| 424 | } |
| 425 | privateKeyPath := strings.TrimSuffix(f, ".pub") |
| 426 | _, err = os.Stat(privateKeyPath) |
| 427 | if errors.Is(err, fs.ErrNotExist) { |
| 428 | |
| 429 | |
| 430 | |
| 431 | |
| 432 | |
| 433 | continue |
| 434 | } |
| 435 | if err != nil { |
| 436 | |
| 437 | return nil, err |
| 438 | } |
| 439 | idf, err = identityFileEntry(ctx, sshExe, privateKeyPath) |
| 440 | if err != nil { |
| 441 | return nil, err |
| 442 | } |
| 443 | opts = append(opts, idf) |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | opts = append(opts, |
| 448 | "StrictHostKeyChecking=no", |
| 449 | "UserKnownHostsFile=/dev/null", |
| 450 | "NoHostAuthenticationForLocalhost=yes", |
| 451 | "PreferredAuthentications=publickey", |
| 452 | "Compression=no", |
| 453 | "BatchMode=yes", |
| 454 | "IdentitiesOnly=yes", |
| 455 | ) |
| 456 | |
| 457 | sshInfo.Do(func() { |
| 458 | sshInfo.aesAccelerated = detectAESAcceleration() |
| 459 | sshInfo.openSSH = detectOpenSSHInfo(ctx, sshExe) |
| 460 | }) |
| 461 | |
| 462 | if sshInfo.openSSH.GSSAPISupported { |
| 463 | opts = append(opts, "GSSAPIAuthentication=no") |
| 464 | } |
| 465 | |
| 466 | |
| 467 | if !sshInfo.openSSH.Version.LessThan(*semver.New("8.1.0")) { |
| 468 | |
| 469 | |
| 470 | |
| 471 | |
| 472 | if sshInfo.aesAccelerated { |
| 473 | logrus.Debugf("AES accelerator seems available, prioritizing [email protected] and [email protected]") |
| 474 | if runtime.GOOS == "windows" { |
| 475 | opts = append(opts, "Ciphers=^[email protected],[email protected]") |
| 476 | } else { |
| 477 | opts = append(opts, "Ciphers=\"^[email protected],[email protected]\"") |
| 478 | } |
| 479 | } else { |
| 480 | logrus.Debugf("AES accelerator does not seem available, prioritizing [email protected]") |
| 481 | if runtime.GOOS == "windows" { |
| 482 | opts = append(opts, "Ciphers=^[email protected]") |
| 483 | } else { |
| 484 | opts = append(opts, "Ciphers=\"^[email protected]\"") |
| 485 | } |
| 486 | } |
| 487 | } |
| 488 | return opts, nil |
| 489 | } |
| 490 | |
| 491 | func identityFileEntry(ctx context.Context, sshExe SSHExe, privateKeyPath string) (string, error) { |
| 492 | if runtime.GOOS == "windows" { |
| 493 | privateKeyPath, err := PathForSSH(ctx, sshExe, privateKeyPath) |
| 494 | if err != nil { |
| 495 | return "", err |
| 496 | } |
| 497 | return fmt.Sprintf(`IdentityFile='%s'`, privateKeyPath), nil |
| 498 | } |
| 499 | return fmt.Sprintf(`IdentityFile="%s"`, privateKeyPath), nil |
| 500 | } |
| 501 | |
| 502 | |
| 503 | func DisableControlMasterOptsFromSSHArgs(sshArgs []string) []string { |
| 504 | argsForOverridingConfigFile := []string{ |
| 505 | "-o", "ControlMaster=no", |
| 506 | "-o", "ControlPath=none", |
| 507 | "-o", "ControlPersist=no", |
| 508 | } |
| 509 | return slices.Concat(argsForOverridingConfigFile, removeOptsFromSSHArgs(sshArgs, "ControlMaster", "ControlPath", "ControlPersist")) |
| 510 | } |
| 511 | |
| 512 | func removeOptsFromSSHArgs(sshArgs []string, removeOpts ...string) []string { |
| 513 | res := make([]string, 0, len(sshArgs)) |
| 514 | isOpt := false |
| 515 | for _, arg := range sshArgs { |
| 516 | if isOpt { |
| 517 | isOpt = false |
| 518 | if !slices.ContainsFunc(removeOpts, func(opt string) bool { |
| 519 | return strings.HasPrefix(arg, opt) |
| 520 | }) { |
| 521 | res = append(res, "-o", arg) |
| 522 | } |
| 523 | } else if arg == "-o" { |
| 524 | isOpt = true |
| 525 | } else { |
| 526 | res = append(res, arg) |
| 527 | } |
| 528 | } |
| 529 | return res |
| 530 | } |
| 531 | |
| 532 | |
| 533 | func IsControlMasterExisting(instDir string) bool { |
| 534 | controlSock := filepath.Join(instDir, filenames.SSHSock) |
| 535 | _, err := os.Stat(controlSock) |
| 536 | return err == nil |
| 537 | } |
| 538 | |
| 539 | |
| 540 | |
| 541 | |
| 542 | |
| 543 | |
| 544 | |
| 545 | func IsControlMasterRunning(ctx context.Context, instDir string) bool { |
| 546 | controlSock := filepath.Join(instDir, filenames.SSHSock) |
| 547 | ctx, cancel := context.WithTimeout(ctx, 3*time.Second) |
| 548 | defer cancel() |
| 549 | var dialer net.Dialer |
| 550 | conn, err := dialer.DialContext(ctx, "unix", controlSock) |
| 551 | if err != nil { |
| 552 | return false |
| 553 | } |
| 554 | _ = conn.Close() |
| 555 | return true |
| 556 | } |
| 557 | |
| 558 | |
| 559 | |
| 560 | |
| 561 | |
| 562 | |
| 563 | func RemoveStaleControlMaster(ctx context.Context, instDir string) (bool, error) { |
| 564 | if IsControlMasterRunning(ctx, instDir) { |
| 565 | return false, nil |
| 566 | } |
| 567 | existed := IsControlMasterExisting(instDir) |
| 568 | controlSock := filepath.Join(instDir, filenames.SSHSock) |
| 569 | if err := os.RemoveAll(controlSock); err != nil { |
| 570 | return false, err |
| 571 | } |
| 572 | return existed, nil |
| 573 | } |
| 574 | |
| 575 | |
| 576 | func SSHOpts(ctx context.Context, sshExe SSHExe, instDir, username string, useDotSSH, forwardAgent, forwardX11, forwardX11Trusted bool) ([]string, error) { |
| 577 | controlSock := filepath.Join(instDir, filenames.SSHSock) |
| 578 | if len(controlSock) >= osutil.UnixPathMax { |
| 579 | return nil, fmt.Errorf("socket path %#q is too long: >= UNIX_PATH_MAX=%d", controlSock, osutil.UnixPathMax) |
| 580 | } |
| 581 | opts, err := CommonOpts(ctx, sshExe, useDotSSH) |
| 582 | if err != nil { |
| 583 | return nil, err |
| 584 | } |
| 585 | controlPath := fmt.Sprintf(`ControlPath="%s"`, controlSock) |
| 586 | if runtime.GOOS == "windows" { |
| 587 | controlSock, err = PathForSSH(ctx, sshExe, controlSock) |
| 588 | if err != nil { |
| 589 | return nil, err |
| 590 | } |
| 591 | controlPath = fmt.Sprintf(`ControlPath='%s'`, controlSock) |
| 592 | } |
| 593 | opts = append(opts, |
| 594 | fmt.Sprintf("User=%s", username), |
| 595 | "ControlMaster=auto", |
| 596 | controlPath, |
| 597 | "ControlPersist=yes", |
| 598 | ) |
| 599 | if forwardAgent { |
| 600 | opts = append(opts, "ForwardAgent=yes") |
| 601 | } |
| 602 | if forwardX11 { |
| 603 | opts = append(opts, "ForwardX11=yes") |
| 604 | } |
| 605 | if forwardX11Trusted { |
| 606 | opts = append(opts, "ForwardX11Trusted=yes") |
| 607 | } |
| 608 | return opts, nil |
| 609 | } |
| 610 | |
| 611 | |
| 612 | |
| 613 | func SSHArgsFromOpts(opts []string) []string { |
| 614 | args := []string{"-F", "/dev/null"} |
| 615 | for _, o := range opts { |
| 616 | args = append(args, "-o", o) |
| 617 | } |
| 618 | return args |
| 619 | } |
| 620 | |
| 621 | |
| 622 | func SSHOptsRemovingControlPath(opts []string) []string { |
| 623 | |
| 624 | copiedOpts := slices.Clone(opts) |
| 625 | return slices.DeleteFunc(copiedOpts, func(s string) bool { |
| 626 | return strings.HasPrefix(s, "ControlMaster") || strings.HasPrefix(s, "ControlPath") || strings.HasPrefix(s, "ControlPersist") |
| 627 | }) |
| 628 | } |
| 629 | |
| 630 | func ParseOpenSSHVersion(version []byte) *semver.Version { |
| 631 | |
| 632 | |
| 633 | regex := regexp.MustCompile(`(?m)^OpenSSH(?:_for_Windows[_ ]|_)(\d+\.\d+)(?:p(\d+))?\b`) |
| 634 | matches := regex.FindSubmatch(version) |
| 635 | if len(matches) == 3 { |
| 636 | if len(matches[2]) == 0 { |
| 637 | matches[2] = []byte("0") |
| 638 | } |
| 639 | return semver.New(fmt.Sprintf("%s.%s", matches[1], matches[2])) |
| 640 | } |
| 641 | |
| 642 | |
| 643 | logrus.Debugf("ParseOpenSSHVersion: no match in %q; returning 0.0.0", string(version)) |
| 644 | return &semver.Version{} |
| 645 | } |
| 646 | |
| 647 | func parseOpenSSHGSSAPISupported(version string) bool { |
| 648 | return !strings.Contains(version, `Unsupported option "gssapiauthentication"`) |
| 649 | } |
| 650 | |
| 651 | |
| 652 | type sshExecutable struct { |
| 653 | Path string |
| 654 | Size int64 |
| 655 | ModTime time.Time |
| 656 | } |
| 657 | |
| 658 | var ( |
| 659 | |
| 660 | openSSHInfos = map[sshExecutable]*openSSHInfo{} |
| 661 | openSSHInfosRW sync.RWMutex |
| 662 | ) |
| 663 | |
| 664 | func detectOpenSSHInfo(ctx context.Context, sshExe SSHExe) openSSHInfo { |
| 665 | var ( |
| 666 | info openSSHInfo |
| 667 | exe sshExecutable |
| 668 | stderr bytes.Buffer |
| 669 | ) |
| 670 | |
| 671 | |
| 672 | |
| 673 | |
| 674 | if st, err := os.Stat(sshExe.Exe); err == nil { |
| 675 | exe = sshExecutable{Path: sshExe.Exe, Size: st.Size(), ModTime: st.ModTime()} |
| 676 | openSSHInfosRW.RLock() |
| 677 | info := openSSHInfos[exe] |
| 678 | openSSHInfosRW.RUnlock() |
| 679 | if info != nil { |
| 680 | return *info |
| 681 | } |
| 682 | } |
| 683 | sshArgs := append([]string{}, sshExe.Args...) |
| 684 | |
| 685 | sshArgs = append(sshArgs, "-o", "GSSAPIAuthentication=no", "-V") |
| 686 | cmd := exec.CommandContext(ctx, sshExe.Exe, sshArgs...) |
| 687 | cmd.Stderr = &stderr |
| 688 | if err := cmd.Run(); err != nil { |
| 689 | logrus.Warnf("failed to run %v: stderr=%#q", cmd.Args, stderr.String()) |
| 690 | } else { |
| 691 | info = openSSHInfo{ |
| 692 | Version: *ParseOpenSSHVersion(stderr.Bytes()), |
| 693 | GSSAPISupported: parseOpenSSHGSSAPISupported(stderr.String()), |
| 694 | } |
| 695 | logrus.Debugf("OpenSSH version %s detected, is GSSAPI supported: %t", info.Version, info.GSSAPISupported) |
| 696 | openSSHInfosRW.Lock() |
| 697 | openSSHInfos[exe] = &info |
| 698 | openSSHInfosRW.Unlock() |
| 699 | } |
| 700 | return info |
| 701 | } |
| 702 | |
| 703 | func DetectOpenSSHVersion(ctx context.Context, sshExe SSHExe) semver.Version { |
| 704 | return detectOpenSSHInfo(ctx, sshExe).Version |
| 705 | } |
| 706 | |
| 707 | |
| 708 | |
| 709 | |
| 710 | |
| 711 | func detectValidPublicKey(content string) bool { |
| 712 | if strings.ContainsRune(content, '\n') { |
| 713 | return false |
| 714 | } |
| 715 | spaced := strings.SplitN(content, " ", 3) |
| 716 | if len(spaced) < 2 { |
| 717 | return false |
| 718 | } |
| 719 | algo, base64Key := spaced[0], spaced[1] |
| 720 | decodedKey, err := base64.StdEncoding.DecodeString(base64Key) |
| 721 | if err != nil || len(decodedKey) < 4 { |
| 722 | return false |
| 723 | } |
| 724 | sigLength := binary.BigEndian.Uint32(decodedKey) |
| 725 | |
| 726 | |
| 727 | |
| 728 | |
| 729 | if sigLength > uint32(len(decodedKey))-4 { |
| 730 | return false |
| 731 | } |
| 732 | sigFormat := string(decodedKey[4 : 4+sigLength]) |
| 733 | return algo == sigFormat |
| 734 | } |
| 735 | |
| 736 | func detectAESAcceleration() bool { |
| 737 | if !cpu.Initialized { |
| 738 | if runtime.GOOS == "linux" && runtime.GOARCH == "arm64" { |
| 739 | |
| 740 | |
| 741 | return cpu.ARM64.HasAES |
| 742 | } |
| 743 | if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" { |
| 744 | |
| 745 | |
| 746 | |
| 747 | |
| 748 | |
| 749 | |
| 750 | |
| 751 | |
| 752 | |
| 753 | logrus.Debug("Failed to detect CPU features. Assuming that AES acceleration is available on this Apple silicon.") |
| 754 | return true |
| 755 | } |
| 756 | logrus.Warn("Failed to detect CPU features. Assuming that AES acceleration is not available.") |
| 757 | return false |
| 758 | } |
| 759 | return cpu.ARM.HasAES || cpu.ARM64.HasAES || cpu.PPC64.IsPOWER8 || cpu.S390X.HasAES || cpu.X86.HasAES |
| 760 | } |