fix: harden operations and configuration recovery
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
// 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)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package execsafe_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"proxyctl/internal/execsafe"
|
||||
)
|
||||
|
||||
func TestLookPathUsesOnlyTrustedSystemDirectories(t *testing.T) {
|
||||
path, err := execsafe.LookPath("sh")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !filepath.IsAbs(path) || filepath.Base(path) != "sh" {
|
||||
t.Fatalf("resolved path = %q", path)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLookPathRejectsPathsAndMissingCommands(t *testing.T) {
|
||||
for _, name := range []string{"../systemctl", "/tmp/systemctl", "dir/systemctl", ""} {
|
||||
if _, err := execsafe.LookPath(name); err == nil {
|
||||
t.Fatalf("unsafe name %q was accepted", name)
|
||||
}
|
||||
}
|
||||
if _, err := execsafe.LookPath("proxyctl-command-that-does-not-exist"); !errors.Is(err, exec.ErrNotFound) {
|
||||
t.Fatalf("missing command error = %v", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user