From 88724bec6dc1ac0da3e297b11a8039d6675684bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anders=20F=20Bj=C3=B6rklund?= Date: Tue, 9 Jul 2024 12:39:06 +0200 Subject: [PATCH] Use net helper for local ssh CommonOpts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Anders F Björklund --- cmd/limactl/copy.go | 2 +- pkg/sshutil/sshutil.go | 11 ++++++++++- pkg/sshutil/sshutil_test.go | 4 ++++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/cmd/limactl/copy.go b/cmd/limactl/copy.go index 5c55d0ec685..d1b55d1b9d3 100644 --- a/cmd/limactl/copy.go +++ b/cmd/limactl/copy.go @@ -85,7 +85,7 @@ func copyAction(cmd *cobra.Command, args []string) error { } else { scpArgs = append(scpArgs, fmt.Sprintf("scp://%s@%s:%d/%s", *inst.Config.User.Name, inst.SSHAddress, inst.SSHLocalPort, path[1])) } - if inst.SSHAddress != "127.0.0.1" { + if !sshutil.IsLocalhost(inst.SSHAddress) { localhostOnly = false } instances[instName] = inst diff --git a/pkg/sshutil/sshutil.go b/pkg/sshutil/sshutil.go index 8da0f759016..cb3e07c4d1a 100644 --- a/pkg/sshutil/sshutil.go +++ b/pkg/sshutil/sshutil.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "io/fs" + "net" "os" "os/exec" "path/filepath" @@ -121,6 +122,14 @@ var sshInfo struct { openSSHVersion semver.Version } +func IsLocalhost(address string) bool { + ip := net.ParseIP(address) + if ip == nil { + return false + } + return ip.IsLoopback() +} + // CommonOpts returns ssh option key-value pairs like {"IdentityFile=/path/to/id_foo"}. // The result may contain different values with the same key. // @@ -234,7 +243,7 @@ func SSHOpts(instDir, username string, useDotSSH bool, hostAddress string, forwa if len(controlSock) >= osutil.UnixPathMax { return nil, fmt.Errorf("socket path %q is too long: >= UNIX_PATH_MAX=%d", controlSock, osutil.UnixPathMax) } - opts, err := CommonOpts(useDotSSH, hostAddress == "127.0.0.1") + opts, err := CommonOpts(useDotSSH, IsLocalhost(hostAddress)) if err != nil { return nil, err } diff --git a/pkg/sshutil/sshutil_test.go b/pkg/sshutil/sshutil_test.go index ef2b754da23..e452a160f1d 100644 --- a/pkg/sshutil/sshutil_test.go +++ b/pkg/sshutil/sshutil_test.go @@ -15,6 +15,10 @@ func TestDefaultPubKeys(t *testing.T) { } } +func TestIsLocalhost(t *testing.T) { + assert.Equal(t, IsLocalhost("127.0.0.1"), true) +} + func TestParseOpenSSHVersion(t *testing.T) { assert.Check(t, ParseOpenSSHVersion([]byte("OpenSSH_8.4p1 Ubuntu")).Equal( semver.Version{Major: 8, Minor: 4, Patch: 1, PreRelease: "", Metadata: ""}))