Skip to content

Commit 9c400d9

Browse files
committed
Don't try to remove host keys when ~/.ssh/known_hosts doesn't exist
`ssh-keygen -R` will exit with a non-0 status and the hostagent would abort. If the file doesn't exist, then there isn't anything to do. Signed-off-by: Jan Dubois <[email protected]>
1 parent 5d337b9 commit 9c400d9

File tree

2 files changed

+24
-6
lines changed

2 files changed

+24
-6
lines changed

pkg/hostagent/hostagent.go

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -159,12 +159,9 @@ func (a *HostAgent) Run(ctx context.Context) error {
159159
}
160160
stBooting := stBase
161161
a.emitEvent(ctx, hostagentapi.Event{Status: stBooting})
162-
sshFixCmd := exec.Command("ssh-keygen",
163-
"-R", fmt.Sprintf("[127.0.0.1]:%d", sshLocalPort),
164-
"-R", fmt.Sprintf("[localhost]:%d", sshLocalPort),
165-
)
166-
if out, err := sshFixCmd.CombinedOutput(); err != nil {
167-
return errors.Wrapf(err, "failed to run %v: %q", sshFixCmd.Args, string(out))
162+
if err := sshutil.RemoveKnownHostEntries(sshLocalPort); err != nil {
163+
a.l.WithError(err).Error("couldn't remove existing localhost host keys")
164+
return err
168165
}
169166

170167
go func() {

pkg/sshutil/sshutil.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package sshutil
22

33
import (
4+
"fmt"
45
"os"
6+
"os/exec"
57
"path/filepath"
68
"strings"
79

@@ -46,6 +48,25 @@ func DefaultPubKeys() []PubKey {
4648
return res
4749
}
4850

51+
func RemoveKnownHostEntries(sshLocalPort int) error {
52+
homeDir, err := os.UserHomeDir()
53+
if err != nil {
54+
return err
55+
}
56+
// `ssh-keygen -R` will return a non-0 status when ~/.ssh/known_hosts doesn't exist
57+
if _, err := os.Stat(filepath.Join(homeDir, ".ssh/known_hosts")); errors.Is(err, os.ErrNotExist) {
58+
return nil
59+
}
60+
sshFixCmd := exec.Command("ssh-keygen",
61+
"-R", fmt.Sprintf("[127.0.0.1]:%d", sshLocalPort),
62+
"-R", fmt.Sprintf("[localhost]:%d", sshLocalPort),
63+
)
64+
if out, err := sshFixCmd.CombinedOutput(); err != nil {
65+
return errors.Wrapf(err, "failed to run %v: %q", sshFixCmd.Args, string(out))
66+
}
67+
return nil
68+
}
69+
4970
func SSHArgs(instDir string) ([]string, error) {
5071
controlSock := filepath.Join(instDir, filenames.SSHSock)
5172
if len(controlSock) >= osutil.UnixPathMax {

0 commit comments

Comments
 (0)