package connect
import (
"fmt"
"os"
"path/filepath"
"strings"
"git.neuromancer.ovh/bastien-mrq/sssh/internal/host"
)
// JumpConfig préserve notamment IdentityFile par bastion. Les alias sont
// conservés pour que les règles utilisateur Host bastion restent applicables.
func JumpConfig(hops []host.Host) (string, func(), error) {
noop := func() {}
if len(hops) == 0 {
return "", noop, nil
}
var b strings.Builder
seen := map[string]bool{}
for _, h := range hops {
if h.Name == "" || strings.HasPrefix(h.Name, "-") || strings.ContainsAny(h.Name, " \t\r\n\x00*?!,\"'\\") {
return "", noop, fmt.Errorf("alias de bastion invalide : %q", h.Name)
}
if seen[h.Name] {
continue
}
seen[h.Name] = true
if h.Host == "" || h.Port < 0 || h.Port > 65535 {
return "", noop, fmt.Errorf("bastion invalide : %s", h.Name)
}
for _, value := range []string{h.Host, h.User, h.Identity} {
if strings.ContainsAny(value, "\r\n\x00") {
return "", noop, fmt.Errorf("caractère de contrôle dans le bastion %s", h.Name)
}
}
fmt.Fprintf(&b, "Host %s\n HostName %s\n", h.Name, configQuote(h.Host))
if h.User != "" {
fmt.Fprintf(&b, " User %s\n", configQuote(h.User))
}
if h.Port != 0 {
fmt.Fprintf(&b, " Port %d\n", h.Port)
}
if h.Identity != "" {
fmt.Fprintf(&b, " IdentityFile %s\n", configQuote(host.ExpandTilde(h.Identity)))
}
// La chaîne est déjà développée par sssh ; éviter une seconde expansion.
b.WriteString(" ProxyJump none\n")
}
home, err := os.UserHomeDir()
if err != nil {
return "", noop, err
}
fmt.Fprintf(&b, "Host *\n Include %s\n Include /etc/ssh/ssh_config\n", configQuote(filepath.Join(home, ".ssh", "config")))
f, err := os.CreateTemp("", "sssh-jumps-*.conf")
if err != nil {
return "", noop, err
}
cleanup := func() { _ = os.Remove(f.Name()) }
_, err = f.WriteString(b.String())
closeErr := f.Close()
if err != nil {
cleanup()
return "", noop, err
}
if closeErr != nil {
cleanup()
return "", noop, closeErr
}
return f.Name(), cleanup, nil
}
func configQuote(s string) string {
return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(s) + `"`
}