Gitfed
bastien-mrq/sssh/ Commits/ 746e092

feat: VPN automatique (OpenVPN ou commandes up/down) avant la connexion

- profils [vpn.<nom>] dans hosts.toml : sssh vpn add|list|rm - champ vpn sur un host (-v en CLI, formulaire TUI) - à la connexion : sonde TCP de la cible (ou check / premier hop du jump) ; si injoignable, sudo openvpn en arrière-plan, attente, ssh en enfant, puis arrêt via l'interface de management (sans second sudo) - config déplacée vers ~/.config/sssh/hosts.toml (XDG), ancien emplacement macOS conservé s'il existe - sssh list : colonnes JUMP et VPN ; export/import incluent les profils Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

bastien-mrq 2026-09-28 07:55 commit 746e09218ddcae512eb3e15eeaf626f0bc8d99af parent a0dc4209ac89e84d54f487414911e97594b0e214
12 fichiers modifiés +750 −80
A .rtk/filters.toml +13 −0
A CLAUDE.md +10 −0
M README.md +33 −1
M completions/_sssh +4 −0
M completions/sssh.bash +6 −1
M completions/sssh.fish +4 −0
M internal/connect/connect.go +36 −3
M internal/host/host.go +14 −0
M internal/store/store.go +80 −11
M internal/tui/form.go +12 −2
A internal/vpn/vpn.go +298 −0
M main.go +240 −62
.rtk/filters.toml
diff --git a/.rtk/filters.toml b/.rtk/filters.toml new file mode 100644 index 0000000..d9bd43f --- /dev/null +++ b/.rtk/filters.toml @@ -0,0 +1,13 @@ +# Project-local RTK filters — commit this file with your repo. +# Filters here override user-global and built-in filters. +# Docs: https://github.com/rtk-ai/rtk#custom-filters +schema_version = 1 + +# Example: suppress build noise from a custom tool +# [filters.my-tool] +# description = "Compact my-tool output" +# match_command = "^my-tool\\s+build" +# strip_ansi = true +# strip_lines_matching = ["^\\s*$", "^Downloading", "^Installing"] +# max_lines = 30 +# on_empty = "my-tool: ok"
CLAUDE.md
diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..413a172 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,10 @@ +<!-- rtk-instructions v2 --> +# Command output + +Command output here is condensed to save tokens, keeping every signal and +dropping costly noise. Treat it as the complete result: run commands +normally, and batch related commands into one call to avoid extra turns. +Truncated results state their recovery path in their own output. Re-run a +command as `rtk proxy <cmd>` only when its result is unusable: empty when +output was clearly expected, contradicting its exit code, or garbled. +<!-- /rtk-instructions -->
README.md
diff --git a/README.md b/README.md index a36e499..f68aadd 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ Un gestionnaire de connexions SSH minimaliste : un nom court par serveur, un TUI - Ajout en une ligne ou via formulaire dans le TUI - Import de tes hosts existants depuis `~/.ssh/config` (multi-sélection interactive ou one-liner) - Support port, clé privée, ProxyJump (qui peut référencer un autre host sssh) et tags +- VPN automatique : monte un tunnel OpenVPN (ou n'importe quelle commande) si la cible n'est pas joignable, et le démonte après la session - Export / import pour synchroniser entre machines - La connexion délègue au `ssh` système (`exec`) : agent, TTY, config… tout marche comme un ssh normal @@ -51,6 +52,8 @@ sssh vps-ovh uptime # exécute une commande distante sssh add vps-ovh debian@203.0.113.21 # ajout en une ligne sssh add api deploy@192.0.2.7:2222 -i ~/.ssh/id_deploy -J bastion -t client,prod +sssh vpn add bureau ~/vpn/bureau.ovpn # profil VPN… +sssh add nas admin@192.168.10.5 -v bureau # …monté automatiquement pour ce host sssh edit vps-ovh # formulaire d'édition sssh rm vps-ovh sssh list @@ -111,7 +114,7 @@ Pour une synchro permanente, pointe `$SSSH_CONFIG` vers un fichier partagé (dos ## Configuration -Les hosts vivent dans `~/.config/sssh/hosts.toml` (surchargeable avec `$SSSH_CONFIG`) : +Les hosts vivent dans `~/.config/sssh/hosts.toml` (ou `$XDG_CONFIG_HOME/sssh/`, surchargeable avec `$SSSH_CONFIG`) : ```toml [hosts.serveur-1] @@ -120,6 +123,7 @@ host = "192.0.2.11" port = 22 # optionnel identity = "~/.ssh/id_prod" # optionnel jump = "bastion" # optionnel — nom sssh ou [user@]host[:port] +vpn = "bureau" # optionnel — profil [vpn.bureau], voir plus bas tags = ["client", "prod"] # optionnel ``` @@ -140,6 +144,34 @@ sssh serveur-prive # → ssh -J admin@203.0.113.10 deploy@10.0.4.2 Limite d'OpenSSH : `-J` ne prend pas de clé par hop ; si un bastion demande une clé spécifique, déclare-la dans `~/.ssh/config` (`Host bastion` + `IdentityFile`). +### VPN automatique + +Pour les machines joignables seulement à travers un VPN, déclare un profil puis référence-le sur les hosts concernés : + +```sh +sssh vpn add bureau ~/vpn/bureau.ovpn # profil OpenVPN +sssh vpn add bureau ~/vpn/bureau.ovpn -auth ~/vpn/bureau.auth -check 192.168.10.1:22 +sssh add nas admin@192.168.10.5 -v bureau # ou champ « VPN » du formulaire +sssh nas +sssh vpn list / sssh vpn rm bureau +``` + +À la connexion, sssh sonde la cible en TCP (ou l'adresse `check` du profil, ou le premier hop du jump) : + +- **joignable** → connexion directe, sans toucher au VPN (déjà monté, ou inutile depuis ce réseau) ; +- **injoignable** → `sudo openvpn --config …` en arrière-plan (le mot de passe sudo et, si le `.ovpn` a `auth-user-pass`, les identifiants sont demandés dans le terminal), attente que la cible réponde, puis ssh. À la fin de la session, le tunnel est coupé via l'interface de management d'OpenVPN, sans second `sudo`. + +`-auth` pointe vers un fichier « login puis mot de passe » (deux lignes, `chmod 600`) pour éviter la saisie à chaque fois. Le CLI `openvpn` est requis (`brew install openvpn`) ; l'app OpenVPN Connect n'est pas pilotée. Les logs sont dans `~/Library/Caches/sssh/<profil>.log` (macOS) ou `~/.cache/sssh/` (Linux). + +Autre chose qu'OpenVPN (WireGuard, Tailscale…) : un profil à commandes, directement dans `hosts.toml` : + +```toml +[vpn.wg-maison] +up = "sudo wg-quick up maison" +down = "sudo wg-quick down maison" +check = "10.8.0.1:22" +``` + ### Importer depuis `~/.ssh/config` `sssh import-ssh` liste les alias concrets de ton `~/.ssh/config` qui ne sont pas encore dans sssh et te laisse cocher ceux à importer (espace pour sélectionner, `ctrl+a` pour tout prendre). Les champs supportés sont copiés : `HostName`, `User`, `Port`, `IdentityFile`, `ProxyJump`. Avec des noms en arguments, l'import est direct, sans interaction. La touche `i` dans le TUI fait la même chose.
completions/_sssh
diff --git a/completions/_sssh b/completions/_sssh index 001448d..de7f64d 100644 --- a/completions/_sssh +++ b/completions/_sssh @@ -15,6 +15,7 @@ _sssh() { 'export:Exporter hosts.toml' 'import:Importer un hosts.toml' 'import-ssh:Importer depuis ~/.ssh/config' + 'vpn:Profils VPN' 'help:Aide' 'version:Version' ) @@ -32,6 +33,9 @@ _sssh() { import|export) _files ;; + vpn) + (( CURRENT == 3 )) && _values 'action' list add rm + ;; esac }
completions/sssh.bash
diff --git a/completions/sssh.bash b/completions/sssh.bash index 1045fa1..a9d89ad 100644 --- a/completions/sssh.bash +++ b/completions/sssh.bash @@ -9,7 +9,7 @@ _sssh() { if [[ $COMP_CWORD -eq 1 ]]; then local names subcmds names="$(sssh list --names 2>/dev/null)" - subcmds="add edit rm list export import import-ssh help version" + subcmds="add edit rm list vpn export import import-ssh help version" COMPREPLY=($(compgen -W "$names $subcmds" -- "$cur")) return fi @@ -24,6 +24,11 @@ _sssh() { import|export) COMPREPLY=($(compgen -f -- "$cur")) ;; + vpn) + if [[ $COMP_CWORD -eq 2 ]]; then + COMPREPLY=($(compgen -W "list add rm" -- "$cur")) + fi + ;; esac }
completions/sssh.fish
diff --git a/completions/sssh.fish b/completions/sssh.fish index f8f7b36..5dfadcc 100644 --- a/completions/sssh.fish +++ b/completions/sssh.fish @@ -12,7 +12,11 @@ complete -c sssh -n '__fish_use_subcommand' -a list -d 'Lister les hosts' complete -c sssh -n '__fish_use_subcommand' -a export -d 'Exporter hosts.toml' complete -c sssh -n '__fish_use_subcommand' -a import -d 'Importer un hosts.toml' complete -c sssh -n '__fish_use_subcommand' -a import-ssh -d 'Importer depuis ~/.ssh/config' +complete -c sssh -n '__fish_use_subcommand' -a vpn -d 'Profils VPN' complete -c sssh -n '__fish_use_subcommand' -a help -d 'Aide' # Noms de hosts pour edit/rm complete -c sssh -n '__fish_seen_subcommand_from edit rm' -a '(sssh list --names 2>/dev/null)' + +# Sous-commandes de vpn +complete -c sssh -n '__fish_seen_subcommand_from vpn; and not __fish_seen_subcommand_from list add rm' -a 'list add rm'
internal/connect/connect.go
diff --git a/internal/connect/connect.go b/internal/connect/connect.go index 685cbe5..4bab6ae 100644 --- a/internal/connect/connect.go +++ b/internal/connect/connect.go @@ -1,23 +1,56 @@ -// Package connect lance la connexion en remplaçant le processus par ssh. +// Package connect lance la connexion ssh. package connect import ( + "errors" "fmt" "os" "os/exec" + "os/signal" "syscall" "git.neuromancer.ovh/bastien-mrq/sssh/internal/host" ) +func sshPath() (string, error) { + path, err := exec.LookPath("ssh") + if err != nil { + return "", fmt.Errorf("binaire ssh introuvable : %w", err) + } + return path, nil +} + // Exec remplace le processus courant par ssh (TTY natif, agent, etc.). // Ne revient jamais en cas de succès. func Exec(h host.Host, extra []string) error { - path, err := exec.LookPath("ssh") + path, err := sshPath() if err != nil { - return fmt.Errorf("binaire ssh introuvable : %w", err) + return err } argv := append([]string{"ssh"}, h.SSHArgs(extra...)...) fmt.Fprintf(os.Stderr, "→ %s\n", h.Describe()) return syscall.Exec(path, argv, os.Environ()) } + +// Run lance ssh en processus enfant et attend sa fin : utilisé quand sssh +// doit reprendre la main ensuite (démontage du VPN). Rend le code de sortie +// de ssh. Ctrl-C est ignoré côté sssh pour laisser ssh le gérer. +func Run(h host.Host, extra []string) (int, error) { + path, err := sshPath() + if err != nil { + return 0, err + } + cmd := exec.Command(path, h.SSHArgs(extra...)...) + cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr + fmt.Fprintf(os.Stderr, "→ %s\n", h.Describe()) + + signal.Ignore(syscall.SIGINT, syscall.SIGQUIT) + defer signal.Reset(syscall.SIGINT, syscall.SIGQUIT) + + err = cmd.Run() + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + return exitErr.ExitCode(), nil + } + return 0, err +}
internal/host/host.go
diff --git a/internal/host/host.go b/internal/host/host.go index 1d28887..e3ac381 100644 --- a/internal/host/host.go +++ b/internal/host/host.go @@ -4,6 +4,7 @@ package host import ( "errors" "fmt" + "net" "os" "path/filepath" "strconv" @@ -18,6 +19,7 @@ type Host struct { Port int `toml:"port,omitempty"` Identity string `toml:"identity,omitempty"` Jump string `toml:"jump,omitempty"` + VPN string `toml:"vpn,omitempty"` Tags []string `toml:"tags,omitempty"` } @@ -52,6 +54,15 @@ func (h Host) Target() string { return t } +// Addr rend host:port (22 par défaut), pour sonder la joignabilité. +func (h Host) Addr() string { + port := h.Port + if port == 0 { + port = 22 + } + return net.JoinHostPort(h.Host, strconv.Itoa(port)) +} + // JumpSpec rend la forme [user@]host[:port] utilisable après -J. func (h Host) JumpSpec() string { s := h.Target() @@ -83,6 +94,9 @@ func (h Host) Describe() string { if h.Port != 0 && h.Port != 22 { d += ":" + strconv.Itoa(h.Port) } + if h.VPN != "" { + d += " vpn:" + h.VPN + } if len(h.Tags) > 0 { d += " #" + strings.Join(h.Tags, " #") }
internal/store/store.go
diff --git a/internal/store/store.go b/internal/store/store.go index 2db8ab1..16ac1e5 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -1,4 +1,4 @@ -// Package store gère la persistance des hosts dans hosts.toml. +// Package store gère la persistance des hosts et profils VPN dans hosts.toml. package store import ( @@ -11,33 +11,54 @@ import ( "github.com/pelletier/go-toml/v2" "git.neuromancer.ovh/bastien-mrq/sssh/internal/host" + "git.neuromancer.ovh/bastien-mrq/sssh/internal/vpn" ) -type fileFormat struct { - Hosts map[string]host.Host `toml:"hosts"` +// File est le format de hosts.toml (aussi celui d'export/import). +type File struct { + Hosts map[string]host.Host `toml:"hosts"` + VPN map[string]vpn.Profile `toml:"vpn,omitempty"` } // Store est le contenu chargé de hosts.toml. type Store struct { path string Hosts map[string]host.Host + VPNs map[string]vpn.Profile } -// Path rend le chemin du fichier de configuration, surchargé par $SSSH_CONFIG. +// Path rend le chemin du fichier de configuration : $SSSH_CONFIG, sinon +// ~/.config/sssh/hosts.toml (ou $XDG_CONFIG_HOME). L'emplacement historique +// (os.UserConfigDir, ~/Library/Application Support sur macOS) reste utilisé +// s'il existe et que le nouveau n'existe pas. func Path() string { if p := os.Getenv("SSSH_CONFIG"); p != "" { return p } - base, err := os.UserConfigDir() - if err != nil { - base = filepath.Join(os.Getenv("HOME"), ".config") + xdg := os.Getenv("XDG_CONFIG_HOME") + if xdg == "" { + home, err := os.UserHomeDir() + if err != nil { + home = os.Getenv("HOME") + } + xdg = filepath.Join(home, ".config") + } + p := filepath.Join(xdg, "sssh", "hosts.toml") + if _, err := os.Stat(p); err == nil { + return p + } + if base, err := os.UserConfigDir(); err == nil { + legacy := filepath.Join(base, "sssh", "hosts.toml") + if _, err := os.Stat(legacy); err == nil { + return legacy + } } - return filepath.Join(base, "sssh", "hosts.toml") + return p } // Load lit hosts.toml ; un fichier absent donne un store vide. func Load() (*Store, error) { - s := &Store{path: Path(), Hosts: map[string]host.Host{}} + s := &Store{path: Path(), Hosts: map[string]host.Host{}, VPNs: map[string]vpn.Profile{}} data, err := os.ReadFile(s.path) if os.IsNotExist(err) { return s, nil @@ -45,13 +66,16 @@ func Load() (*Store, error) { if err != nil { return nil, err } - var f fileFormat + var f File if err := toml.Unmarshal(data, &f); err != nil { return nil, fmt.Errorf("%s : %w", s.path, err) } if f.Hosts != nil { s.Hosts = f.Hosts } + if f.VPN != nil { + s.VPNs = f.VPN + } return s, nil } @@ -73,7 +97,11 @@ func (s *Store) Save() error { // Marshal sérialise le store au format hosts.toml. func (s *Store) Marshal() ([]byte, error) { - return toml.Marshal(fileFormat{Hosts: s.Hosts}) + f := File{Hosts: s.Hosts} + if len(s.VPNs) > 0 { + f.VPN = s.VPNs + } + return toml.Marshal(f) } // Get rend le host nommé, avec son Name renseigné. @@ -110,6 +138,47 @@ func (s *Store) List() []host.Host { return hosts } +// VPN rend le profil VPN nommé. +func (s *Store) VPN(name string) (vpn.Profile, bool) { + p, ok := s.VPNs[name] + return p, ok +} + +// SetVPN ajoute ou remplace un profil VPN. +func (s *Store) SetVPN(name string, p vpn.Profile) { + s.VPNs[name] = p +} + +// RemoveVPN supprime un profil VPN ; rend false s'il n'existait pas. +func (s *Store) RemoveVPN(name string) bool { + if _, ok := s.VPNs[name]; !ok { + return false + } + delete(s.VPNs, name) + return true +} + +// VPNNames rend les noms de profils VPN triés. +func (s *Store) VPNNames() []string { + names := make([]string, 0, len(s.VPNs)) + for n := range s.VPNs { + names = append(names, n) + } + sort.Strings(names) + return names +} + +// HostsUsingVPN rend les noms des hosts qui référencent ce profil. +func (s *Store) HostsUsingVPN(name string) []string { + var out []string + for _, h := range s.List() { + if h.VPN == name { + out = append(out, h.Name) + } + } + return out +} + // Resolve cherche name parmi hosts : correspondance exacte d'abord, // sinon préfixe unique. En cas d'ambiguïté, l'erreur liste les candidats. func Resolve(hosts []host.Host, name string) (host.Host, error) {
internal/tui/form.go
diff --git a/internal/tui/form.go b/internal/tui/form.go index 59135dc..ae571ea 100644 --- a/internal/tui/form.go +++ b/internal/tui/form.go @@ -15,8 +15,9 @@ import ( var ErrAborted = errors.New("annulé") // HostForm ouvre le formulaire d'ajout/édition et modifie h en place. -// oldName est vide pour un ajout ; exists vérifie l'unicité du nom. -func HostForm(h *host.Host, oldName string, exists func(string) bool) error { +// oldName est vide pour un ajout ; exists vérifie l'unicité du nom ; +// vpnExists valide le nom d'un profil VPN. +func HostForm(h *host.Host, oldName string, exists, vpnExists func(string) bool) error { name := h.Name port := "" if h.Port != 0 { @@ -64,6 +65,14 @@ func HostForm(h *host.Host, oldName string, exists func(string) bool) error { }), huh.NewInput().Title("Clé privée (optionnel)").Placeholder("~/.ssh/id_ed25519").Value(&h.Identity), huh.NewInput().Title("Jump host / ProxyJump (optionnel)").Value(&h.Jump), + huh.NewInput().Title("VPN : nom d'un profil (optionnel)").Description("sssh vpn list").Value(&h.VPN). + Validate(func(s string) error { + s = strings.TrimSpace(s) + if s != "" && !vpnExists(s) { + return fmt.Errorf("profil vpn inconnu : %q (sssh vpn add)", s) + } + return nil + }), huh.NewInput().Title("Tags, séparés par des virgules (optionnel)").Value(&tags), )) @@ -79,6 +88,7 @@ func HostForm(h *host.Host, oldName string, exists func(string) bool) error { h.User = strings.TrimSpace(h.User) h.Identity = strings.TrimSpace(h.Identity) h.Jump = strings.TrimSpace(h.Jump) + h.VPN = strings.TrimSpace(h.VPN) h.Port = 0 if p := strings.TrimSpace(port); p != "" { h.Port, _ = strconv.Atoi(p)
internal/vpn/vpn.go
diff --git a/internal/vpn/vpn.go b/internal/vpn/vpn.go new file mode 100644 index 0000000..7246c07 --- /dev/null +++ b/internal/vpn/vpn.go @@ -0,0 +1,298 @@ +// Package vpn monte un tunnel (OpenVPN ou commandes custom) le temps +// d'une connexion SSH, et le démonte ensuite. +package vpn + +import ( + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "io" + "net" + "os" + "os/exec" + "os/signal" + "path/filepath" + "strings" + "time" + + "git.neuromancer.ovh/bastien-mrq/sssh/internal/host" +) + +// Profile décrit un VPN dans hosts.toml ([vpn.<nom>]). +// Soit Config (fichier .ovpn lancé avec openvpn), soit Up/Down (commandes shell). +type Profile struct { + Config string `toml:"config,omitempty"` // fichier .ovpn + Auth string `toml:"auth,omitempty"` // fichier login/mot de passe (--auth-user-pass) + Up string `toml:"up,omitempty"` // commande de montage (alternative à config) + Down string `toml:"down,omitempty"` // commande de démontage + Check string `toml:"check,omitempty"` // host:port à sonder (défaut : la cible ssh) +} + +// Validate vérifie la cohérence du profil. +func (p Profile) Validate(name string) error { + switch { + case p.Config == "" && p.Up == "": + return fmt.Errorf("profil vpn %q : il faut config (fichier .ovpn) ou up (commande)", name) + case p.Config != "" && p.Up != "": + return fmt.Errorf("profil vpn %q : config et up sont exclusifs", name) + } + return nil +} + +// Describe rend une description courte pour les listes. +func (p Profile) Describe() string { + if p.Config != "" { + return "openvpn " + p.Config + } + return "up: " + p.Up +} + +// NeedsInteractiveAuth indique qu'openvpn demandera login/mot de passe +// au terminal (auth-user-pass sans fichier, et pas de auth dans le profil). +func (p Profile) NeedsInteractiveAuth() bool { + if p.Config == "" || p.Auth != "" { + return false + } + data, err := os.ReadFile(host.ExpandTilde(p.Config)) + if err != nil { + return false + } + for _, line := range strings.Split(string(data), "\n") { + if strings.TrimSpace(line) == "auth-user-pass" { + return true + } + } + return false +} + +// Reachable teste une connexion TCP vers addr (host:port). +func Reachable(addr string, timeout time.Duration) bool { + c, err := net.DialTimeout("tcp", addr, timeout) + if err != nil { + return false + } + c.Close() + return true +} + +// Session est un tunnel monté par Start, à démonter avec Stop. +type Session struct { + name string + profile Profile + cmd *exec.Cmd // openvpn (via sudo) ; nil pour un profil up/down + done chan error + mgmt string // adresse de l'interface de management openvpn + mgmtPw string + pidFile string + LogPath string +} + +func cacheDir() (string, error) { + base, err := os.UserCacheDir() + if err != nil { + base = os.TempDir() + } + dir := filepath.Join(base, "sssh") + return dir, os.MkdirAll(dir, 0o700) +} + +func findOpenVPN() (string, error) { + if p, err := exec.LookPath("openvpn"); err == nil { + return p, nil + } + for _, p := range []string{"/opt/homebrew/sbin/openvpn", "/usr/local/sbin/openvpn", "/usr/sbin/openvpn"} { + if _, err := os.Stat(p); err == nil { + return p, nil + } + } + return "", errors.New("binaire openvpn introuvable (brew install openvpn)") +} + +func freePort() (int, error) { + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + return 0, err + } + defer l.Close() + return l.Addr().(*net.TCPAddr).Port, nil +} + +// Start monte le tunnel. Pour un profil openvpn, le processus tourne en +// arrière-plan (logs dans LogPath) ; sudo et openvpn posent leurs questions +// (mot de passe, identifiants) directement sur le terminal. +func Start(name string, p Profile) (*Session, error) { + s := &Session{name: name, profile: p} + + if p.Up != "" { + cmd := exec.Command("sh", "-c", p.Up) + cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr + if err := cmd.Run(); err != nil { + return nil, fmt.Errorf("vpn %s : commande up : %w", name, err) + } + return s, nil + } + + bin, err := findOpenVPN() + if err != nil { + return nil, err + } + config := host.ExpandTilde(p.Config) + if _, err := os.Stat(config); err != nil { + return nil, fmt.Errorf("vpn %s : %w", name, err) + } + dir, err := cacheDir() + if err != nil { + return nil, err + } + port, err := freePort() + if err != nil { + return nil, err + } + raw := make([]byte, 16) + if _, err := rand.Read(raw); err != nil { + return nil, err + } + s.mgmt = fmt.Sprintf("127.0.0.1:%d", port) + s.mgmtPw = hex.EncodeToString(raw) + s.pidFile = filepath.Join(dir, name+".pid") + s.LogPath = filepath.Join(dir, name+".log") + pwFile := filepath.Join(dir, name+".mgmt") + if err := os.WriteFile(pwFile, []byte(s.mgmtPw+"\n"), 0o600); err != nil { + return nil, err + } + _ = os.Remove(s.pidFile) + logf, err := os.OpenFile(s.LogPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600) + if err != nil { + return nil, err + } + defer logf.Close() // l'enfant garde son propre descripteur + + args := []string{ + "--config", config, + "--management", "127.0.0.1", fmt.Sprint(port), pwFile, + "--writepid", s.pidFile, + "--verb", "3", + } + if p.Auth != "" { + args = append(args, "--auth-user-pass", host.ExpandTilde(p.Auth)) + } + + var cmd *exec.Cmd + if os.Geteuid() == 0 { + cmd = exec.Command(bin, args...) + } else { + sudoArgs := append([]string{"-p", "[sssh] mot de passe sudo (openvpn) : ", bin}, args...) + cmd = exec.Command("sudo", sudoArgs...) + } + cmd.Dir = filepath.Dir(config) // chemins relatifs (ca, cert…) du .ovpn + cmd.Stdin = os.Stdin + cmd.Stdout, cmd.Stderr = logf, logf + if err := cmd.Start(); err != nil { + return nil, fmt.Errorf("vpn %s : %w", name, err) + } + s.cmd = cmd + s.done = make(chan error, 1) + go func() { s.done <- cmd.Wait() }() + return s, nil +} + +// WaitReachable attend que addr réponde en TCP. Échoue si openvpn s'arrête +// avant, si le délai expire, ou sur Ctrl-C. +func (s *Session) WaitReachable(addr string, timeout time.Duration) error { + sig := make(chan os.Signal, 1) + signal.Notify(sig, os.Interrupt) + defer signal.Stop(sig) + + deadline := time.Now().Add(timeout) + tick := time.NewTicker(500 * time.Millisecond) + defer tick.Stop() + for { + select { + case err := <-s.done: + s.done <- err + return fmt.Errorf("vpn %s : openvpn s'est arrêté (%v)\n%s", s.name, err, s.LogTail(8)) + case <-sig: + return errors.New("annulé") + case <-tick.C: + if Reachable(addr, time.Second) { + return nil + } + if time.Now().After(deadline) { + return fmt.Errorf("vpn %s : %s toujours injoignable après %s\n%s", s.name, addr, timeout, s.LogTail(8)) + } + } + } +} + +// Stop démonte le tunnel : commande down, ou SIGTERM à openvpn via son +// interface de management (pas besoin de sudo), avec repli sur sudo kill. +func (s *Session) Stop() error { + if s.cmd == nil { + if s.profile.Down == "" { + return nil + } + cmd := exec.Command("sh", "-c", s.profile.Down) + cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr + if err := cmd.Run(); err != nil { + return fmt.Errorf("vpn %s : commande down : %w", s.name, err) + } + return nil + } + + select { + case err := <-s.done: + s.done <- err + return nil // déjà arrêté + default: + } + + if err := s.managementSignal("SIGTERM"); err != nil { + if pid, e := os.ReadFile(s.pidFile); e == nil { + kill := exec.Command("sudo", "-p", "[sssh] mot de passe sudo (arrêt openvpn) : ", + "kill", "-TERM", strings.TrimSpace(string(pid))) + kill.Stdin, kill.Stdout, kill.Stderr = os.Stdin, os.Stdout, os.Stderr + _ = kill.Run() + } + } + + select { + case <-s.done: + return nil + case <-time.After(15 * time.Second): + return fmt.Errorf("vpn %s : openvpn ne s'est pas arrêté (voir %s)", s.name, s.LogPath) + } +} + +func (s *Session) managementSignal(sig string) error { + c, err := net.DialTimeout("tcp", s.mgmt, 2*time.Second) + if err != nil { + return err + } + defer c.Close() + _ = c.SetDeadline(time.Now().Add(5 * time.Second)) + if _, err := fmt.Fprintf(c, "%s\nsignal %s\n", s.mgmtPw, sig); err != nil { + return err + } + out, _ := io.ReadAll(c) + if !strings.Contains(string(out), "SUCCESS: signal") { + return fmt.Errorf("management openvpn : réponse inattendue") + } + return nil +} + +// LogTail rend les n dernières lignes du log openvpn, indentées. +func (s *Session) LogTail(n int) string { + if s.LogPath == "" { + return "" + } + data, err := os.ReadFile(s.LogPath) + if err != nil { + return "" + } + lines := strings.Split(strings.TrimRight(string(data), "\n"), "\n") + if len(lines) > n { + lines = lines[len(lines)-n:] + } + return " " + strings.Join(lines, "\n ") +}
main.go
diff --git a/main.go b/main.go index 297c0f8..af85852 100644 --- a/main.go +++ b/main.go @@ -10,8 +10,10 @@ import ( "flag" "fmt" "os" + "path/filepath" "strings" "text/tabwriter" + "time" "github.com/pelletier/go-toml/v2" @@ -20,19 +22,23 @@ import ( "git.neuromancer.ovh/bastien-mrq/sssh/internal/sshconf" "git.neuromancer.ovh/bastien-mrq/sssh/internal/store" "git.neuromancer.ovh/bastien-mrq/sssh/internal/tui" + "git.neuromancer.ovh/bastien-mrq/sssh/internal/vpn" ) -const version = "0.1.0" +const version = "0.2.0" const usage = `sssh — simple-ssh Usage : sssh ouvre le TUI de sélection sssh <nom> [cmd...] se connecte au host (préfixe unique accepté) - sssh add <nom> <[user@]host[:port]> [-p port] [-i clé] [-J jump] [-t tags] + sssh add <nom> <[user@]host[:port]> [-p port] [-i clé] [-J jump] [-v vpn] [-t tags] sssh edit <nom> édite un host (formulaire) sssh rm <nom> supprime un host sssh list liste les hosts (--names : noms seuls) + sssh vpn list profils VPN + sssh vpn add <nom> <fichier.ovpn> [-auth fichier] [-check host:port] + sssh vpn rm <nom> sssh export [fichier] exporte hosts.toml (stdout par défaut) sssh import <fichier> importe en fusionnant (--force pour écraser) sssh import-ssh [noms...] importe des hosts depuis ~/.ssh/config @@ -61,6 +67,8 @@ func run(args []string) error { return cmdEdit(args[1:]) case "list", "ls": return cmdList(args[1:]) + case "vpn": + return cmdVPN(args[1:]) case "export": return cmdExport(args[1:]) case "import": @@ -120,6 +128,71 @@ func resolveJump(st *store.Store, h *host.Host) { h.Jump = strings.Join(chain, ",") } +// probeAddr rend l'adresse à sonder pour savoir si le VPN est nécessaire : +// le check du profil, sinon le premier hop du jump, sinon la cible. +func probeAddr(h host.Host, p vpn.Profile) string { + if p.Check != "" { + return p.Check + } + if h.Jump != "" { + first := strings.SplitN(h.Jump, ",", 2)[0] + if hop, err := host.Parse("", first); err == nil { + return hop.Addr() + } + } + return h.Addr() +} + +// connectHost lance ssh, en montant d'abord le VPN du host si la cible +// n'est pas joignable. Sans VPN, exec remplace le processus ; avec VPN, +// ssh tourne en enfant et le tunnel est démonté à la fin. +func connectHost(st *store.Store, h host.Host, extra []string) error { + resolveJump(st, &h) + if h.VPN == "" { + return connect.Exec(h, extra) + } + + p, ok := st.VPN(h.VPN) + if !ok { + return fmt.Errorf("profil vpn inconnu : %q (sssh vpn list)", h.VPN) + } + if err := p.Validate(h.VPN); err != nil { + return err + } + addr := probeAddr(h, p) + if vpn.Reachable(addr, 1500*time.Millisecond) { + return connect.Exec(h, extra) // déjà joignable : VPN actif ou inutile + } + + fmt.Fprintf(os.Stderr, "⇅ vpn %s : %s injoignable, montage du tunnel… (Ctrl-C pour annuler)\n", h.VPN, addr) + if p.NeedsInteractiveAuth() { + fmt.Fprintln(os.Stderr, " openvpn va demander identifiant et mot de passe") + } + s, err := vpn.Start(h.VPN, p) + if err != nil { + return err + } + if err := s.WaitReachable(addr, 2*time.Minute); err != nil { + _ = s.Stop() + return err + } + fmt.Fprintf(os.Stderr, "⇅ vpn %s : actif\n", h.VPN) + + code, runErr := connect.Run(h, extra) + + fmt.Fprintf(os.Stderr, "⇅ vpn %s : démontage\n", h.VPN) + if err := s.Stop(); err != nil { + fmt.Fprintln(os.Stderr, "sssh :", err) + } + if runErr != nil { + return runErr + } + if code != 0 { + os.Exit(code) + } + return nil +} + func cmdConnect(name string, extra []string) error { st, err := store.Load() if err != nil { @@ -129,8 +202,7 @@ func cmdConnect(name string, extra []string) error { if err != nil { return err } - resolveJump(st, &h) - return connect.Exec(h, extra) + return connectHost(st, h, extra) } func runTUI() error { @@ -149,9 +221,7 @@ func runTUI() error { return nil case tui.ActionConnect: - h := res.Host - resolveJump(st, &h) - return connect.Exec(h, nil) + return connectHost(st, res.Host, nil) case tui.ActionAdd: h := host.Host{} @@ -185,7 +255,8 @@ func runTUI() error { // Une annulation du formulaire n'est pas une erreur. func editForm(st *store.Store, h *host.Host, oldName string) error { exists := func(name string) bool { _, ok := st.Get(name); return ok } - if err := tui.HostForm(h, oldName, exists); err != nil { + vpnExists := func(name string) bool { _, ok := st.VPN(name); return ok } + if err := tui.HostForm(h, oldName, exists, vpnExists); err != nil { if errors.Is(err, tui.ErrAborted) { return nil } @@ -200,7 +271,7 @@ func editForm(st *store.Store, h *host.Host, oldName string) error { func cmdAdd(args []string) error { if len(args) < 2 { - return errors.New("usage : sssh add <nom> <[user@]host[:port]> [-p port] [-i clé] [-J jump] [-t tags]") + return errors.New("usage : sssh add <nom> <[user@]host[:port]> [-p port] [-i clé] [-J jump] [-v vpn] [-t tags]") } name, target := args[0], args[1] @@ -208,6 +279,7 @@ func cmdAdd(args []string) error { port := fs.Int("p", 0, "port") identity := fs.String("i", "", "clé privée") jump := fs.String("J", "", "jump host (ProxyJump)") + vpnName := fs.String("v", "", "profil VPN (sssh vpn list)") tags := fs.String("t", "", "tags séparés par des virgules") if err := fs.Parse(args[2:]); err != nil { return err @@ -220,6 +292,11 @@ func cmdAdd(args []string) error { if _, ok := st.Get(name); ok { return fmt.Errorf("%q existe déjà (sssh edit %s pour le modifier)", name, name) } + if *vpnName != "" { + if _, ok := st.VPN(*vpnName); !ok { + return fmt.Errorf("profil vpn inconnu : %q (sssh vpn add %s <fichier.ovpn>)", *vpnName, *vpnName) + } + } h, err := host.Parse(name, target) if err != nil { @@ -230,6 +307,7 @@ func cmdAdd(args []string) error { } h.Identity = *identity h.Jump = *jump + h.VPN = *vpnName for _, t := range strings.Split(*tags, ",") { if t = strings.TrimSpace(t); t != "" { h.Tags = append(h.Tags, t) @@ -299,80 +377,106 @@ func cmdList(args []string) error { return nil } w := tabwriter.NewWriter(os.Stdout, 2, 4, 2, ' ', 0) - fmt.Fprintln(w, "NOM\tCIBLE\tPORT\tTAGS") + fmt.Fprintln(w, "NOM\tCIBLE\tPORT\tJUMP\tVPN\tTAGS") for _, h := range hosts { port := "" if h.Port != 0 && h.Port != 22 { port = fmt.Sprint(h.Port) } - fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", - h.Name, h.Target(), port, strings.Join(h.Tags, ",")) + fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n", + h.Name, h.Target(), port, h.Jump, h.VPN, strings.Join(h.Tags, ",")) } return w.Flush() } -// importSSHConfig ouvre la multi-sélection sur candidates et enregistre -// les hosts choisis ; rend le nombre importé (annulation = 0, sans erreur). -func importSSHConfig(st *store.Store, candidates []host.Host) (int, error) { - selected, err := tui.SelectSSHConfigHosts(candidates) - if err != nil { - if errors.Is(err, tui.ErrAborted) { - return 0, nil - } - return 0, err - } - for _, h := range selected { - st.Set(h) - } - if len(selected) == 0 { - return 0, nil +func cmdVPN(args []string) error { + if len(args) == 0 { + args = []string{"list"} } - return len(selected), st.Save() -} - -func cmdImportSSH(args []string) error { st, err := store.Load() if err != nil { return err } - // Sans argument : sélection interactive parmi les hosts non enregistrés. - if len(args) == 0 { - candidates := sshConfigCandidates(st) - if len(candidates) == 0 { - fmt.Println("Rien à importer : aucun host de ~/.ssh/config n'est absent de sssh.") + switch args[0] { + case "list", "ls": + names := st.VPNNames() + if len(names) == 0 { + fmt.Println("Aucun profil VPN. Ajoute-en un : sssh vpn add <nom> <fichier.ovpn>") return nil } - n, err := importSSHConfig(st, candidates) - if err != nil { + w := tabwriter.NewWriter(os.Stdout, 2, 4, 2, ' ', 0) + fmt.Fprintln(w, "NOM\tCONFIG\tCHECK\tHOSTS") + for _, name := range names { + p := st.VPNs[name] + fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", name, p.Describe(), p.Check, strings.Join(st.HostsUsingVPN(name), ",")) + } + return w.Flush() + + case "add": + if len(args) < 3 { + return errors.New("usage : sssh vpn add <nom> <fichier.ovpn> [-auth fichier] [-check host:port]") + } + name, config := args[1], args[2] + fs := flag.NewFlagSet("vpn add", flag.ContinueOnError) + auth := fs.String("auth", "", "fichier login/mot de passe (--auth-user-pass)") + check := fs.String("check", "", "host:port à sonder pour savoir si le VPN est actif") + if err := fs.Parse(args[3:]); err != nil { return err } - fmt.Printf("✓ %d importés depuis ~/.ssh/config\n", n) + if _, ok := st.VPN(name); ok { + return fmt.Errorf("profil vpn %q existe déjà (sssh vpn rm %s d'abord)", name, name) + } + config = absUnlessTilde(config) + if _, err := os.Stat(host.ExpandTilde(config)); err != nil { + return fmt.Errorf("fichier .ovpn : %w", err) + } + p := vpn.Profile{Config: config, Check: *check} + if *auth != "" { + p.Auth = absUnlessTilde(*auth) + if _, err := os.Stat(host.ExpandTilde(p.Auth)); err != nil { + return fmt.Errorf("fichier auth : %w", err) + } + } + st.SetVPN(name, p) + if err := st.Save(); err != nil { + return err + } + fmt.Printf("✓ profil vpn %s ajouté (%s)\n associe-le à un host : sssh add <nom> <user@host> -v %s\n", name, p.Describe(), name) return nil - } - byName := map[string]host.Host{} - for _, h := range sshconf.Hosts() { - byName[h.Name] = h - } - added, skipped := 0, 0 - for _, name := range args { - h, ok := byName[name] - if !ok { - return fmt.Errorf("host absent de ~/.ssh/config : %q", name) + case "rm", "remove": + if len(args) != 2 { + return errors.New("usage : sssh vpn rm <nom>") } - if _, exists := st.Get(name); exists { - skipped++ - continue + name := args[1] + if used := st.HostsUsingVPN(name); len(used) > 0 { + return fmt.Errorf("profil vpn %q utilisé par : %s", name, strings.Join(used, ", ")) } - st.Set(h) - added++ + if !st.RemoveVPN(name) { + return fmt.Errorf("profil vpn inconnu : %q", name) + } + if err := st.Save(); err != nil { + return err + } + fmt.Printf("✓ profil vpn %s supprimé\n", name) + return nil + + default: + return fmt.Errorf("sssh vpn : sous-commande inconnue %q (list, add, rm)", args[0]) } - if err := st.Save(); err != nil { - return err +} + +// absUnlessTilde rend un chemin absolu, sauf s'il commence par ~ (gardé +// tel quel pour rester portable entre machines). +func absUnlessTilde(p string) string { + if strings.HasPrefix(p, "~") { + return p } - fmt.Printf("✓ %d importés, %d ignorés (déjà enregistrés)\n", added, skipped) - return nil + if abs, err := filepath.Abs(p); err == nil { + return abs + } + return p } func cmdExport(args []string) error { @@ -413,9 +517,7 @@ func cmdImport(args []string) error { if err != nil { return err } - var in struct { - Hosts map[string]host.Host `toml:"hosts"` - } + var in store.File if err := toml.Unmarshal(data, &in); err != nil { return fmt.Errorf("%s : %w", path, err) } @@ -434,9 +536,85 @@ func cmdImport(args []string) error { st.Set(h) added++ } + vpnAdded := 0 + for name, p := range in.VPN { + if _, ok := st.VPN(name); ok && !force { + continue + } + st.SetVPN(name, p) + vpnAdded++ + } if err := st.Save(); err != nil { return err } - fmt.Printf("✓ %d importés, %d ignorés (déjà présents, --force pour écraser)\n", added, skipped) + fmt.Printf("✓ %d importés, %d ignorés (déjà présents, --force pour écraser)", added, skipped) + if vpnAdded > 0 { + fmt.Printf(", %d profils vpn", vpnAdded) + } + fmt.Println() + return nil +} + +// importSSHConfig ouvre la multi-sélection sur candidates et enregistre +// les hosts choisis ; rend le nombre importé (annulation = 0, sans erreur). +func importSSHConfig(st *store.Store, candidates []host.Host) (int, error) { + selected, err := tui.SelectSSHConfigHosts(candidates) + if err != nil { + if errors.Is(err, tui.ErrAborted) { + return 0, nil + } + return 0, err + } + for _, h := range selected { + st.Set(h) + } + if len(selected) == 0 { + return 0, nil + } + return len(selected), st.Save() +} + +func cmdImportSSH(args []string) error { + st, err := store.Load() + if err != nil { + return err + } + + // Sans argument : sélection interactive parmi les hosts non enregistrés. + if len(args) == 0 { + candidates := sshConfigCandidates(st) + if len(candidates) == 0 { + fmt.Println("Rien à importer : aucun host de ~/.ssh/config n'est absent de sssh.") + return nil + } + n, err := importSSHConfig(st, candidates) + if err != nil { + return err + } + fmt.Printf("✓ %d importés depuis ~/.ssh/config\n", n) + return nil + } + + byName := map[string]host.Host{} + for _, h := range sshconf.Hosts() { + byName[h.Name] = h + } + added, skipped := 0, 0 + for _, name := range args { + h, ok := byName[name] + if !ok { + return fmt.Errorf("host absent de ~/.ssh/config : %q", name) + } + if _, exists := st.Get(name); exists { + skipped++ + continue + } + st.Set(h) + added++ + } + if err := st.Save(); err != nil { + return err + } + fmt.Printf("✓ %d importés, %d ignorés (déjà enregistrés)\n", added, skipped) return nil }