Gitfed
bastien-mrq/sssh / internal / vpn / lock.go
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)
}