Skip to content

Commit

Permalink
Verify if binary exists before executing
Browse files Browse the repository at this point in the history
  • Loading branch information
Hector Vido authored and praveenkumar committed Mar 5, 2025
1 parent 467e61f commit 4bdcc16
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
8 changes: 7 additions & 1 deletion pkg/os/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"github.com/crc-org/crc/v2/pkg/crc/logging"
)

var privilegedCommand = "sudo"

func runCmd(command string, args []string, env map[string]string) (string, string, error) {
cmd := exec.Command(command, args...) // #nosec G204
if len(env) != 0 {
Expand Down Expand Up @@ -44,11 +46,15 @@ func runPrivate(command string, args []string, env map[string]string) (string, s
// RunPrivileged executes a command using sudo
// provide a reason why root is needed as the first argument
func RunPrivileged(reason string, cmdAndArgs ...string) (string, string, error) {
sudo, err := exec.LookPath("sudo")
sudo, err := exec.LookPath(privilegedCommand)
if err != nil {
return "", "", errors.New("sudo executable not found")
}
logging.Infof("Using root access: %s", reason)
_, err = exec.LookPath(cmdAndArgs[0])
if err != nil {
return "", "", errors.New(cmdAndArgs[0] + " executable not found")
}
return run(sudo, cmdAndArgs, map[string]string{})
}

Expand Down
13 changes: 13 additions & 0 deletions pkg/os/exec_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package os

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestRunPrivileged(t *testing.T) {
privilegedCommand = "echo"
_, _, err := RunPrivileged("it should fail", "i-dont-exist")
assert.ErrorContains(t, err, "i-dont-exist executable not found")
}

0 comments on commit 4bdcc16

Please sign in to comment.