Gitfed
bastien-mrq/sssh / internal / vpn / vpn.go
// Package vpn supervise un VPN pendant une connexion SSH.
package vpn

import (
	"bufio"
	"context"
	"errors"
	"fmt"
	"net"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"syscall"
	"time"

	"git.neuromancer.ovh/bastien-mrq/sssh/internal/host"
	"git.neuromancer.ovh/bastien-mrq/sssh/internal/process"
)

type Profile struct {
	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
}

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 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
}

func (p Profile) Describe() string {
	if p.Config != "" {
		return "openvpn " + p.Config
	}
	return "up: " + p.Up
}
func (p Profile) AuthDescribe() string {
	if p.Auth == KeychainAuth {
		return "trousseau"
	}
	return p.Auth
}
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") {
		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
}

// 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
	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) {
	base, err := os.UserCacheDir()
	if err != nil {
		base = os.TempDir()
	}
	dir := filepath.Join(base, "sssh")
	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 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)")
}

// 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 nil, err
	}
	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 != "" {
		// 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, err := filepath.Abs(host.ExpandTilde(p.Config))
	if err != nil {
		return nil, err
	}
	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 : %w (sssh vpn auth %s)", name, err, name)
		}
		creds = &c
	}
	if creds != nil {
		if err := creds.Validate(); err != nil {
			return nil, err
		}
	}
	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
	}
	s.sessionDir, err = os.MkdirTemp(dir, name+"-")
	if err != nil {
		return nil, err
	}
	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
	}
	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
	}
	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
	}
	if err := os.Chmod(socket, 0600); err != nil {
		return nil, err
	}
	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)
	}
	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, 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
}

// 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 strings.HasPrefix(f[0], "</") {
			inline = false
			continue
		}
		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)
		}
	}
	return nil
}

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.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 : 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
			}
			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) {
	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) 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)
}

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 {
		if err := s.Healthy(); err != nil {
			return err
		}
		if err := ctx.Err(); err != nil {
			return err
		}
		if s.profile.Check == "" {
			return nil
		}
		dialer := net.Dialer{Timeout: time.Second}
		conn, err := dialer.DialContext(ctx, "tcp", s.profile.Check)
		if err == nil {
			conn.Close()
			return s.Healthy()
		}
		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 s.processError()
		case <-time.After(200 * time.Millisecond):
		}
	}
}
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 s.processError()
	}
}

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)
		}
	}
	if s.runtimeDir != "" {
		err = errors.Join(err, os.RemoveAll(s.runtimeDir))
	}
	// 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 err
}