Skip to content

Commit

Permalink
prevent single-line sudo command to run in dbl-shell
Browse files Browse the repository at this point in the history
  • Loading branch information
umputun committed Jul 18, 2023
1 parent cb93e16 commit 342eb60
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
6 changes: 5 additions & 1 deletion pkg/runner/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,11 @@ func (ec *execCmd) Script(ctx context.Context) (resp execCmdResp, err error) {
resp.details = fmt.Sprintf(" {script: %s}", c)
if ec.cmd.Options.Sudo {
resp.details = fmt.Sprintf(" {script: %s, sudo: true}", c)
c = fmt.Sprintf("sudo sh -c %q", c)
if strings.HasPrefix(c, "sh -c ") { // single line script already has sh -c
c = fmt.Sprintf("sudo %s", c)
} else {
c = fmt.Sprintf("sudo sh -c %q", c)
}
}
resp.verbose = scr

Expand Down
23 changes: 21 additions & 2 deletions pkg/runner/runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,10 +222,10 @@ func TestProcess_Run(t *testing.T) {
conf, err := config.New("testdata/conf.yml", nil, nil)
require.NoError(t, err)

cmd := conf.Tasks[0].Commands[18]
cmd := conf.Tasks[0].Commands[19]
assert.Equal(t, "copy filename from env", cmd.Name)
cmd.Environment = map[string]string{"filename": "testdata/conf.yml"}
conf.Tasks[0].Commands[18] = cmd
conf.Tasks[0].Commands[19] = cmd

p := Process{
Concurrency: 1,
Expand Down Expand Up @@ -340,6 +340,25 @@ func TestProcess_RunWithSudo(t *testing.T) {
assert.Contains(t, outWriter.String(), "passwd")
})

t.Run("single line script with var", func(t *testing.T) {
p := Process{
Concurrency: 1,
Connector: connector,
Playbook: conf,
ColorWriter: executor.NewColorizedWriter(os.Stdout, "", "", "", nil),
Only: []string{"root only single line with var"},
}

outWriter := &bytes.Buffer{}
log.SetOutput(io.MultiWriter(outWriter, os.Stderr))
res, err := p.Run(ctx, "task1", testingHostAndPort)
require.NoError(t, err)
assert.Equal(t, 1, res.Commands)
assert.Equal(t, 1, res.Hosts)
assert.Contains(t, outWriter.String(), " > sudo sh -c 'vvv=123 && echo var=$vvv'")
assert.Contains(t, outWriter.String(), " > var=123")
})

t.Run("multi line script", func(t *testing.T) {
p := Process{
Concurrency: 1,
Expand Down
5 changes: 5 additions & 0 deletions pkg/runner/testdata/conf.yml
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,11 @@ tasks:
script: ls -l /etc
options: {no_auto: true, sudo: true}


- name: root only single line with var
script: vvv=123 && echo var=$vvv
options: {no_auto: true, sudo: true}

- name: root only copy single file
copy: {src: testdata/conf.yml, dst: /srv/conf.yml}
options: {no_auto: true, sudo: true}
Expand Down

0 comments on commit 342eb60

Please sign in to comment.