Skip to content

Commit

Permalink
Issue #3514 Remove crc instance entries from known_hosts file
Browse files Browse the repository at this point in the history
while using the podman preset in CRC the instance identity is added to the
known_hosts file and when it changes podman-remote complains about it  and
shows the following error:
```
Error: failed to connect: ssh: handshake failed: knownhosts: key mismatch
```

this will occur in crc when users upgrade podman from 4.3.1 to 4.4.1 with this patch it'll
remove the [127.0.0.1]:2222 entries from known_hosts which should work-around this issue
  • Loading branch information
anjannath authored and openshift-merge-robot committed Mar 31, 2023
1 parent 99c46e6 commit 469aa3e
Showing 1 changed file with 58 additions and 0 deletions.
58 changes: 58 additions & 0 deletions pkg/crc/machine/delete.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
package machine

import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"

"github.com/crc-org/crc/pkg/crc/constants"
"github.com/crc-org/crc/pkg/crc/logging"
"github.com/crc-org/crc/pkg/crc/podman"
"github.com/pkg/errors"
Expand Down Expand Up @@ -39,5 +44,58 @@ func (client *client) Delete() error {
logging.Warnf("Failed to remove crc contexts from kubeconfig: %v", err)
}
}
return removeCRCHostEntriesFromKnownHosts()
}

func removeCRCHostEntriesFromKnownHosts() error {
knownHostsPath := filepath.Join(constants.GetHomeDir(), ".ssh", "known_hosts")
if _, err := os.Stat(knownHostsPath); err != nil {
return nil
}
f, err := os.Open(knownHostsPath)
if err != nil {
return fmt.Errorf("Unable to open user's 'known_hosts' file: %w", err)
}
defer f.Close()

tempHostsFile, err := os.CreateTemp(filepath.Join(constants.GetHomeDir(), ".ssh"), "crc")
if err != nil {
return fmt.Errorf("Unable to create temp file: %w", err)
}
defer func() {
tempHostsFile.Close()
os.Remove(tempHostsFile.Name())
}()

if err := tempHostsFile.Chmod(0600); err != nil {
return fmt.Errorf("Error trying to change permissions for temp file: %w", err)
}

var foundCRCEntries bool
scanner := bufio.NewScanner(f)
writer := bufio.NewWriter(tempHostsFile)
for scanner.Scan() {
if strings.Contains(scanner.Text(), "[127.0.0.1]:2222") || strings.Contains(scanner.Text(), "192.168.130.11") {
foundCRCEntries = true
continue
}
if _, err := writer.WriteString(fmt.Sprintf("%s\n", scanner.Text())); err != nil {
return fmt.Errorf("Error while writing hostsfile content to temp file: %w", err)
}
}

if err := writer.Flush(); err != nil {
return fmt.Errorf("Error while flushing buffered content to temp file: %w", err)
}

if foundCRCEntries {
if err := f.Close(); err != nil {
return fmt.Errorf("Error closing known_hosts file: %w", err)
}
if err := tempHostsFile.Close(); err != nil {
return fmt.Errorf("Error closing temp file: %w", err)
}
return os.Rename(tempHostsFile.Name(), knownHostsPath)
}
return nil
}

0 comments on commit 469aa3e

Please sign in to comment.