Gitfed
bastien-mrq/sssh / internal / vpn / keychain.go
package vpn

import (
	"errors"
	"fmt"
	"os/exec"
	"regexp"
	"runtime"
	"strings"
)

// Credentials sont les identifiants VPN (auth-user-pass) d'un profil.
type Credentials struct {
	Username string
	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"

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 err := ValidateName(profile); err != nil {
		return err
	}
	if err := c.Validate(); err != nil {
		return err
	}
	svc := keychainService(profile)
	switch runtime.GOOS {
	case "darwin":
		// Mode interactif de security : la commande est lue sur stdin ;
		// 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",
			strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(c.Username), svc, profile, []byte(c.Password))
		cmd := exec.Command("security", "-i")
		cmd.Stdin = strings.NewReader(script)
		if err := cmd.Run(); err != nil {
			return fmt.Errorf("security : %w", err)
		}
	case "linux":
		cmd := exec.Command("secret-tool", "store", "--label=sssh vpn "+profile,
			"service", svc, "username", c.Username)
		cmd.Stdin = strings.NewReader(c.Password)
		if out, err := cmd.CombinedOutput(); err != nil {
			return fmt.Errorf("secret-tool : %v\n%s", err, out)
		}
	default:
		return fmt.Errorf("trousseau non supporté sur %s : utilise -auth <fichier>", runtime.GOOS)
	}
	// Relecture pour s'assurer que l'enregistrement est exploitable.
	got, err := LookupCredentials(profile)
	if err != nil {
		return fmt.Errorf("vérification après enregistrement : %w", err)
	}
	if got != c {
		return errors.New("vérification après enregistrement : identifiants relus différents")
	}
	return nil
}

var (
	reAcct     = regexp.MustCompile(`"acct"<blob>="((?:[^"\\]|\\.)*)"`)
	reUsername = regexp.MustCompile(`(?m)^attribute\.username = (.*)$`)
)

// 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 {
	case "darwin":
		pw, err := exec.Command("security", "find-generic-password", "-s", svc, "-w").Output()
		if err != nil {
			return c, fmt.Errorf("aucun identifiant pour %q dans le trousseau", profile)
		}
		c.Password = strings.TrimSuffix(string(pw), "\n")
		attrs, err := exec.Command("security", "find-generic-password", "-s", svc).Output()
		if err != nil {
			return c, fmt.Errorf("trousseau : %w", err)
		}
		m := reAcct.FindSubmatch(attrs)
		if m == nil {
			return c, errors.New("trousseau : identifiant (acct) illisible")
		}
		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 {
			return c, fmt.Errorf("aucun identifiant pour %q dans le trousseau", profile)
		}
		c.Password = strings.TrimSuffix(string(pw), "\n")
		attrs, err := exec.Command("secret-tool", "search", "--all", "service", svc).CombinedOutput()
		if err != nil {
			return c, fmt.Errorf("secret-tool : %w", err)
		}
		m := reUsername.FindSubmatch(attrs)
		if m == nil {
			return c, errors.New("trousseau : attribut username absent")
		}
		c.Username = strings.TrimSpace(string(m[1]))
	default:
		return c, fmt.Errorf("trousseau non supporté sur %s", runtime.GOOS)
	}
	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 {
	case "darwin":
		cmd = exec.Command("security", "delete-generic-password", "-s", svc)
	case "linux":
		cmd = exec.Command("secret-tool", "clear", "service", svc)
	default:
		return fmt.Errorf("trousseau non supporté sur %s", runtime.GOOS)
	}
	if out, err := cmd.CombinedOutput(); err != nil {
		return fmt.Errorf("suppression dans le trousseau : %v\n%s", err, out)
	}
	return nil
}

// mgmtQuote encadre une valeur pour l'interface de management d'openvpn.
func mgmtQuote(s string) string {
	s = strings.ReplaceAll(s, `\`, `\\`)
	s = strings.ReplaceAll(s, `"`, `\"`)
	return `"` + s + `"`
}