36 lines
1.0 KiB
Go
36 lines
1.0 KiB
Go
// Package execsafe resolves privileged system commands without consulting the
|
|
// caller-controlled PATH.
|
|
package execsafe
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strings"
|
|
)
|
|
|
|
var systemDirectories = []string{"/usr/sbin", "/usr/bin", "/sbin", "/bin"}
|
|
|
|
// LookPath resolves a bare command name only from standard system directories.
|
|
func LookPath(name string) (string, error) {
|
|
if name == "" || filepath.Base(name) != name || strings.ContainsRune(name, filepath.Separator) {
|
|
return "", fmt.Errorf("unsafe system command name %q", name)
|
|
}
|
|
for _, directory := range systemDirectories {
|
|
candidate := filepath.Join(directory, name)
|
|
info, err := os.Stat(candidate)
|
|
if err != nil {
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
continue
|
|
}
|
|
return "", fmt.Errorf("inspect trusted system command %s: %w", candidate, err)
|
|
}
|
|
if info.Mode().IsRegular() && info.Mode().Perm()&0o111 != 0 {
|
|
return candidate, nil
|
|
}
|
|
}
|
|
return "", fmt.Errorf("%w: trusted system command %s", exec.ErrNotFound, name)
|
|
}
|