build: Makefile (make install = binaire + complétions, version via ldflags)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
19 fichiers modifiés
+1564 −349
A
Makefile
+24 −0
M
README.md
+37 −10
M
go.mod
+1 −1
M
internal/connect/connect.go
+57 −12
A
internal/connect/connect_test.go
+85 −0
A
internal/connect/jumps.go
+74 −0
A
internal/connect/jumps_test.go
+55 −0
A
internal/connect/options.go
+88 −0
A
internal/connect/options_test.go
+109 −0
A
internal/process/process.go
+50 −0
A
internal/process/process_test.go
+22 −0
M
internal/vpn/keychain.go
+23 −7
A
internal/vpn/lock.go
+40 −0
M
internal/vpn/vpn.go
+368 −238
A
internal/vpn/vpn_test.go
+271 −0
M
main.go
+87 −81
A
main_test.go
+80 −0
A
route.go
+60 −0
A
route_test.go
+33 −0
Makefile
@@ -0,0 +1,24 @@
+BIN ?= $(HOME)/.local/bin
+VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)
+
+.PHONY: build install completions test clean
+
+build: ## compile ./sssh
+ go build -ldflags "-X main.version=$(VERSION)" -o sssh .
+
+install: ## installe le binaire dans $(BIN) + la complétion fish
+ mkdir -p $(BIN)
+ go build -ldflags "-X main.version=$(VERSION)" -o $(BIN)/sssh .
+ $(MAKE) completions
+ @echo "✓ sssh $(VERSION) installé dans $(BIN)"
+
+completions: ## copie les complétions pour les shells présents
+ @if [ -d $(HOME)/.config/fish ]; then \
+ mkdir -p $(HOME)/.config/fish/completions && cp completions/sssh.fish $(HOME)/.config/fish/completions/; fi
+ @if [ -d $(HOME)/.zsh/completions ]; then cp completions/_sssh $(HOME)/.zsh/completions/; fi
+
+test: ## vet + build
+ go vet ./... && go build ./...
+
+clean:
+ rm -f sssh
README.md
@@ -7,11 +7,12 @@ Un gestionnaire de connexions SSH minimaliste : un nom court par serveur, un TUI
## Fonctionnalités
- `sssh <nom>` se connecte directement — un préfixe unique suffit (`sssh ino` → `inoval`)
+- `sssh <nom> -f 80` ouvre un tunnel SSH sur un port local disponible
- `sssh` sans argument ouvre un TUI avec filtre instantané
- 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
+- VPN supervisé : monte les profils de la cible et des bastions avant SSH, puis les 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
@@ -20,10 +21,11 @@ Un gestionnaire de connexions SSH minimaliste : un nom court par serveur, un TUI
```sh
git clone ssh://git@git.neuromancer.ovh:2222/bastien-mrq/sssh.git
cd sssh
-go build -o sssh .
-mv sssh ~/.local/bin/ # ou n'importe où dans ton PATH
+make install # binaire dans ~/.local/bin + complétion fish/zsh si présentes
```
+Mise à jour : `git pull && make install`. Sans make : `go build -o ~/.local/bin/sssh .`
+
### Complétion shell
```sh
@@ -65,6 +67,21 @@ sssh import-ssh # importe depuis ~/.ssh/config (interacti
sssh import-ssh bastion vps # importe ces hosts-là directement
```
+## Forward de ports
+
+```sh
+sssh filab -f 80 # port local libre → 127.0.0.1:80 sur filab
+sssh filab -f 80 -f 5432 # plusieurs tunnels dans la même connexion
+sssh filab --forward 80 # forme longue
+sssh filab -f 80 uptime # tunnel pendant la commande distante
+```
+
+sssh affiche l'adresse locale choisie, par exemple `127.0.0.1:49152` : pour un service HTTP, ouvre `http://127.0.0.1:49152`. Le port distant est joint depuis le serveur SSH final, y compris en passant par les bastions et leurs profils VPN. L'écoute locale est limitée à `127.0.0.1`, sans exposition sur le réseau local ni besoin de sudo pour le port 80.
+
+Sans commande distante, la connexion reste au premier plan sans shell ; `Ctrl-C` ferme le tunnel. Les options `-f` doivent précéder la commande distante ; ses propres arguments restent inchangés (`sssh filab tail -f /tmp/log`). `--` termine les options sssh.
+
+Le message affiche le tunnel demandé, pas une confirmation que le service distant répond. Si le port local est pris entre sa sélection et le lancement d'OpenSSH, SSH échoue explicitement (`ExitOnForwardFailure`) : relance la commande pour choisir un autre port.
+
## Export, import et synchronisation
`sssh export` sort l'intégralité de tes hosts au format `hosts.toml` — le même format que le fichier de config, donc un export est directement réutilisable :
@@ -133,16 +150,16 @@ C'est un simple fichier : pour synchroniser deux machines, copie-le, ou versionn
Le champ `jump` (option `-J` de `sssh add`, champ « Jump host » du formulaire) accepte :
-- le **nom d'un autre host sssh** : sa cible réelle (user, IP, port) est utilisée, et si ce host a lui-même un `jump`, la chaîne complète est construite (`ssh -J hop1,hop2 cible`) ;
+- le **nom d'un autre host sssh** : sa cible, son utilisateur, son port et sa clé privée sont conservés. Si ce host a lui-même un `jump`, la chaîne complète est construite (`ssh -J hop1,hop2 cible`) ;
- une **spécification ssh brute** `[user@]host[:port]`, passée telle quelle.
```sh
sssh add bastion admin@203.0.113.10
sssh add serveur-prive deploy@10.0.4.2 -J bastion
-sssh serveur-prive # → ssh -J admin@203.0.113.10 deploy@10.0.4.2
+sssh serveur-prive # chaîne via bastion ; ses paramètres SSH sont conservés
```
-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`).
+sssh génère une configuration SSH temporaire privée pour les bastions enregistrés, puis la supprime à la fin de la connexion. Les règles de `~/.ssh/config` et de `/etc/ssh/ssh_config` restent incluses. Les cycles sont refusés explicitement. Les listes de jumps séparés par des virgules peuvent mélanger alias sssh et spécifications SSH brutes.
### VPN automatique
@@ -156,12 +173,17 @@ sssh nas
sssh vpn list / sssh vpn rm bureau / sssh vpn auth bureau --forget
```
-À la connexion, sssh sonde la cible en TCP (ou l'adresse `check` du profil, ou le premier hop du jump) :
+À la connexion, sssh résout tous les profils VPN de la chaîne, du premier bastion à la cible, et monte chaque profil une seule fois. Un profil déclaré est obligatoire : une cible déjà joignable en TCP ne permet pas de le contourner, et un VPN lancé par une autre application n'est pas repris implicitement.
+
+Pour OpenVPN, les identifiants interactifs et l'autorisation `sudo` sont demandés avant les délais de connexion. sssh attend ensuite l'état `CONNECTED,SUCCESS` du canal de management. Le champ `check`, facultatif, est un contrôle TCP supplémentaire après cette activation. Une perte du VPN ou du canal de management interrompt SSH. Les profils sont démontés dans l'ordre inverse, y compris après une erreur ou Ctrl-C.
+
+**Sessions simultanées.** Un verrou par profil interdit deux sessions sssh utilisant le même VPN : la seconde échoue avec un message explicite. Il faut terminer la première avant de réessayer. Les fichiers de session et les logs sont isolés. Le verrou se libère automatiquement à la fin du processus ; les fichiers `.lock` restent sur disque et ne doivent pas être supprimés pendant une session.
-- **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`.
+**Management.** OpenVPN se connecte à un socket Unix situé dans un répertoire aléatoire privé (`0700`, socket `0600`). Il quitte aussi si la connexion de management disparaît, y compris si sssh est tué. Aucun port TCP de management ni fichier PID partagé n'est utilisé. Le profil `.ovpn` doit rester au premier plan et ne pas redéfinir le management, les logs ou le PID ; les directives incompatibles (`daemon`, `management*`, `config`, `log`, `log-append`, `writepid`) sont refusées. Utilise des profils de confiance : OpenVPN les exécute avec les droits root.
-**Identifiants.** Si le `.ovpn` contient `auth-user-pass`, `sssh vpn auth bureau` demande login et mot de passe (saisie masquée) et les range dans le trousseau système : Keychain sur macOS (`security`), libsecret sur Linux (`secret-tool`). À la connexion, sssh les lit et les transmet à OpenVPN par son interface de management (`--management-query-passwords`) : ils ne sont jamais écrits sur le disque ni passés en ligne de commande. `sssh vpn auth bureau --forget` les retire. Sans trousseau, `-auth fichier` (login puis mot de passe, deux lignes, `chmod 600`) reste possible. 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).
+**Identifiants.** `sssh vpn auth bureau` demande login et mot de passe (saisie masquée) et les range dans le trousseau : Keychain sur macOS (`security`), libsecret sur Linux (`secret-tool`). Les mots de passe du trousseau ou saisis pour une session sont transmis via le socket, sans fichier temporaire ni argument de processus, avec `auth-nocache`. Sans trousseau, `-auth fichier` reste possible (login puis mot de passe, deux lignes, permissions `600` exigées). Sans `auth` configuré, un `.ovpn` contenant `auth-user-pass` déclenche une saisie pour la session. Les challenges MFA et demandes de secrets supplémentaires ne sont pas gérés : la connexion échoue explicitement. `sssh vpn auth bureau --forget` retire les identifiants enregistrés.
+
+Le CLI `openvpn` est requis (`brew install openvpn`) ; l'app OpenVPN Connect n'est pas pilotée. Les logs sont conservés dans `~/Library/Caches/sssh/<profil>-<session>/openvpn.log` (macOS) ou `~/.cache/sssh/<profil>-<session>/openvpn.log` (Linux, ou `$XDG_CACHE_HOME`). Le chemin est indiqué en cas d'erreur. Les noms de profils acceptent lettres, chiffres, `_`, `-` et `.` et commencent par une lettre ou un chiffre.
Autre chose qu'OpenVPN (WireGuard, Tailscale…) : un profil à commandes, directement dans `hosts.toml` :
@@ -172,6 +194,10 @@ down = "sudo wg-quick down maison"
check = "10.8.0.1:22"
```
+Pour ces profils, `down` est obligatoire ; il doit tolérer un montage partiel, car il est exécuté même si `up` échoue ou est interrompu. La commande `up` doit revenir uniquement lorsque le VPN est prêt et retourner un code non nul en cas d'échec. Contrairement à OpenVPN, ces commandes ne fournissent pas de notifications d'état pendant SSH. Le contrôle TCP facultatif ne prouve pas le chemin réseau.
+
+Cette supervision vérifie l'état OpenVPN et ferme SSH en cas de perte ; elle n'installe pas de pare-feu coupe-circuit et ne vérifie pas que chaque destination est routée dans le VPN. Les routes restent définies par le profil VPN.
+
### 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.
@@ -182,6 +208,7 @@ check = "10.8.0.1:22"
```sh
go build ./...
+go test ./...
go vet ./...
```
go.mod
@@ -9,6 +9,7 @@ require (
github.com/charmbracelet/lipgloss v1.1.0
github.com/kevinburke/ssh_config v1.6.0
github.com/pelletier/go-toml/v2 v2.4.3
+ golang.org/x/sys v0.38.0
)
require (
@@ -36,6 +37,5 @@ require (
github.com/rivo/uniseg v0.4.7 // indirect
github.com/sahilm/fuzzy v0.1.1 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
- golang.org/x/sys v0.38.0 // indirect
golang.org/x/text v0.23.0 // indirect
)
internal/connect/connect.go
@@ -2,12 +2,14 @@
package connect
import (
+ "context"
"errors"
"fmt"
"os"
"os/exec"
"os/signal"
"syscall"
+ "time"
"git.neuromancer.ovh/bastien-mrq/sssh/internal/host"
)
@@ -22,35 +24,78 @@ func sshPath() (string, error) {
// 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 {
+func Exec(h host.Host, opts Options) error {
path, err := sshPath()
if err != nil {
return err
}
- argv := append([]string{"ssh"}, h.SSHArgs(extra...)...)
+ args, release, err := opts.sshArgs(h, os.Stderr)
+ if err != nil {
+ return err
+ }
+ argv := append([]string{"ssh"}, args...)
fmt.Fprintf(os.Stderr, "→ %s\n", h.Describe())
+ release()
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) {
+// de ssh. Les signaux sont transmis à ssh pour permettre ensuite le nettoyage.
+func Run(h host.Host, opts Options) (int, error) {
+ ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGHUP)
+ defer stop()
+ return RunContext(ctx, h, opts)
+}
+
+// RunContext interrompt SSH si le VPN disparaît ou si l'utilisateur annule.
+// SSH garde le terminal ; on évite un groupe séparé qui casserait son TTY.
+func RunContext(ctx context.Context, h host.Host, opts Options) (int, error) {
+ if err := ctx.Err(); err != nil {
+ return 0, err
+ }
path, err := sshPath()
if err != nil {
return 0, err
}
- cmd := exec.Command(path, h.SSHArgs(extra...)...)
+ args, release, err := opts.sshArgs(h, os.Stderr)
+ if err != nil {
+ return 0, err
+ }
+ defer release()
+ cmd := exec.Command(path, args...)
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()
+ release()
+ if err := cmd.Start(); err != nil {
+ return 0, err
+ }
+ done := make(chan error, 1)
+ go func() { done <- cmd.Wait() }()
+ select {
+ case err = <-done:
+ case <-ctx.Done():
+ _ = cmd.Process.Signal(syscall.SIGTERM)
+ select {
+ case err = <-done:
+ case <-time.After(3 * time.Second):
+ _ = cmd.Process.Kill()
+ err = <-done
+ }
+ }
var exitErr *exec.ExitError
+ code := 0
if errors.As(err, &exitErr) {
- return exitErr.ExitCode(), nil
+ code = exitErr.ExitCode()
+ if code < 0 {
+ if status, ok := exitErr.Sys().(syscall.WaitStatus); ok && status.Signaled() {
+ code = 128 + int(status.Signal())
+ }
+ }
+ err = nil
+ }
+ if ctx.Err() != nil {
+ return code, ctx.Err()
}
- return 0, err
+ return code, err
}
internal/connect/connect_test.go
@@ -0,0 +1,85 @@
+package connect
+
+import (
+ "context"
+ "errors"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "syscall"
+ "testing"
+ "time"
+
+ "git.neuromancer.ovh/bastien-mrq/sssh/internal/host"
+)
+
+func TestRunExitCode(t *testing.T) {
+ dir := t.TempDir()
+ if err := os.WriteFile(filepath.Join(dir, "ssh"), []byte("#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$SSSH_TEST_ARGS\"\nexit 7\n"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
+ argsPath := filepath.Join(dir, "args")
+ t.Setenv("SSSH_TEST_ARGS", argsPath)
+ code, err := Run(host.Host{Name: "filab", Host: "example.invalid"}, Options{Forwards: []int{80}})
+ if err != nil || code != 7 {
+ t.Fatalf("exit = %d, %v", code, err)
+ }
+ data, err := os.ReadFile(argsPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ args := strings.Split(strings.TrimSpace(string(data)), "\n")
+ if args[len(args)-1] != "example.invalid" || !strings.Contains(string(data), ":127.0.0.1:80\n") {
+ t.Fatalf("invalid SSH arguments: %q", args)
+ }
+}
+
+// Le signal vise uniquement le parent : il doit atteindre SSH, puis Run
+// doit revenir afin que l'appelant puisse démonter le VPN.
+func TestRunSignal(t *testing.T) {
+ if os.Getenv("SSSH_TEST_SIGNAL_CHILD") == "1" {
+ code, err := Run(host.Host{Host: "example.invalid"}, Options{Forwards: []int{80}})
+ if !errors.Is(err, context.Canceled) || code != 42 {
+ os.Exit(1)
+ }
+ os.Exit(0)
+ }
+ dir := t.TempDir()
+ ready := filepath.Join(dir, "ready")
+ if err := os.WriteFile(filepath.Join(dir, "ssh"), []byte("#!/bin/sh\ntrap 'exit 42' TERM\n: > \"$SSSH_TEST_READY\"\nwhile :; do :; done\n"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ cmd := exec.Command(os.Args[0], "-test.run=^TestRunSignal$")
+ cmd.Env = append(os.Environ(), "SSSH_TEST_SIGNAL_CHILD=1", "SSSH_TEST_READY="+ready, "PATH="+dir+string(os.PathListSeparator)+os.Getenv("PATH"))
+ // Le groupe dédié permet le nettoyage de tous les enfants si le test échoue.
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
+ if err := cmd.Start(); err != nil {
+ t.Fatal(err)
+ }
+ defer syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
+ done := make(chan error, 1)
+ go func() { done <- cmd.Wait() }()
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ if _, err := os.Stat(ready); err == nil {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("SSH child did not become ready")
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ if err := cmd.Process.Signal(syscall.SIGTERM); err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatalf("signal was not handled correctly: %v", err)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("Run did not return after SIGTERM")
+ }
+}
internal/connect/jumps.go
@@ -0,0 +1,74 @@
+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) + `"`
+}
internal/connect/jumps_test.go
@@ -0,0 +1,55 @@
+package connect
+
+import (
+ "git.neuromancer.ovh/bastien-mrq/sssh/internal/host"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestJumpConfig(t *testing.T) {
+ ssh, err := exec.LookPath("ssh")
+ if err != nil {
+ t.Skip("OpenSSH unavailable")
+ }
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ if err := os.Mkdir(filepath.Join(home, ".ssh"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(home, ".ssh", "config"), []byte("Host bastion\n ServerAliveInterval 17\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ config, cleanup, err := JumpConfig([]host.Host{{Name: "bastion", Host: "10.0.0.1", User: "alice", Port: 2222, Identity: "~/key with spaces"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer cleanup()
+ info, err := os.Stat(config)
+ if err != nil || info.Mode().Perm() != 0600 {
+ t.Fatalf("config permissions: %v", err)
+ }
+ out, err := exec.Command(ssh, "-G", "-F", config, "bastion").Output()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, want := range []string{"hostname 10.0.0.1", "user alice", "port 2222", "identityfile " + home + "/key with spaces", "serveraliveinterval 17"} {
+ if !strings.Contains(string(out), want) {
+ t.Errorf("missing %q", want)
+ }
+ }
+ cleanup()
+ if _, err := os.Stat(config); !os.IsNotExist(err) {
+ t.Fatalf("config not removed: %v", err)
+ }
+}
+func TestJumpConfigRejectsInjection(t *testing.T) {
+ for _, h := range []host.Host{{Name: "*", Host: "example"}, {Name: "safe", Host: "example\nProxyCommand bad"}, {Name: "safe", Host: "example", Identity: "key\nMatch all"}} {
+ if _, cleanup, err := JumpConfig([]host.Host{h}); err == nil {
+ cleanup()
+ t.Fatalf("accepted config injection: %+v", h)
+ }
+ }
+}
internal/connect/options.go
@@ -0,0 +1,88 @@
+package connect
+
+import (
+ "fmt"
+ "io"
+ "net"
+ "strconv"
+ "strings"
+
+ "git.neuromancer.ovh/bastien-mrq/sssh/internal/host"
+)
+
+// Options distingue les options sssh de la commande distante.
+type Options struct {
+ Forwards []int
+ Command []string
+ ConfigFile string
+ Supervised bool
+}
+
+// ParseOptions ne consomme que les options placées avant la commande.
+// -- permet de transmettre une commande commençant par -f littéralement.
+func ParseOptions(args []string) (Options, error) {
+ var opts Options
+ for len(args) > 0 {
+ arg := args[0]
+ if arg == "--" {
+ opts.Command = args[1:]
+ return opts, nil
+ }
+ var value string
+ switch {
+ case arg == "-f" || arg == "--forward":
+ if len(args) < 2 {
+ return opts, fmt.Errorf("%s attend un port distant (1–65535)", arg)
+ }
+ value, args = args[1], args[2:]
+ case strings.HasPrefix(arg, "--forward="):
+ value, args = strings.TrimPrefix(arg, "--forward="), args[1:]
+ default:
+ opts.Command = args
+ return opts, nil
+ }
+ port, err := strconv.Atoi(value)
+ if err != nil || port < 1 || port > 65535 {
+ return opts, fmt.Errorf("port distant invalide : %q (1–65535)", value)
+ }
+ opts.Forwards = append(opts.Forwards, port)
+ }
+ return opts, nil
+}
+
+// sshArgs réserve les ports jusqu'au lancement de ssh. OpenSSH ne permet pas
+// de lui transmettre ces sockets : ExitOnForwardFailure couvre la courte
+// fenêtre entre leur libération et le bind de ssh.
+func (o Options) sshArgs(h host.Host, out io.Writer) ([]string, func(), error) {
+ var listeners []net.Listener
+ release := func() {
+ for _, l := range listeners {
+ _ = l.Close()
+ }
+ }
+ var args []string
+ if o.ConfigFile != "" {
+ args = append(args, "-F", o.ConfigFile)
+ }
+ if len(o.Forwards) > 0 || o.Supervised {
+ args = append(args, "-S", "none", "-o", "ForkAfterAuthentication=no", "-o", "ControlMaster=no", "-o", "ControlPersist=no")
+ }
+ if len(o.Forwards) > 0 {
+ args = append(args, "-o", "ExitOnForwardFailure=yes", "-o", "ClearAllForwardings=no")
+ if len(o.Command) == 0 {
+ args = append(args, "-N", "-T")
+ }
+ }
+ for _, remote := range o.Forwards {
+ l, err := net.Listen("tcp4", "127.0.0.1:0")
+ if err != nil {
+ release()
+ return nil, func() {}, fmt.Errorf("port local disponible : %w", err)
+ }
+ listeners = append(listeners, l)
+ local := l.Addr().(*net.TCPAddr).Port
+ args = append(args, "-L", fmt.Sprintf("127.0.0.1:%d:127.0.0.1:%d", local, remote))
+ fmt.Fprintf(out, "⇄ tunnel demandé : 127.0.0.1:%d → %s:127.0.0.1:%d (Ctrl-C pour arrêter)\n", local, h.Name, remote)
+ }
+ return append(args, h.SSHArgs(o.Command...)...), release, nil
+}
internal/connect/options_test.go
@@ -0,0 +1,109 @@
+package connect
+
+import (
+ "bytes"
+ "io"
+ "net"
+ "os/exec"
+ "reflect"
+ "strings"
+ "testing"
+
+ "git.neuromancer.ovh/bastien-mrq/sssh/internal/host"
+)
+
+func TestParseOptions(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ args []string
+ want Options
+ }{
+ {"shell", nil, Options{}},
+ {"tunnel", []string{"-f", "80"}, Options{Forwards: []int{80}}},
+ {"multiple", []string{"-f", "80", "--forward=443", "--forward", "5432"}, Options{Forwards: []int{80, 443, 5432}}},
+ {"command", []string{"-f", "80", "tail", "-f", "/tmp/log"}, Options{Forwards: []int{80}, Command: []string{"tail", "-f", "/tmp/log"}}},
+ {"untouched", []string{"tail", "-f", "/tmp/log"}, Options{Command: []string{"tail", "-f", "/tmp/log"}}},
+ {"separator", []string{"--", "-f", "80"}, Options{Command: []string{"-f", "80"}}},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := ParseOptions(tt.args)
+ if err != nil || !reflect.DeepEqual(got, tt.want) {
+ t.Fatalf("got %#v, %v; want %#v", got, err, tt.want)
+ }
+ })
+ }
+ for _, args := range [][]string{{"-f"}, {"--forward"}, {"-f", "0"}, {"-f", "65536"}, {"-f", "-1"}, {"-f", "abc"}, {"--forward="}, {"-f", "80:80"}} {
+ if _, err := ParseOptions(args); err == nil {
+ t.Errorf("expected invalid port error for %q", args)
+ }
+ }
+}
+
+func TestForwardReservations(t *testing.T) {
+ h := host.Host{Name: "filab", Host: "example.invalid", User: "alice", Port: 2222, Jump: "bastion"}
+ var out bytes.Buffer
+ args, release, err := (Options{Forwards: []int{80, 443}}).sshArgs(h, &out)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer release()
+ var addresses []string
+ for i, arg := range args {
+ if arg != "-L" {
+ continue
+ }
+ parts := strings.Split(args[i+1], ":")
+ if len(parts) != 4 || parts[0] != "127.0.0.1" || parts[2] != "127.0.0.1" {
+ t.Fatalf("unsafe forwarding specification: %q", args[i+1])
+ }
+ address := strings.Join(parts[:2], ":")
+ l, err := net.Listen("tcp4", address)
+ if err == nil {
+ l.Close()
+ t.Fatalf("port %s was not reserved", address)
+ }
+ if !strings.Contains(out.String(), address) {
+ t.Errorf("local address missing from output: %s", address)
+ }
+ addresses = append(addresses, address)
+ }
+ if len(addresses) != 2 || addresses[0] == addresses[1] {
+ t.Fatalf("expected two distinct listeners: %v", addresses)
+ }
+ release()
+ for _, address := range addresses {
+ l, err := net.Listen("tcp4", address)
+ if err != nil {
+ t.Fatal(err)
+ }
+ l.Close()
+ }
+}
+
+// Vérifie l'interprétation réelle par OpenSSH sans connexion réseau (-G).
+func TestOpenSSHForwardConfig(t *testing.T) {
+ ssh, err := exec.LookPath("ssh")
+ if err != nil {
+ t.Skip("OpenSSH unavailable")
+ }
+ for _, remoteCommand := range [][]string{nil, {"uptime"}} {
+ opts := Options{Forwards: []int{80}, Command: remoteCommand}
+ args, release, err := opts.sshArgs(host.Host{Host: "example.invalid", Port: 2222, Jump: "bastion"}, io.Discard)
+ if err != nil {
+ t.Fatal(err)
+ }
+ release()
+ out, err := exec.Command(ssh, append([]string{"-G", "-F", "/dev/null"}, args...)...).Output()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, want := range []string{"exitonforwardfailure yes", "forkafterauthentication no", "clearallforwardings no", "localforward [127.0.0.1]:", " [127.0.0.1]:80", "port 2222", "proxyjump bastion"} {
+ if !strings.Contains(string(out), want) {
+ t.Errorf("missing %q in SSH configuration:\n%s", want, out)
+ }
+ }
+ if (len(remoteCommand) == 0) != strings.Contains(string(out), "sessiontype none") {
+ t.Errorf("unexpected session type for command %v:\n%s", remoteCommand, out)
+ }
+ }
+}
internal/process/process.go
@@ -0,0 +1,50 @@
+// Package process exécute les commandes de profil avec une annulation bornée.
+package process
+
+import (
+ "context"
+ "os"
+ "os/exec"
+ "os/signal"
+ "syscall"
+ "time"
+
+ "golang.org/x/sys/unix"
+)
+
+// Run isole le groupe pour pouvoir arrêter aussi les enfants d'un shell.
+func Run(ctx context.Context, cmd *exec.Cmd) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
+ cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
+ // Les commandes up/down (notamment sudo) doivent pouvoir lire le terminal.
+ // Leur groupe devient temporairement le groupe de premier plan.
+ if foreground, err := unix.IoctlGetInt(int(os.Stdin.Fd()), unix.TIOCGPGRP); err == nil && foreground == syscall.Getpgrp() {
+ cmd.SysProcAttr.Foreground = true
+ cmd.SysProcAttr.Ctty = int(os.Stdin.Fd())
+ sig := make(chan os.Signal, 1)
+ signal.Notify(sig, syscall.SIGTTOU)
+ defer signal.Stop(sig)
+ defer unix.IoctlSetPointerInt(int(os.Stdin.Fd()), unix.TIOCSPGRP, foreground)
+ }
+ if err := cmd.Start(); err != nil {
+ return err
+ }
+ done := make(chan error, 1)
+ go func() { done <- cmd.Wait() }()
+ select {
+ case err := <-done:
+ return err
+ case <-ctx.Done():
+ _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM)
+ select {
+ case <-done:
+ case <-time.After(3 * time.Second):
+ _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
+ <-done
+ }
+ return ctx.Err()
+ }
+}
internal/process/process_test.go
@@ -0,0 +1,22 @@
+package process
+
+import (
+ "context"
+ "errors"
+ "os/exec"
+ "testing"
+ "time"
+)
+
+func TestCancellation(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
+ defer cancel()
+ start := time.Now()
+ err := Run(ctx, exec.Command("sh", "-c", "sleep 60 & wait"))
+ if !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("cancel: %v", err)
+ }
+ if time.Since(start) > 4*time.Second {
+ t.Fatal("shell did not stop promptly")
+ }
+}
internal/vpn/keychain.go
@@ -15,6 +15,13 @@ type Credentials struct {
Password string
}
+func (c Credentials) Validate() error {
+ if c.Username == "" || c.Password == "" || strings.ContainsAny(c.Username+c.Password, "\x00\r\n") {
+ return errors.New("identifiants VPN vides ou contenant un caractère de contrôle interdit")
+ }
+ return nil
+}
+
// KeychainAuth est la valeur de Profile.Auth qui désigne le trousseau.
const KeychainAuth = "keychain"
@@ -23,8 +30,11 @@ func keychainService(profile string) string { return "sssh-vpn-" + profile }
// StoreCredentials enregistre les identifiants dans le trousseau système.
// Le mot de passe ne passe jamais par la ligne de commande (visible dans ps).
func StoreCredentials(profile string, c Credentials) error {
- if strings.ContainsAny(c.Username, "\"\n") {
- return errors.New("identifiant invalide (guillemet ou saut de ligne)")
+ if err := ValidateName(profile); err != nil {
+ return err
+ }
+ if err := c.Validate(); err != nil {
+ return err
}
svc := keychainService(profile)
switch runtime.GOOS {
@@ -33,11 +43,11 @@ func StoreCredentials(profile string, c Credentials) error {
// le mot de passe est passé en hexadécimal (-X) pour éviter tout
// problème de guillemets.
script := fmt.Sprintf("add-generic-password -a \"%s\" -s \"%s\" -l \"sssh vpn %s\" -X %X -U\n",
- c.Username, svc, profile, []byte(c.Password))
+ strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(c.Username), svc, profile, []byte(c.Password))
cmd := exec.Command("security", "-i")
cmd.Stdin = strings.NewReader(script)
- if out, err := cmd.CombinedOutput(); err != nil {
- return fmt.Errorf("security : %v\n%s", err, out)
+ if err := cmd.Run(); err != nil {
+ return fmt.Errorf("security : %w", err)
}
case "linux":
cmd := exec.Command("secret-tool", "store", "--label=sssh vpn "+profile,
@@ -67,6 +77,9 @@ var (
// LookupCredentials lit les identifiants du profil dans le trousseau.
func LookupCredentials(profile string) (Credentials, error) {
+ if err := ValidateName(profile); err != nil {
+ return Credentials{}, err
+ }
svc := keychainService(profile)
var c Credentials
switch runtime.GOOS {
@@ -84,7 +97,7 @@ func LookupCredentials(profile string) (Credentials, error) {
if m == nil {
return c, errors.New("trousseau : identifiant (acct) illisible")
}
- c.Username = strings.ReplaceAll(string(m[1]), `\"`, `"`)
+ c.Username = strings.NewReplacer(`\\`, `\`, `\"`, `"`).Replace(string(m[1]))
case "linux":
pw, err := exec.Command("secret-tool", "lookup", "service", svc).Output()
if err != nil || len(pw) == 0 {
@@ -103,11 +116,14 @@ func LookupCredentials(profile string) (Credentials, error) {
default:
return c, fmt.Errorf("trousseau non supporté sur %s", runtime.GOOS)
}
- return c, nil
+ return c, c.Validate()
}
// DeleteCredentials retire les identifiants du profil du trousseau.
func DeleteCredentials(profile string) error {
+ if err := ValidateName(profile); err != nil {
+ return err
+ }
svc := keychainService(profile)
var cmd *exec.Cmd
switch runtime.GOOS {
internal/vpn/lock.go
@@ -0,0 +1,40 @@
+package vpn
+
+import (
+ "crypto/sha256"
+ "fmt"
+ "os"
+ "path/filepath"
+ "syscall"
+)
+
+// Le verrou est lié au profil, indépendant des fichiers de session. Il reste
+// sur disque : supprimer un fichier flock créerait deux inodes verrouillables.
+func lockProfile(dir, name string) (*os.File, error) {
+ path := filepath.Join(dir, fmt.Sprintf("%x.lock", sha256.Sum256([]byte(name))))
+ fd, err := syscall.Open(path, syscall.O_CREAT|syscall.O_RDWR|syscall.O_NOFOLLOW|syscall.O_CLOEXEC, 0600)
+ if err != nil {
+ return nil, err
+ }
+ f := os.NewFile(uintptr(fd), path)
+ if err := syscall.Flock(fd, syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
+ f.Close()
+ return nil, fmt.Errorf("vpn %s : profil déjà utilisé par une autre session sssh ; ferme cette session avant de réessayer", name)
+ }
+ return f, nil
+}
+
+func privateDir(path string) error {
+ if err := os.MkdirAll(path, 0700); err != nil {
+ return err
+ }
+ info, err := os.Lstat(path)
+ if err != nil {
+ return err
+ }
+ stat, ok := info.Sys().(*syscall.Stat_t)
+ if !info.IsDir() || !ok || stat.Uid != uint32(os.Geteuid()) {
+ return fmt.Errorf("répertoire privé invalide : %s", path)
+ }
+ return os.Chmod(path, 0700)
+}
internal/vpn/vpn.go
@@ -1,68 +1,79 @@
-// Package vpn monte un tunnel (OpenVPN ou commandes custom) le temps
-// d'une connexion SSH, et le démonte ensuite.
+// Package vpn supervise un VPN pendant une connexion SSH.
package vpn
import (
"bufio"
- "crypto/rand"
- "encoding/hex"
+ "context"
"errors"
"fmt"
"net"
"os"
"os/exec"
- "os/signal"
"path/filepath"
+ "regexp"
+ "strconv"
"strings"
"sync"
+ "syscall"
"time"
"git.neuromancer.ovh/bastien-mrq/sssh/internal/host"
+ "git.neuromancer.ovh/bastien-mrq/sssh/internal/process"
)
-// 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"` // "keychain" (trousseau) ou fichier login/mot de passe
- 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)
+ Config string `toml:"config,omitempty"`
+ Auth string `toml:"auth,omitempty"`
+ Up string `toml:"up,omitempty"`
+ Down string `toml:"down,omitempty"`
+ Check string `toml:"check,omitempty"`
+}
+
+var profileName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`)
+
+func ValidateName(name string) error {
+ if !profileName.MatchString(name) {
+ return fmt.Errorf("nom de profil VPN invalide : %q (lettres, chiffres, _, - et .)", name)
+ }
+ return nil
}
-// Validate vérifie la cohérence du profil.
func (p Profile) Validate(name string) error {
+ if err := ValidateName(name); err != nil {
+ return err
+ }
switch {
case p.Config == "" && p.Up == "":
- return fmt.Errorf("profil vpn %q : il faut config (fichier .ovpn) ou up (commande)", name)
+ return fmt.Errorf("profil vpn %q : il faut config ou up", name)
case p.Config != "" && p.Up != "":
return fmt.Errorf("profil vpn %q : config et up sont exclusifs", name)
+ case p.Up != "" && p.Down == "":
+ return fmt.Errorf("profil vpn %q : down est obligatoire avec up", name)
+ case p.Up != "" && p.Auth != "":
+ return fmt.Errorf("profil vpn %q : auth ne s'applique qu'à OpenVPN", name)
+ }
+ if p.Check != "" {
+ h, port, err := net.SplitHostPort(p.Check)
+ n, e := strconv.Atoi(port)
+ if err != nil || e != nil || h == "" || n < 1 || n > 65535 {
+ return fmt.Errorf("profil vpn %q : check doit être host:port (1–65535)", 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
}
-
-// AuthDescribe rend la provenance des identifiants pour les listes.
func (p Profile) AuthDescribe() string {
- switch p.Auth {
- case "":
- return ""
- case KeychainAuth:
+ if p.Auth == KeychainAuth {
return "trousseau"
- default:
- return p.Auth
}
+ return p.Auth
}
-
-// 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
@@ -72,38 +83,40 @@ func (p Profile) NeedsInteractiveAuth() bool {
return false
}
for _, line := range strings.Split(string(data), "\n") {
- if strings.TrimSpace(line) == "auth-user-pass" {
+ fields := strings.Fields(line)
+ if len(fields) > 0 && strings.TrimPrefix(fields[0], "--") == "auth-user-pass" &&
+ (len(fields) == 1 || strings.HasPrefix(fields[1], "#") || strings.HasPrefix(fields[1], ";")) {
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.
+// Session appartient à un seul appelant. Le verrou empêche deux sessions de
+// modifier les routes du même profil. Stop est idempotent.
type Session struct {
- name string
- profile Profile
- cmd *exec.Cmd // openvpn (via sudo) ; nil pour un profil up/down
- done chan error
- fail chan error // erreurs remontées par l'interface de management
-
- mgmtAddr string
- mgmtPw string
- mgmtMu sync.Mutex
- mgmt net.Conn
-
- pidFile string
- LogPath string
+ name string
+ profile Profile
+ cmd *exec.Cmd
+ done chan struct{}
+ ready chan struct{}
+ failed chan struct{}
+ failOnce sync.Once
+ readyOnce sync.Once
+ stopOnce sync.Once
+ stopErr error
+ mu sync.Mutex
+ failure error
+ waitErr error
+ connected bool
+ stopping bool
+ mgmt net.Conn
+ writeMu sync.Mutex
+ listener *net.UnixListener
+ lock *os.File
+ sessionDir string
+ runtimeDir string
+ LogPath string
}
func cacheDir() (string, error) {
@@ -112,278 +125,395 @@ func cacheDir() (string, error) {
base = os.TempDir()
}
dir := filepath.Join(base, "sssh")
- return dir, os.MkdirAll(dir, 0o700)
+ return dir, privateDir(dir)
}
-
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 {
+ if info, err := os.Stat(p); err == nil && info.Mode().IsRegular() && info.Mode().Perm()&0111 != 0 {
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")
+// Start prépare sudo au terminal avant de démarrer les délais du VPN. OpenVPN
+// se connecte à notre socket Unix privé ; si sssh disparaît, management-client
+// déclenche SIGTERM dans OpenVPN. Aucun PID provenant d'un fichier n'est tué.
+func Start(ctx context.Context, name string, p Profile, creds *Credentials) (_ *Session, retErr error) {
+ if err := p.Validate(name); err != nil {
+ return nil, err
+ }
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ dir, err := cacheDir()
if err != nil {
- return 0, err
+ return nil, 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 pose sa question sur le terminal.
-// Les identifiants du trousseau sont fournis à openvpn par son interface
-// de management : ils ne sont jamais écrits sur le disque.
-func Start(name string, p Profile) (*Session, error) {
- s := &Session{name: name, profile: p}
-
+ lock, err := lockProfile(dir, name)
+ if err != nil {
+ return nil, err
+ }
+ s := &Session{name: name, profile: p, lock: lock, ready: make(chan struct{}), failed: make(chan struct{})}
+ defer func() {
+ if retErr != nil {
+ retErr = errors.Join(retErr, s.Stop())
+ }
+ }()
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 {
+ // Même un up interrompu peut avoir créé l'interface : Stop exécute down.
+ if err := process.Run(ctx, exec.Command("sh", "-c", p.Up)); err != nil {
return nil, fmt.Errorf("vpn %s : commande up : %w", name, err)
}
+ close(s.ready)
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)
+ config, err := filepath.Abs(host.ExpandTilde(p.Config))
+ if err != nil {
+ return nil, err
}
-
- var creds *Credentials
- switch {
- case p.Auth == KeychainAuth:
+ if err := validateConfig(config); err != nil {
+ return nil, err
+ }
+ if p.Auth == KeychainAuth {
c, err := LookupCredentials(name)
if err != nil {
- return nil, fmt.Errorf("vpn %s : %v (sssh vpn auth %s pour les enregistrer)", name, err, name)
+ return nil, fmt.Errorf("vpn %s : %w (sssh vpn auth %s)", name, err, name)
}
creds = &c
- case p.Auth != "":
- if _, err := os.Stat(host.ExpandTilde(p.Auth)); err != nil {
- return nil, fmt.Errorf("vpn %s : fichier auth : %w", name, err)
+ }
+ if creds != nil {
+ if err := creds.Validate(); err != nil {
+ return nil, err
}
}
-
- dir, err := cacheDir()
- if err != nil {
+ var authPath string
+ if p.Auth != "" && p.Auth != KeychainAuth {
+ authPath, err = filepath.Abs(host.ExpandTilde(p.Auth))
+ if err != nil {
+ return nil, err
+ }
+ info, err := os.Stat(authPath)
+ if err != nil {
+ return nil, err
+ }
+ if !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 {
+ return nil, fmt.Errorf("fichier auth non privé : %s (chmod 600)", authPath)
+ }
+ }
+ if os.Geteuid() != 0 {
+ sudo := exec.CommandContext(ctx, "sudo", "-v", "-p", "[sssh] mot de passe sudo (openvpn) : ")
+ sudo.Stdin, sudo.Stdout, sudo.Stderr = os.Stdin, os.Stdout, os.Stderr
+ if err := sudo.Run(); err != nil {
+ return nil, fmt.Errorf("authentification sudo : %w", err)
+ }
+ }
+ if err := ctx.Err(); err != nil {
return nil, err
}
- port, err := freePort()
+ s.sessionDir, err = os.MkdirTemp(dir, name+"-")
if err != nil {
return nil, err
}
- raw := make([]byte, 16)
- if _, err := rand.Read(raw); err != nil {
+ s.LogPath = filepath.Join(s.sessionDir, "openvpn.log")
+ logf, err := os.OpenFile(s.LogPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
+ if err != nil {
return nil, err
}
- s.mgmtAddr = 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 {
+ defer logf.Close()
+ // /tmp maintient le chemin sous la limite des sockets Unix sur macOS.
+ // MkdirTemp crée un répertoire aléatoire 0700, sans suivre de lien existant.
+ s.runtimeDir, err = os.MkdirTemp("/tmp", "sssh-vpn-")
+ if 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)
+ socket := filepath.Join(s.runtimeDir, "management.sock")
+ s.listener, err = net.ListenUnix("unix", &net.UnixAddr{Name: socket, Net: "unix"})
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 err := os.Chmod(socket, 0600); err != nil {
+ return nil, err
}
- switch {
- case creds != nil:
- args = append(args, "--management-query-passwords")
- case p.Auth != "":
- args = append(args, "--auth-user-pass", host.ExpandTilde(p.Auth))
+ args := []string{"--config", config, "--management", socket, "unix", "--management-client",
+ "--management-hold", "--management-query-passwords", "--auth-nocache", "--auth-retry", "none", "--verb", "3"}
+ if creds != nil {
+ args = append(args, "--auth-user-pass")
+ } else if authPath != "" {
+ args = append(args, "--auth-user-pass", authPath)
}
-
- 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 := exec.Command(bin, args...)
+ if os.Geteuid() != 0 {
+ cmd = exec.Command("sudo", append([]string{"-n", "--", bin}, args...)...)
+ }
+ cmd.Dir = filepath.Dir(config)
cmd.Stdout, cmd.Stderr = logf, logf
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("vpn %s : %w", name, err)
}
- s.cmd = cmd
- s.done = make(chan error, 1)
- s.fail = make(chan error, 4)
- go func() { s.done <- cmd.Wait() }()
+ s.cmd, s.done = cmd, make(chan struct{})
+ go func() {
+ err := cmd.Wait()
+ s.mu.Lock()
+ s.waitErr = err
+ s.mu.Unlock()
+ close(s.done)
+ }()
go s.manage(creds)
return s, nil
}
-// manage se connecte à l'interface de management d'openvpn, répond aux
-// demandes d'identifiants et garde la connexion pour l'arrêt.
-func (s *Session) manage(creds *Credentials) {
- var conn net.Conn
- deadline := time.Now().Add(15 * time.Second)
- for conn == nil {
- c, err := net.DialTimeout("tcp", s.mgmtAddr, time.Second)
- if err == nil {
- conn = c
- break
+// Les profils sont des fichiers de confiance (exécutés par root), mais les
+// directives de détachement et de contrôle cassent la supervision de sssh.
+func validateConfig(path string) error {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return err
+ }
+ inline := false
+ for _, line := range strings.Split(string(data), "\n") {
+ f := strings.Fields(line)
+ if len(f) == 0 || strings.HasPrefix(f[0], "#") || strings.HasPrefix(f[0], ";") {
+ continue
}
- if time.Now().After(deadline) {
- s.report(fmt.Errorf("vpn %s : interface de management injoignable", s.name))
- return
+ if strings.HasPrefix(f[0], "</") {
+ inline = false
+ continue
}
- select {
- case err := <-s.done:
- s.done <- err
- return
- case <-time.After(200 * time.Millisecond):
+ if strings.HasPrefix(f[0], "<") {
+ inline = true
+ continue
+ }
+ if inline {
+ continue
+ }
+ option := strings.TrimPrefix(strings.Trim(f[0], "\"'"), "--")
+ if option == "daemon" || option == "config" || option == "writepid" || option == "log" || option == "log-append" || strings.HasPrefix(option, "management") {
+ return fmt.Errorf("%s : directive %q incompatible avec la supervision sssh ; utilise un profil .ovpn sans cette directive", path, option)
}
}
- s.mgmtMu.Lock()
- s.mgmt = conn
- s.mgmtMu.Unlock()
+ return nil
+}
- fmt.Fprintf(conn, "%s\n", s.mgmtPw)
- sc := bufio.NewScanner(conn)
- for sc.Scan() {
- line := sc.Text()
+func (s *Session) send(command string) error {
+ s.writeMu.Lock()
+ defer s.writeMu.Unlock()
+ s.mu.Lock()
+ conn := s.mgmt
+ s.mu.Unlock()
+ if conn == nil {
+ return errors.New("management non connecté")
+ }
+ _ = conn.SetWriteDeadline(time.Now().Add(2 * time.Second))
+ _, err := fmt.Fprintln(conn, command)
+ return err
+}
+func (s *Session) manage(creds *Credentials) {
+ // Le listener est créé avant sudo/openvpn : aucun port libéré puis repris.
+ _ = s.listener.SetDeadline(time.Now().Add(30 * time.Second))
+ conn, err := s.listener.AcceptUnix()
+ if err != nil {
+ s.report(fmt.Errorf("vpn %s : management : %w", s.name, err))
+ return
+ }
+ s.mu.Lock()
+ if s.stopping {
+ s.mu.Unlock()
+ conn.Close()
+ return
+ }
+ s.mgmt = conn
+ s.mu.Unlock()
+ defer conn.Close()
+ _ = s.listener.Close()
+ if err := s.send("state on\nhold off\nhold release"); err != nil {
+ s.report(err)
+ return
+ }
+ scanner := bufio.NewScanner(conn)
+ for scanner.Scan() {
+ line := scanner.Text()
switch {
- case strings.Contains(line, ">PASSWORD:Need 'Auth'"):
+ case strings.HasPrefix(line, ">PASSWORD:Verification Failed"):
+ s.report(fmt.Errorf("vpn %s : identifiants refusés (sssh vpn auth %s)", s.name, s.name))
+ return
+ case strings.HasPrefix(line, ">PASSWORD:Need 'Auth' username/password"):
+ if strings.Contains(line, "SC:") {
+ s.report(fmt.Errorf("vpn %s : challenge MFA non pris en charge", s.name))
+ return
+ }
if creds == nil {
- s.report(fmt.Errorf("vpn %s : openvpn demande des identifiants mais le profil n'en a pas", s.name))
+ s.report(fmt.Errorf("vpn %s : identifiants requis (sssh vpn auth %s)", s.name, s.name))
+ return
+ }
+ if err := s.send("username \"Auth\" " + mgmtQuote(creds.Username) + "\npassword \"Auth\" " + mgmtQuote(creds.Password)); err != nil {
+ s.report(err)
+ return
+ }
+ case strings.HasPrefix(line, ">PASSWORD:Need"), strings.HasPrefix(line, ">NEED-OK:"), strings.HasPrefix(line, ">NEED-STR:"):
+ s.report(fmt.Errorf("vpn %s : demande interactive OpenVPN non prise en charge", s.name))
+ return
+ case strings.HasPrefix(line, ">STATE:"):
+ fields := strings.Split(strings.TrimPrefix(line, ">STATE:"), ",")
+ if len(fields) < 3 {
continue
}
- fmt.Fprintf(conn, "username \"Auth\" %s\npassword \"Auth\" %s\n",
- mgmtQuote(creds.Username), mgmtQuote(creds.Password))
- case strings.Contains(line, ">PASSWORD:Verification Failed"):
- s.report(fmt.Errorf("vpn %s : identifiants refusés (sssh vpn auth %s pour les ressaisir)", s.name, s.name))
- case strings.Contains(line, ">PASSWORD:Need"):
- s.report(fmt.Errorf("vpn %s : openvpn demande un secret non géré : %s", s.name, strings.TrimPrefix(line, ">PASSWORD:")))
+ if fields[1] == "CONNECTED" && fields[2] == "SUCCESS" {
+ s.mu.Lock()
+ s.connected = true
+ s.mu.Unlock()
+ s.readyOnce.Do(func() { close(s.ready) })
+ } else {
+ s.mu.Lock()
+ connected := s.connected
+ s.mu.Unlock()
+ if connected {
+ s.report(fmt.Errorf("vpn %s : connexion perdue (%s)", s.name, fields[1]))
+ return
+ }
+ }
+ case strings.HasPrefix(line, ">FATAL:"), strings.HasPrefix(line, "ERROR:"):
+ s.report(fmt.Errorf("vpn %s : erreur OpenVPN (voir %s)", s.name, s.LogPath))
+ return
}
}
+ s.report(fmt.Errorf("vpn %s : canal de management fermé", s.name))
}
-
func (s *Session) report(err error) {
- select {
- case s.fail <- err:
- default:
- }
+ s.mu.Lock()
+ if s.stopping {
+ s.mu.Unlock()
+ return
+ }
+ s.mu.Unlock()
+ s.failOnce.Do(func() {
+ s.mu.Lock()
+ s.failure = err
+ s.mu.Unlock()
+ close(s.failed)
+ })
}
-
-func (s *Session) mgmtConn() net.Conn {
- s.mgmtMu.Lock()
- defer s.mgmtMu.Unlock()
- return s.mgmt
+func (s *Session) failureError() error { s.mu.Lock(); defer s.mu.Unlock(); return s.failure }
+func (s *Session) processError() error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return fmt.Errorf("vpn %s : OpenVPN arrêté (%v), voir %s", s.name, s.waitErr, s.LogPath)
}
-// WaitReachable attend que addr réponde en TCP. Échoue si openvpn s'arrête
-// avant, si l'interface de management signale un problème, 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()
+func (s *Session) WaitReady(ctx context.Context, timeout time.Duration) error {
+ ctx, cancel := context.WithTimeout(ctx, timeout)
+ defer cancel()
+ select {
+ case <-ctx.Done():
+ return fmt.Errorf("vpn %s : attente : %w", s.name, ctx.Err())
+ case <-s.failed:
+ return s.failureError()
+ case <-s.done:
+ return s.processError()
+ case <-s.ready:
+ }
+ // check est une vérification supplémentaire, jamais une preuve de VPN actif.
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 err := <-s.fail:
+ if err := s.Healthy(); err != nil {
return err
- 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 == "" {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if s.profile.Check == "" {
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)
+ dialer := net.Dialer{Timeout: time.Second}
+ conn, err := dialer.DialContext(ctx, "tcp", s.profile.Check)
+ if err == nil {
+ conn.Close()
+ return s.Healthy()
}
- return nil
- }
-
- select {
- case err := <-s.done:
- s.done <- err
- return nil // déjà arrêté
- default:
- }
-
- if conn := s.mgmtConn(); conn != nil {
- fmt.Fprint(conn, "signal SIGTERM\n")
select {
+ case <-ctx.Done():
+ return fmt.Errorf("vpn %s : check %s : %w", s.name, s.profile.Check, ctx.Err())
+ case <-s.failed:
+ return s.failureError()
case <-s.done:
- return nil
- case <-time.After(10 * time.Second):
+ return s.processError()
+ case <-time.After(200 * time.Millisecond):
}
}
-
- // Repli : openvpn tourne en root, il faut sudo pour le signaler.
- if pid, err := os.ReadFile(s.pidFile); err == 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()
+}
+func (s *Session) Healthy() error {
+ select {
+ case <-s.failed:
+ return s.failureError()
+ default:
+ }
+ select {
+ case <-s.done:
+ return s.processError()
+ default:
}
+ return nil
+}
+func (s *Session) Watch(ctx context.Context) error {
select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-s.failed:
+ return s.failureError()
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)
+ return s.processError()
}
}
-// LogTail rend les n dernières lignes du log openvpn, indentées.
-func (s *Session) LogTail(n int) string {
- if s.LogPath == "" {
- return ""
+func (s *Session) Stop() error {
+ s.stopOnce.Do(func() { s.stopErr = s.stop() })
+ return s.stopErr
+}
+func (s *Session) stop() error {
+ s.mu.Lock()
+ s.stopping = true
+ conn := s.mgmt
+ s.mu.Unlock()
+ if s.listener != nil {
+ _ = s.listener.Close()
+ }
+ if conn != nil {
+ _ = s.send("signal SIGTERM")
+ _ = conn.Close() // management-client quitte aussi sur déconnexion
+ }
+ var err error
+ if s.cmd != nil {
+ select {
+ case <-s.done:
+ default:
+ // sudo relaie le signal au processus qu'il supervise ; aucun kill par PID lu.
+ _ = s.cmd.Process.Signal(syscall.SIGTERM)
+ select {
+ case <-s.done:
+ case <-time.After(10 * time.Second):
+ return fmt.Errorf("vpn %s : arrêt non confirmé, verrou conservé jusqu'à la fin de sssh ; voir %s", s.name, s.LogPath)
+ }
+ }
+ } else if s.profile.Up != "" {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ if e := process.Run(ctx, exec.Command("sh", "-c", s.profile.Down)); e != nil {
+ err = fmt.Errorf("vpn %s : commande down : %w", s.name, e)
+ }
}
- data, err := os.ReadFile(s.LogPath)
- if err != nil {
- return ""
+ if s.runtimeDir != "" {
+ err = errors.Join(err, os.RemoveAll(s.runtimeDir))
}
- lines := strings.Split(strings.TrimRight(string(data), "\n"), "\n")
- if len(lines) > n {
- lines = lines[len(lines)-n:]
+ // Les logs sont conservés dans le répertoire unique pour le diagnostic.
+ if s.lock != nil {
+ err = errors.Join(err, s.lock.Close())
}
- return " " + strings.Join(lines, "\n ")
+ return err
}
internal/vpn/vpn_test.go
@@ -0,0 +1,271 @@
+package vpn
+
+import (
+ "bufio"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+// Faux OpenVPN isolé : le même exécutable de test, sans réseau VPN ni sudo.
+func TestVPNHelper(t *testing.T) {
+ mode := os.Getenv("SSSH_VPN_TEST_MODE")
+ if mode == "" {
+ return
+ }
+ args := os.Args
+ if path := os.Getenv("SSSH_VPN_TEST_ARGS"); path != "" {
+ data, _ := json.Marshal(args)
+ _ = os.WriteFile(path, data, 0600)
+ }
+ var socket string
+ for i, arg := range args {
+ if arg == "--management" && i+1 < len(args) {
+ socket = args[i+1]
+ }
+ }
+ conn, err := net.Dial("unix", socket)
+ if err != nil {
+ os.Exit(8)
+ }
+ defer conn.Close()
+ fmt.Fprintln(conn, ">INFO:OpenVPN Management Interface")
+ fmt.Fprintln(conn, ">HOLD:Waiting for hold release:0")
+ sc := bufio.NewScanner(conn)
+ usernameOK := false
+ connected := func() { fmt.Fprintln(conn, ">STATE:1,CONNECTED,SUCCESS,10.0.0.1,127.0.0.1") }
+ for sc.Scan() {
+ line := sc.Text()
+ switch {
+ case line == "state on" || line == "hold off":
+ fmt.Fprintln(conn, "SUCCESS: command succeeded")
+ case line == "hold release":
+ switch mode {
+ case "hang":
+ case "auth":
+ fmt.Fprintln(conn, ">PASSWORD:Need 'Auth' username/password")
+ case "reject":
+ fmt.Fprintln(conn, ">PASSWORD:Verification Failed: 'Auth'")
+ case "die":
+ os.Exit(9)
+ default:
+ connected()
+ if mode == "loss" {
+ go func() {
+ for {
+ if _, err := os.Stat(os.Getenv("SSSH_VPN_TEST_LOSE")); err == nil {
+ fmt.Fprintln(conn, ">STATE:2,RECONNECTING,connection-reset")
+ return
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ }()
+ }
+ }
+ case strings.HasPrefix(line, "username "):
+ usernameOK = line == `username "Auth" "domain\\user"`
+ case strings.HasPrefix(line, "password "):
+ if !usernameOK || line != `password "Auth" "a\"b\\c"` {
+ os.Exit(7)
+ }
+ connected()
+ case line == "signal SIGTERM":
+ os.Exit(0)
+ }
+ }
+ os.Exit(0)
+}
+
+func fakeVPN(t *testing.T, mode string) (Profile, string) {
+ t.Helper()
+ dir := t.TempDir()
+ t.Setenv("HOME", dir)
+ t.Setenv("XDG_CACHE_HOME", filepath.Join(dir, "cache"))
+ t.Setenv("SSSH_VPN_TEST_MODE", mode)
+ t.Setenv("SSSH_VPN_TEST_EXE", os.Args[0])
+ t.Setenv("SSSH_VPN_TEST_ARGS", filepath.Join(dir, "args"))
+ t.Setenv("SSSH_VPN_TEST_LOSE", filepath.Join(dir, "lose"))
+ t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
+ scripts := map[string]string{
+ "openvpn": "#!/bin/sh\nexec \"$SSSH_VPN_TEST_EXE\" -test.run=^TestVPNHelper$ -- \"$@\"\n",
+ "sudo": "#!/bin/sh\nif [ \"$1\" = -v ]; then exit 0; fi\nif [ \"$1\" != -n ] || [ \"$2\" != -- ]; then exit 77; fi\nshift 2\nexec \"$@\"\n",
+ }
+ for name, script := range scripts {
+ if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ config := filepath.Join(dir, "profile.ovpn")
+ if err := os.WriteFile(config, []byte("client\ndev tun\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ return Profile{Config: config}, dir
+}
+func startFake(t *testing.T, p Profile, c *Credentials) *Session {
+ t.Helper()
+ s, err := Start(context.Background(), "test", p, c)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if err := s.Stop(); err != nil {
+ t.Error(err)
+ }
+ })
+ return s
+}
+func TestSessionLifecycle(t *testing.T) {
+ p, dir := fakeVPN(t, "auth")
+ s := startFake(t, p, &Credentials{Username: `domain\user`, Password: `a"b\c`})
+ if err := s.WaitReady(context.Background(), 3*time.Second); err != nil {
+ t.Fatal(err)
+ }
+ for path, mode := range map[string]os.FileMode{s.runtimeDir: 0700, filepath.Join(s.runtimeDir, "management.sock"): 0600, s.sessionDir: 0700, s.LogPath: 0600} {
+ // Le listener retire son socket après accept ; le répertoire reste privé.
+ info, err := os.Stat(path)
+ if os.IsNotExist(err) && strings.HasSuffix(path, "management.sock") {
+ continue
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if info.Mode().Perm() != mode {
+ t.Fatalf("permissions %s: %v", path, info.Mode())
+ }
+ }
+ if other, err := Start(context.Background(), "test", p, nil); err == nil {
+ other.Stop()
+ t.Fatal("concurrent profile accepted")
+ }
+ data, err := os.ReadFile(filepath.Join(dir, "args"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, secret := range []string{"domain", `a\\\"b`} {
+ if strings.Contains(string(data), secret) {
+ t.Fatal("credentials leaked into arguments")
+ }
+ }
+ if err := s.Stop(); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.Stop(); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(s.runtimeDir); !os.IsNotExist(err) {
+ t.Fatalf("runtime directory not removed: %v", err)
+ }
+ // Le verrou est libéré, et une nouvelle session a ses propres logs.
+ s2 := startFake(t, p, &Credentials{Username: `domain\user`, Password: `a"b\c`})
+ if s2.LogPath == s.LogPath {
+ t.Fatal("shared log path")
+ }
+ if err := s2.WaitReady(context.Background(), 3*time.Second); err != nil {
+ t.Fatal(err)
+ }
+}
+func TestReachableDoesNotBypassVPN(t *testing.T) {
+ p, _ := fakeVPN(t, "hang")
+ l, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer l.Close()
+ p.Check = l.Addr().String()
+ s := startFake(t, p, nil)
+ if err := s.WaitReady(context.Background(), 200*time.Millisecond); !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("reachable target bypassed VPN: %v", err)
+ }
+}
+func TestSessionFailures(t *testing.T) {
+ for _, mode := range []string{"reject", "die", "loss"} {
+ t.Run(mode, func(t *testing.T) {
+ p, dir := fakeVPN(t, mode)
+ s := startFake(t, p, nil)
+ err := s.WaitReady(context.Background(), 3*time.Second)
+ if mode != "loss" {
+ if err == nil {
+ t.Fatal("failed VPN became ready")
+ }
+ return
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "lose"), nil, 0600); err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ defer cancel()
+ if err := s.Watch(ctx); err == nil || errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("loss not detected: %v", err)
+ }
+ })
+ }
+}
+func TestCustomProfileCleanup(t *testing.T) {
+ _, dir := fakeVPN(t, "unused")
+ t.Setenv("SSSH_TEST_DOWN", filepath.Join(dir, "down"))
+ p := Profile{Up: "exit 4", Down: `printf 'down\n' >> "$SSSH_TEST_DOWN"`}
+ if _, err := Start(context.Background(), "custom", p, nil); err == nil {
+ t.Fatal("up failure ignored")
+ }
+ p.Up = "true"
+ s := startFake(t, p, nil)
+ if err := s.WaitReady(context.Background(), time.Second); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.Stop(); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.Stop(); err != nil {
+ t.Fatal(err)
+ }
+ data, err := os.ReadFile(filepath.Join(dir, "down"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(data) != "down\ndown\n" {
+ t.Fatalf("cleanup count: %q", data)
+ }
+}
+func TestCanceledStart(t *testing.T) {
+ p, _ := fakeVPN(t, "hang")
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ if _, err := Start(ctx, "test", p, nil); !errors.Is(err, context.Canceled) {
+ t.Fatalf("canceled start: %v", err)
+ }
+}
+func TestValidation(t *testing.T) {
+ for _, name := range []string{"../escape", "a\nb", "a\"b", "", "-bad"} {
+ if err := ValidateName(name); err == nil {
+ t.Errorf("accepted profile %q", name)
+ }
+ }
+ for _, c := range []Credentials{{Username: "a\ncommand", Password: "b"}, {Username: "a", Password: "b\rcommand"}, {Username: "a", Password: ""}} {
+ if err := c.Validate(); err == nil {
+ t.Errorf("accepted invalid credentials")
+ }
+ }
+ for _, p := range []Profile{{Up: "true"}, {Config: "x", Up: "true"}, {Config: "x", Check: "host:0"}, {Config: "x", Check: "host"}} {
+ if err := p.Validate("test"); err == nil {
+ t.Errorf("accepted profile %+v", p)
+ }
+ }
+ dir := t.TempDir()
+ for _, directive := range []string{"daemon", "--daemon", "config other.ovpn", "management localhost 1234", "log /tmp/vpn.log"} {
+ path := filepath.Join(dir, "p.ovpn")
+ os.WriteFile(path, []byte(directive), 0600)
+ if err := validateConfig(path); err == nil {
+ t.Errorf("accepted conflicting directive %q", directive)
+ }
+ }
+}
main.go
@@ -6,12 +6,15 @@
package main
import (
+ "context"
"errors"
"flag"
"fmt"
"os"
+ "os/signal"
"path/filepath"
"strings"
+ "syscall"
"text/tabwriter"
"time"
@@ -25,13 +28,14 @@ import (
"git.neuromancer.ovh/bastien-mrq/sssh/internal/vpn"
)
-const version = "0.2.0"
+var version = "0.2.0" // écrasé par -ldflags au build (make)
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 <nom> -f <port> tunnel vers 127.0.0.1:<port> distant, port local libre
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
@@ -51,6 +55,10 @@ Fichier : ` + "`$SSSH_CONFIG`" + ` ou ~/.config/sssh/hosts.toml`
func main() {
if err := run(os.Args[1:]); err != nil {
fmt.Fprintln(os.Stderr, "sssh :", err)
+ var code exitStatus
+ if errors.As(err, &code) {
+ os.Exit(int(code))
+ }
os.Exit(1)
}
}
@@ -99,101 +107,96 @@ func sshConfigCandidates(st *store.Store) []host.Host {
return out
}
-// resolveJump construit la chaîne ProxyJump complète. Un jump qui référence
-// un host sssh est remplacé par sa cible réelle, et si ce host a lui-même
-// un jump, la chaîne remonte (-J hop1,hop2,…) jusqu'au premier hop.
-// Un jump inconnu de sssh est passé tel quel à ssh ([user@]host[:port]).
-func resolveJump(st *store.Store, h *host.Host) {
- if h.Jump == "" {
- return
- }
- var chain []string
- seen := map[string]bool{h.Name: true}
- jump := h.Jump
- for {
- if seen[jump] {
- break // cycle dans les jumps : on coupe la chaîne là
- }
- j, ok := st.Get(jump)
- if !ok {
- chain = append([]string{jump}, chain...)
- break
- }
- seen[jump] = true
- chain = append([]string{j.JumpSpec()}, chain...)
- if j.Jump == "" {
- break
- }
- jump = j.Jump
+// connectHost supervise les VPN de toute la chaîne puis la session SSH.
+func connectHost(st *store.Store, h host.Host, extra []string) (retErr error) {
+ opts, err := connect.ParseOptions(extra)
+ if err != nil {
+ return err
}
- 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
+ h, hops, profiles, err := resolveRoute(st, h)
+ if err != nil {
+ return err
}
- if h.Jump != "" {
- first := strings.SplitN(h.Jump, ",", 2)[0]
- if hop, err := host.Parse("", first); err == nil {
- return hop.Addr()
+ // Valider tous les profils avant la moindre modification réseau.
+ for _, name := range profiles {
+ p, ok := st.VPN(name)
+ if !ok {
+ return fmt.Errorf("profil vpn inconnu : %q (sssh vpn list)", name)
+ }
+ if err := p.Validate(name); err != nil {
+ return err
}
}
- 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 {
+ config, cleanup, err := connect.JumpConfig(hops)
+ if 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
+ defer cleanup()
+ opts.ConfigFile = config
+ if len(profiles) == 0 && config == "" {
+ return connect.Exec(h, opts)
+ }
+ ctx, stopSignals := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT)
+ defer stopSignals()
+ ctx, cancel := context.WithCancelCause(ctx)
+ defer cancel(nil)
+ var sessions []*vpn.Session
+ defer func() {
+ cancel(nil)
+ for i := len(sessions) - 1; i >= 0; i-- {
+ fmt.Fprintf(os.Stderr, "⇅ vpn %s : démontage\n", profiles[i])
+ retErr = errors.Join(retErr, sessions[i].Stop())
+ }
+ }()
+ for _, name := range profiles {
+ p, _ := st.VPN(name)
+ var creds *vpn.Credentials
+ if p.NeedsInteractiveAuth() {
+ user, pass, err := tui.CredentialsForm(name)
+ if err != nil {
+ return err
+ }
+ creds = &vpn.Credentials{Username: user, Password: pass}
+ }
+ fmt.Fprintf(os.Stderr, "⇅ vpn %s : montage du tunnel… (Ctrl-C pour annuler)\n", name)
+ s, err := vpn.Start(ctx, name, p, creds)
+ if err != nil {
+ return err
+ }
+ sessions = append(sessions, s)
+ // Surveiller aussi pendant le démarrage des profils suivants.
+ go func() {
+ if err := s.Watch(ctx); err != nil && ctx.Err() == nil {
+ cancel(err)
+ }
+ }()
+ if err := s.WaitReady(ctx, 2*time.Minute); err != nil {
+ if cause := context.Cause(ctx); cause != nil {
+ return cause
+ }
+ return err
+ }
+ fmt.Fprintf(os.Stderr, "⇅ vpn %s : actif\n", name)
}
-
- 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")
+ // Une connexion multiplexée ou détachée pourrait survivre au VPN.
+ opts.Supervised = true
+ code, err := connect.RunContext(ctx, h, opts)
+ if cause := context.Cause(ctx); cause != nil {
+ return cause
}
- 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 exitStatus(code)
}
return nil
}
+type exitStatus int
+
+func (e exitStatus) Error() string { return fmt.Sprintf("ssh : code de sortie %d", e) }
+
func cmdConnect(name string, extra []string) error {
st, err := store.Load()
if err != nil {
@@ -421,7 +424,7 @@ func cmdVPN(args []string) error {
name, config := args[1], args[2]
fs := flag.NewFlagSet("vpn add", flag.ContinueOnError)
auth := fs.String("auth", "", "keychain (trousseau) ou fichier login/mot de passe")
- check := fs.String("check", "", "host:port à sonder pour savoir si le VPN est actif")
+ check := fs.String("check", "", "host:port à vérifier après activation du VPN")
if err := fs.Parse(args[3:]); err != nil {
return err
}
@@ -433,6 +436,9 @@ func cmdVPN(args []string) error {
return fmt.Errorf("fichier .ovpn : %w", err)
}
p := vpn.Profile{Config: config, Check: *check}
+ if err := p.Validate(name); err != nil {
+ return err
+ }
switch {
case *auth == vpn.KeychainAuth:
if err := askAndStoreCredentials(name); err != nil {
main_test.go
@@ -0,0 +1,80 @@
+package main
+
+import (
+ "errors"
+ "net"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "git.neuromancer.ovh/bastien-mrq/sssh/internal/host"
+ "git.neuromancer.ovh/bastien-mrq/sssh/internal/store"
+ "git.neuromancer.ovh/bastien-mrq/sssh/internal/vpn"
+)
+
+func TestConnectVPNChainCleanup(t *testing.T) {
+ dir := t.TempDir()
+ t.Setenv("HOME", dir)
+ t.Setenv("XDG_CACHE_HOME", filepath.Join(dir, "cache"))
+ t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
+ log := filepath.Join(dir, "events")
+ t.Setenv("SSSH_TEST_LOG", log)
+ if err := os.WriteFile(filepath.Join(dir, "ssh"), []byte("#!/bin/sh\nprintf 'ssh\\n' >> \"$SSSH_TEST_LOG\"\nexit 7\n"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer listener.Close()
+ st := &store.Store{Hosts: map[string]host.Host{"bastion": {Host: "example.invalid", VPN: "office"}}, VPNs: map[string]vpn.Profile{
+ "office": {Up: `printf 'up office\n' >> "$SSSH_TEST_LOG"`, Down: `printf 'down office\n' >> "$SSSH_TEST_LOG"`, Check: listener.Addr().String()},
+ "lab": {Up: `printf 'up lab\n' >> "$SSSH_TEST_LOG"`, Down: `printf 'down lab\n' >> "$SSSH_TEST_LOG"`},
+ }}
+ err = connectHost(st, host.Host{Name: "filab", Host: "example.invalid", Jump: "bastion", VPN: "lab"}, []string{"-f", "80"})
+ var code exitStatus
+ if !errors.As(err, &code) || code != 7 {
+ t.Fatalf("SSH status lost: %v", err)
+ }
+ data, err := os.ReadFile(log)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(data) != "up office\nup lab\nssh\ndown lab\ndown office\n" {
+ t.Fatalf("lifecycle: %q", data)
+ }
+ // Une erreur de configuration tardive doit être détectée avant tout up.
+ os.Remove(log)
+ p := st.VPNs["lab"]
+ p.Down = ""
+ st.VPNs["lab"] = p
+ if err := connectHost(st, host.Host{Name: "filab", Host: "example.invalid", Jump: "bastion", VPN: "lab"}, nil); err == nil {
+ t.Fatal("invalid profile accepted")
+ }
+ if _, err := os.Stat(log); !os.IsNotExist(err) {
+ t.Fatal("started VPN before validating all profiles")
+ }
+}
+func TestConnectCleanupOnSecondVPNFailure(t *testing.T) {
+ dir := t.TempDir()
+ t.Setenv("HOME", dir)
+ t.Setenv("XDG_CACHE_HOME", dir)
+ log := filepath.Join(dir, "events")
+ t.Setenv("SSSH_TEST_LOG", log)
+ st := &store.Store{Hosts: map[string]host.Host{"bastion": {Host: "example.invalid", VPN: "first"}}, VPNs: map[string]vpn.Profile{
+ "first": {Up: "true", Down: `printf first >> "$SSSH_TEST_LOG"`},
+ "second": {Up: "exit 9", Down: `printf second >> "$SSSH_TEST_LOG"`},
+ }}
+ err := connectHost(st, host.Host{Name: "filab", Host: "example.invalid", Jump: "bastion", VPN: "second"}, nil)
+ if err == nil || !strings.Contains(err.Error(), "commande up") {
+ t.Fatalf("error: %v", err)
+ }
+ data, err := os.ReadFile(log)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(data) != "secondfirst" {
+ t.Fatalf("cleanup order: %q", data)
+ }
+}
route.go
@@ -0,0 +1,60 @@
+package main
+
+import (
+ "fmt"
+ "strings"
+
+ "git.neuromancer.ovh/bastien-mrq/sssh/internal/host"
+ "git.neuromancer.ovh/bastien-mrq/sssh/internal/store"
+)
+
+// resolveRoute développe les alias, conserve les paramètres de chaque bastion
+// et collecte les VPN dans l'ordre réseau (premier hop jusqu'à la cible).
+func resolveRoute(st *store.Store, h host.Host) (host.Host, []host.Host, []string, error) {
+ var chain []string
+ var hops []host.Host
+ var profiles []string
+ seenVPN := map[string]bool{}
+ stack := map[string]bool{h.Name: true}
+ addVPN := func(name string) {
+ if name != "" && !seenVPN[name] {
+ profiles = append(profiles, name)
+ seenVPN[name] = true
+ }
+ }
+ var visit func(string) error
+ visit = func(spec string) error {
+ if spec == "" || spec == "none" {
+ return nil
+ }
+ for _, name := range strings.Split(spec, ",") {
+ name = strings.TrimSpace(name)
+ if name == "" {
+ return fmt.Errorf("jump vide dans %q", spec)
+ }
+ if stack[name] {
+ return fmt.Errorf("cycle dans les jumps : %q", name)
+ }
+ j, ok := st.Get(name)
+ if !ok {
+ chain = append(chain, name)
+ continue
+ }
+ stack[name] = true
+ if err := visit(j.Jump); err != nil {
+ return err
+ }
+ delete(stack, name)
+ chain = append(chain, name)
+ hops = append(hops, j)
+ addVPN(j.VPN)
+ }
+ return nil
+ }
+ if err := visit(h.Jump); err != nil {
+ return h, nil, nil, err
+ }
+ addVPN(h.VPN)
+ h.Jump = strings.Join(chain, ",")
+ return h, hops, profiles, nil
+}
route_test.go
@@ -0,0 +1,33 @@
+package main
+
+import (
+ "git.neuromancer.ovh/bastien-mrq/sssh/internal/host"
+ "git.neuromancer.ovh/bastien-mrq/sssh/internal/store"
+ "reflect"
+ "testing"
+)
+
+func TestResolveRoute(t *testing.T) {
+ st := &store.Store{Hosts: map[string]host.Host{
+ "edge": {Host: "edge.example", VPN: "office", Identity: "~/.ssh/edge"},
+ "bastion": {Host: "10.0.0.1", Jump: "edge", VPN: "office"},
+ }}
+ h, hops, profiles, err := resolveRoute(st, host.Host{Name: "filab", Host: "10.1.0.1", Jump: "bastion", VPN: "lab"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if h.Jump != "edge,bastion" || len(hops) != 2 || hops[0].Identity != "~/.ssh/edge" || !reflect.DeepEqual(profiles, []string{"office", "lab"}) {
+ t.Fatalf("route: %+v %+v %v", h, hops, profiles)
+ }
+ h, _, profiles, err = resolveRoute(st, host.Host{Name: "filab", Jump: "raw@example:2222,edge"})
+ if err != nil || h.Jump != "raw@example:2222,edge" || !reflect.DeepEqual(profiles, []string{"office"}) {
+ t.Fatalf("mixed route: %+v %v %v", h, profiles, err)
+ }
+ st.Hosts["edge"] = host.Host{Jump: "bastion"}
+ if _, _, _, err := resolveRoute(st, host.Host{Name: "filab", Jump: "bastion"}); err == nil {
+ t.Fatal("cycle accepted")
+ }
+ if _, _, _, err := resolveRoute(st, host.Host{Name: "filab", Jump: "filab"}); err == nil {
+ t.Fatal("self cycle accepted")
+ }
+}