package main import ( "context" "fmt" "net" "os" "os/exec" "path/filepath" "strconv" "strings" "time" "github.com/charmbracelet/x/term" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/resolver" internalssh "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/ssh" ) // stdinIsTerminal is replaced in tests. var stdinIsTerminal = func() bool { return term.IsTerminal(os.Stdin.Fd()) } // confirmStatus asks before connecting to a host whose NetBox status is listed // in ssh.warn_status. Without a terminal it only warns, so scripts keep working. func confirmStatus(cfg *config.Config, host resolvedHost, force bool) error { if force || !cfg.SSH.WarnsStatus(host.Status) { return nil } message := fmt.Sprintf("%s has NetBox status %q", host.Name, host.Status) if !stdinIsTerminal() { fmt.Fprintf(os.Stderr, "netssh: warning: %s\n", message) return nil } if err := confirmAction(message+" — connect anyway", false); err != nil { return fmt.Errorf("%s: %w (skip this question with --force)", host.Name, err) } return nil } // connectPort returns the port given in args (-p for ssh, -P for sftp and scp, // or -o Port=), else 22. The default port is already in args at this point. func connectPort(client internalssh.Client, args []string, dests []int) int { end := len(args) if len(dests) > 0 && dests[0] <= len(args) { end = dests[0] } flag := client.PortArgs("")[0] for i := 0; i < end; i++ { arg := args[i] value := "" switch { case arg == flag && i+1 < end: value = args[i+1] case strings.HasPrefix(arg, flag) && len(arg) > len(flag): value = arg[len(flag):] case arg == "-o" && i+1 < end: if key, v, ok := strings.Cut(args[i+1], "="); ok && strings.EqualFold(strings.TrimSpace(key), "port") { value = v } } if port, err := strconv.Atoi(strings.TrimSpace(value)); err == nil && port > 0 && port <= 65535 { return port } } return 22 } // reachable reports whether address accepts TCP connections on port. func reachable(address string, port int, timeout time.Duration) bool { conn, err := net.DialTimeout("tcp", net.JoinHostPort(address, strconv.Itoa(port)), timeout) if err != nil { return false } _ = conn.Close() return true } // usesJumpHost reports whether the connection goes through a jump host, so // the target address cannot be probed from this machine. func usesJumpHost(opts config.SSHOptions, flags internalssh.WrapperFlags) bool { if flags.NoJump { return false } return flags.Jump != "" || (opts.ProxyJump != "" && !strings.EqualFold(opts.ProxyJump, "none")) || opts.Options["proxycommand"] != "" } // fallbackProbe and fallbackCandidates are replaced in tests. var ( fallbackProbe = reachable fallbackCandidates = netboxCandidates ) // applyFallback keeps host.IP when it answers on the SSH port. Otherwise it // tries the addresses the other resolver strategies find and connects to the // first one that answers, with resolver.fallback enabled. func applyFallback(cfg *config.Config, host resolvedHost, opts config.SSHOptions, flags internalssh.WrapperFlags, port int) resolvedHost { if !cfg.Resolver.Fallback || host.Kind == config.StaticKind || usesJumpHost(opts, flags) { return host } timeout := cfg.Resolver.FallbackTimeoutDuration() if fallbackProbe(host.IP, port, timeout) { return host } candidates, err := fallbackCandidates(cfg, host) if err != nil { fmt.Fprintf(os.Stderr, "netssh: %s does not answer on port %d and no other address is known: %v\n", host.IP, port, err) return host } for _, candidate := range candidates { if candidate.Address == host.IP || !internalssh.ValidAddress(candidate.Address) { continue } if fallbackProbe(candidate.Address, port, timeout) { fmt.Fprintf(os.Stderr, "netssh: %s does not answer on port %d, using %s (%s)\n", host.IP, port, candidate.Address, candidate.Strategy) host.IP = candidate.Address return host } } fmt.Fprintf(os.Stderr, "netssh: no address of %s answers on port %d; trying %s anyway\n", host.Name, port, host.IP) return host } // netboxCandidates looks the host up again and lists every strategy's address. func netboxCandidates(cfg *config.Config, host resolvedHost) ([]resolver.Candidate, error) { if !cfg.HasNetBox() { return nil, fmt.Errorf("no NetBox configured") } client := newNetBoxClient(cfg) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() target, err := client.FindHost(ctx, host.Name, host.Kind) if err != nil { return nil, err } chain, err := resolver.New(cfg.Resolver) if err != nil { return nil, err } return chain.Candidates(ctx, &target, client) } // knownHostsKeys lists the known_hosts names ssh may have stored for a host. func knownHostsKeys(name string, addresses []string, port int) []string { seen := map[string]bool{} var keys []string add := func(key string) { if key == "" || seen[strings.ToLower(key)] { return } seen[strings.ToLower(key)] = true keys = append(keys, key) if port != 22 { keys = append(keys, "["+key+"]:"+strconv.Itoa(port)) } } _, bare := netbox.SplitTarget(name) add(bare) for _, address := range addresses { add(address) } return keys } // knownHostsFile returns the first UserKnownHostsFile configured for the // host, or "" for ssh-keygen's default (~/.ssh/known_hosts). func knownHostsFile(opts config.SSHOptions) string { fields := strings.Fields(opts.Options["userknownhostsfile"]) if len(fields) == 0 || fields[0] == "/dev/null" { return "" } file := fields[0] if rest, ok := strings.CutPrefix(file, "~/"); ok { if home, err := os.UserHomeDir(); err == nil { file = filepath.Join(home, rest) } } return file } // removeKnownHosts runs ssh-keygen -R for every key. ssh-keygen keeps a // known_hosts.old backup of the previous file. var removeKnownHosts = func(keys []string, file string) error { for _, key := range keys { args := []string{"-R", key} if file != "" { args = append(args, "-f", file) } cmd := exec.Command("ssh-keygen", args...) cmd.Stdout, cmd.Stderr = os.Stderr, os.Stderr if err := cmd.Run(); err != nil { return fmt.Errorf("ssh-keygen -R %s: %w", key, err) } } return nil } // offerKnownHostsCleanup reports a changed NetBox address and, in a terminal, // offers to remove the host key stored for the old address. func offerKnownHostsCleanup(opts config.SSHOptions, host resolvedHost, port int) { fmt.Fprintf(os.Stderr, "netssh: address of %s changed from %s to %s\n", host.Name, host.PreviousIP, host.IP) if opts.HostKeyChecking == "off" { return } keys := knownHostsKeys("", []string{host.PreviousIP}, port) if !stdinIsTerminal() { fmt.Fprintf(os.Stderr, "netssh: remove the old host key with: netssh known-hosts reset %s\n", host.Name) return } if confirmAction("Remove the known_hosts entry of the old address "+host.PreviousIP, false) != nil { return } if err := removeKnownHosts(keys, knownHostsFile(opts)); err != nil { fmt.Fprintf(os.Stderr, "netssh: %v\n", err) } }