跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

sshutil.go

760 行 · 25.0 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package sshutil
5
6import (
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// Environment variable that allows configuring the command (alias) to execute
38// in place of the 'ssh' executable.
39const EnvShellSSH = "SSH"
40
41type SSHExe struct {
42 Exe string
43 Args []string
44}
45
46func 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// pickCompleteSSHOnWindows returns an ssh.exe whose directory also has
81// scp.exe and ssh-keygen.exe, which Lima needs for create and copy.
82// MinGit ships ssh.exe without those, so a partial install is skipped for
83// the next complete one on PATH, then the native install under
84// %SystemRoot%\System32\OpenSSH. Returns "" when none qualifies, so the
85// caller falls through to exec.LookPath instead of picking a partial one.
86func 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// systemRoot returns %SystemRoot%, or C:\Windows when unset - honouring
115// installs (Windows PE, some enterprise setups) that put it off the C: drive.
116func systemRoot() string {
117 if r := os.Getenv("SystemRoot"); r != "" {
118 return r
119 }
120 return `C:\Windows`
121}
122
123// missingSiblings returns the names in siblings that do not exist in dir.
124// siblings must be clean paths as they are joined with dir as-is.
125func 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
135var (
136 // cygwinDetectCache maps a resolved ssh path to its sibling cygpath.exe,
137 // or "" when that ssh is not Cygwin-based. Each path is probed once.
138 cygwinDetectCache = map[string]string{}
139 cygwinDetectCacheRW sync.RWMutex
140)
141
142// resolvedSSHPath returns the absolute, symlink-resolved path of sshExe's
143// binary — the directory Lima reads its companion tools from. It returns
144// ("", false) when a bare name does not resolve on PATH.
145func 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// companionForSSH returns tool from the same toolchain as sshExe. NewSSHExe can
165// select an ssh outside PATH, so resolving a companion by bare name can pick a
166// different toolchain than the one PathForSSH formats paths for. It returns tool
167// unchanged on non-Windows, or when no sibling exists, leaving it to PATH.
168func 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// cygpathForSSH returns the cygpath.exe beside sshExe (resolved through
185// symlinks) and whether sshExe is Cygwin-based. Callers pass the returned
186// path to exec.Command so conversions run through that toolchain's own
187// cygpath, even when $SSH points outside PATH. It returns
188// ("", false) on non-Windows or empty input; results are cached per resolved path.
189func 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// PathForSSH converts orig to the path form Lima's ssh-family invocations
218// expect; unchanged on non-Windows. On Windows, Cygwin-based ssh (Git for
219// Windows, MSYS2) gets a /c/Users/... form from the sibling cygpath, which
220// respects the toolchain's fstab; native Windows OpenSSH gets forward
221// slashes (C:/Users/...), which native ssh, ssh-keygen, and scp accept.
222func 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// SftpServerForSSH returns the path of sftp-server binary from sshExe's toolchain,
233// so the server behind a reverse-sshfs mount comes from the same install as the
234// ssh driving it. For Cygwin-based ssh the sibling cygpath resolves
235// /usr/lib/ssh/sftp-server; for native OpenSSH it is sftp-server.exe beside
236// ssh.exe. Returns "" on non-Windows, empty input, or no match, leaving the
237// caller to fall back to its library's auto-detection.
238func 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 // Validate with LookPath, which appends the ".exe" that cygpath omits.
248 // Under the default driver sshocker resolves this path with LookPath as
249 // well and fails the mount when it does not resolve, so returning
250 // nothing beats returning a path it will reject.
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
270type PubKey struct {
271 Filename string
272 Content string
273}
274
275func 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// DefaultPubKeys returns the public key from $LIMA_HOME/_config/user.pub.
289// The key will be created if it does not yet exist.
290//
291// When loadDotSSH is true, ~/.ssh/*.pub will be appended to make the VM accessible without specifying
292// an identity explicitly.
293func DefaultPubKeys(ctx context.Context, loadDotSSH bool) ([]PubKey, error) {
294 // Read $LIMA_HOME/_config/user.pub
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 // no passphrase, no user@host comment
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 // Append all of ~/.ssh/*.pub
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) // Only possible error is ErrBadPattern, so this should be unreachable.
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
370type openSSHInfo struct {
371 // Version is set to the version of OpenSSH, or semver.New("0.0.0") if the version cannot be determined.
372 Version semver.Version
373
374 // Some distributions omit this feature by default, for example, Alpine, NixOS.
375 GSSAPISupported bool
376}
377
378var sshInfo struct {
379 sync.Once
380 // aesAccelerated is set to true when AES acceleration is available.
381 // Available on almost all modern Intel/AMD processors.
382 aesAccelerated bool
383
384 // OpenSSH executable information for the version and supported options.
385 openSSH openSSHInfo
386}
387
388// CommonOpts returns ssh option key-value pairs like {"IdentityFile=/path/to/id_foo"}.
389// The result may contain different values with the same key.
390//
391// The result always contains the IdentityFile option.
392// The result never contains the Port option.
393func 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 // Append all private keys corresponding to ~/.ssh/*.pub to keep old instances working
411 // that had been created before lima started using an internal identity.
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) // Only possible error is ErrBadPattern, so this should be unreachable.
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 // Skip .pub files without a matching private key. This is reasonably common,
429 // due to major projects like Vault recommending the ${name}-cert.pub format
430 // for SSH certificate files.
431 //
432 // e.g. https://www.vaultproject.io/docs/secrets/ssh/signed-ssh-certificates
433 continue
434 }
435 if err != nil {
436 // Fail on permission-related and other path errors
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 // Only OpenSSH version 8.1 and later support adding ciphers to the front of the default set
467 if !sshInfo.openSSH.Version.LessThan(*semver.New("8.1.0")) {
468 // By default, `ssh` choose [email protected], even when AES accelerator is available.
469 // (OpenSSH_8.1p1, macOS 11.6, MacBookPro 2020, Core i7-1068NG7)
470 //
471 // We prioritize AES algorithms when AES accelerator is available.
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
491func 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// DisableControlMasterOptsFromSSHArgs returns ssh args that disable ControlMaster, ControlPath, and ControlPersist.
503func 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
512func 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// IsControlMasterExisting returns true if the control socket file exists.
533func IsControlMasterExisting(instDir string) bool {
534 controlSock := filepath.Join(instDir, filenames.SSHSock)
535 _, err := os.Stat(controlSock)
536 return err == nil
537}
538
539// IsControlMasterRunning reports whether an SSH ControlMaster process is
540// actively listening on the instance's control socket. Unlike
541// IsControlMasterExisting, which only checks that the socket file is present,
542// this dials the socket to verify that a master is alive. A stale socket left
543// behind by an unclean master exit (kill -9, OOM, host crash, or the Cygwin
544// emulation file outliving its process) has no listener and returns false.
545func 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// RemoveStaleControlMaster removes the SSH control socket only when no master
559// process is listening on it. It returns true when a stale socket was removed.
560// A live master's socket is never touched (returns false), and a missing socket
561// is treated as a no-op (returns false). This lets callers recover from a wedged
562// session without clobbering a healthy ControlMaster.
563func 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// SSHOpts adds the following options to CommonOptions: User, ControlMaster, ControlPath, ControlPersist.
576func 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), // guest and host have the same username, but we should specify the username explicitly (#85)
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// SSHArgsFromOpts returns ssh args from opts.
612// The result always contains {"-F", "/dev/null} in addition to {"-o", "KEY=VALUE", ...}.
613func 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// SSHOptsRemovingControlPath removes ControlMaster, ControlPath, and ControlPersist options from SSH options.
622func SSHOptsRemovingControlPath(opts []string) []string {
623 // Create a copy of opts to avoid modifying the original slice, since slices.DeleteFunc modifies the slice in place.
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
630func ParseOpenSSHVersion(version []byte) *semver.Version {
631 // Win32-OpenSSH banners: "OpenSSH_for_Windows_9.5p2", and older releases
632 // with a space before the version.
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 // A 0.0.0 return silently downgrades version-gated behavior, so log the
642 // unparsed banner for --debug traces.
643 logrus.Debugf("ParseOpenSSHVersion: no match in %q; returning 0.0.0", string(version))
644 return &semver.Version{}
645}
646
647func parseOpenSSHGSSAPISupported(version string) bool {
648 return !strings.Contains(version, `Unsupported option "gssapiauthentication"`)
649}
650
651// sshExecutable beyond path also records size and mtime, in the case of ssh upgrades.
652type sshExecutable struct {
653 Path string
654 Size int64
655 ModTime time.Time
656}
657
658var (
659 // openSSHInfos caches the parsed version and supported options of each ssh executable, if it is needed again.
660 openSSHInfos = map[sshExecutable]*openSSHInfo{}
661 openSSHInfosRW sync.RWMutex
662)
663
664func detectOpenSSHInfo(ctx context.Context, sshExe SSHExe) openSSHInfo {
665 var (
666 info openSSHInfo
667 exe sshExecutable
668 stderr bytes.Buffer
669 )
670 // Note: For SSH wrappers like "kitten ssh", os.Stat will check the wrapper
671 // executable (kitten) instead of the underlying ssh binary. This means
672 // cache invalidation won't work properly - ssh upgrades won't be detected
673 // since kitten's size/mtime won't change. This is probably acceptable.
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 // -V should be last
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
703func DetectOpenSSHVersion(ctx context.Context, sshExe SSHExe) semver.Version {
704 return detectOpenSSHInfo(ctx, sshExe).Version
705}
706
707// detectValidPublicKey returns whether content represent a public key.
708// OpenSSH public key format have the structure of '<algorithm> <key> <comment>'.
709// By checking 'algorithm' with signature format identifier in 'key' part,
710// this function may report false positive but provide better compatibility.
711func 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 // The format identifier occupies decodedKey[4 : 4+sigLength], so the buffer
726 // must hold sigLength bytes beyond the 4-byte length prefix, not just
727 // sigLength bytes in total. len(decodedKey) >= 4 is guaranteed above, so the
728 // subtraction cannot underflow.
729 if sigLength > uint32(len(decodedKey))-4 {
730 return false
731 }
732 sigFormat := string(decodedKey[4 : 4+sigLength])
733 return algo == sigFormat
734}
735
736func detectAESAcceleration() bool {
737 if !cpu.Initialized {
738 if runtime.GOOS == "linux" && runtime.GOARCH == "arm64" {
739 // cpu.Initialized seems to always be false, even when the cpu.ARM64 struct is filled out
740 // it is only being set by readARM64Registers, but not by readHWCAP or readLinuxProcCPUInfo
741 return cpu.ARM64.HasAES
742 }
743 if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" {
744 // golang.org/x/sys/cpu supports darwin/amd64, linux/amd64, and linux/arm64,
745 // but apparently lacks support for darwin/arm64: https://github.com/golang/sys/blob/v0.5.0/cpu/cpu_arm64.go#L43-L60
746 //
747 // According to https://gist.github.com/voluntas/fd279c7b4e71f9950cfd4a5ab90b722b ,
748 // aes-128-gcm is faster than chacha20-poly1305 on Apple M1.
749 //
750 // So we return `true` here.
751 //
752 // This workaround will not be needed when https://go-review.googlesource.com/c/sys/+/332729 is merged.
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}