gopkg.in/docker/docker.v20@v20.10.27/integration-cli/docker_cli_run_unix_test.go (about)

     1  //go:build !windows
     2  // +build !windows
     3  
     4  package main
     5  
     6  import (
     7  	"bufio"
     8  	"context"
     9  	"encoding/json"
    10  	"fmt"
    11  	"os"
    12  	"os/exec"
    13  	"path/filepath"
    14  	"regexp"
    15  	"strconv"
    16  	"strings"
    17  	"syscall"
    18  	"testing"
    19  	"time"
    20  
    21  	"github.com/creack/pty"
    22  	"github.com/docker/docker/client"
    23  	"github.com/docker/docker/integration-cli/cli"
    24  	"github.com/docker/docker/integration-cli/cli/build"
    25  	"github.com/docker/docker/pkg/homedir"
    26  	"github.com/docker/docker/pkg/parsers"
    27  	"github.com/docker/docker/pkg/sysinfo"
    28  	"github.com/moby/sys/mount"
    29  	"gotest.tools/v3/assert"
    30  	"gotest.tools/v3/icmd"
    31  )
    32  
    33  // #6509
    34  func (s *DockerSuite) TestRunRedirectStdout(c *testing.T) {
    35  	checkRedirect := func(command string) {
    36  		_, tty, err := pty.Open()
    37  		assert.Assert(c, err == nil, "Could not open pty")
    38  		cmd := exec.Command("sh", "-c", command)
    39  		cmd.Stdin = tty
    40  		cmd.Stdout = tty
    41  		cmd.Stderr = tty
    42  		assert.NilError(c, cmd.Start())
    43  		ch := make(chan error, 1)
    44  		go func() {
    45  			ch <- cmd.Wait()
    46  			close(ch)
    47  		}()
    48  
    49  		select {
    50  		case <-time.After(10 * time.Second):
    51  			c.Fatal("command timeout")
    52  		case err := <-ch:
    53  			assert.Assert(c, err == nil, "wait err")
    54  		}
    55  	}
    56  
    57  	checkRedirect(dockerBinary + " run -i busybox cat /etc/passwd | grep -q root")
    58  	checkRedirect(dockerBinary + " run busybox cat /etc/passwd | grep -q root")
    59  }
    60  
    61  // Test recursive bind mount works by default
    62  func (s *DockerSuite) TestRunWithVolumesIsRecursive(c *testing.T) {
    63  	// /tmp gets permission denied
    64  	testRequires(c, NotUserNamespace, testEnv.IsLocalDaemon)
    65  	tmpDir, err := os.MkdirTemp("", "docker_recursive_mount_test")
    66  	assert.NilError(c, err)
    67  
    68  	defer os.RemoveAll(tmpDir)
    69  
    70  	// Create a temporary tmpfs mount.
    71  	tmpfsDir := filepath.Join(tmpDir, "tmpfs")
    72  	assert.Assert(c, os.MkdirAll(tmpfsDir, 0777) == nil, "failed to mkdir at %s", tmpfsDir)
    73  	assert.Assert(c, mount.Mount("tmpfs", tmpfsDir, "tmpfs", "") == nil, "failed to create a tmpfs mount at %s", tmpfsDir)
    74  
    75  	f, err := os.CreateTemp(tmpfsDir, "touch-me")
    76  	assert.NilError(c, err)
    77  	defer f.Close()
    78  
    79  	out, _ := dockerCmd(c, "run", "--name", "test-data", "--volume", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox:latest", "ls", "/tmp/tmpfs")
    80  	assert.Assert(c, strings.Contains(out, filepath.Base(f.Name())), "Recursive bind mount test failed. Expected file not found")
    81  }
    82  
    83  func (s *DockerSuite) TestRunDeviceDirectory(c *testing.T) {
    84  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
    85  	if _, err := os.Stat("/dev/snd"); err != nil {
    86  		c.Skip("Host does not have /dev/snd")
    87  	}
    88  
    89  	out, _ := dockerCmd(c, "run", "--device", "/dev/snd:/dev/snd", "busybox", "sh", "-c", "ls /dev/snd/")
    90  	assert.Assert(c, strings.Contains(strings.Trim(out, "\r\n"), "timer"), "expected output /dev/snd/timer")
    91  	out, _ = dockerCmd(c, "run", "--device", "/dev/snd:/dev/othersnd", "busybox", "sh", "-c", "ls /dev/othersnd/")
    92  	assert.Assert(c, strings.Contains(strings.Trim(out, "\r\n"), "seq"), "expected output /dev/othersnd/seq")
    93  }
    94  
    95  // TestRunAttachDetach checks attaching and detaching with the default escape sequence.
    96  func (s *DockerSuite) TestRunAttachDetach(c *testing.T) {
    97  	name := "attach-detach"
    98  
    99  	dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
   100  
   101  	cmd := exec.Command(dockerBinary, "attach", name)
   102  	stdout, err := cmd.StdoutPipe()
   103  	assert.NilError(c, err)
   104  	cpty, tty, err := pty.Open()
   105  	assert.NilError(c, err)
   106  	defer cpty.Close()
   107  	cmd.Stdin = tty
   108  	assert.NilError(c, cmd.Start())
   109  	assert.Assert(c, waitRun(name) == nil)
   110  
   111  	_, err = cpty.Write([]byte("hello\n"))
   112  	assert.NilError(c, err)
   113  
   114  	out, err := bufio.NewReader(stdout).ReadString('\n')
   115  	assert.NilError(c, err)
   116  	assert.Equal(c, strings.TrimSpace(out), "hello")
   117  
   118  	// escape sequence
   119  	_, err = cpty.Write([]byte{16})
   120  	assert.NilError(c, err)
   121  	time.Sleep(100 * time.Millisecond)
   122  	_, err = cpty.Write([]byte{17})
   123  	assert.NilError(c, err)
   124  
   125  	ch := make(chan struct{}, 1)
   126  	go func() {
   127  		cmd.Wait()
   128  		ch <- struct{}{}
   129  	}()
   130  
   131  	select {
   132  	case <-ch:
   133  	case <-time.After(10 * time.Second):
   134  		c.Fatal("timed out waiting for container to exit")
   135  	}
   136  
   137  	running := inspectField(c, name, "State.Running")
   138  	assert.Equal(c, running, "true", "expected container to still be running")
   139  
   140  	out, _ = dockerCmd(c, "events", "--since=0", "--until", daemonUnixTime(c), "-f", "container="+name)
   141  	// attach and detach event should be monitored
   142  	assert.Assert(c, strings.Contains(out, "attach"))
   143  	assert.Assert(c, strings.Contains(out, "detach"))
   144  }
   145  
   146  // TestRunAttachDetachFromFlag checks attaching and detaching with the escape sequence specified via flags.
   147  func (s *DockerSuite) TestRunAttachDetachFromFlag(c *testing.T) {
   148  	name := "attach-detach"
   149  	keyCtrlA := []byte{1}
   150  	keyA := []byte{97}
   151  
   152  	dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
   153  
   154  	cmd := exec.Command(dockerBinary, "attach", "--detach-keys=ctrl-a,a", name)
   155  	stdout, err := cmd.StdoutPipe()
   156  	if err != nil {
   157  		c.Fatal(err)
   158  	}
   159  	cpty, tty, err := pty.Open()
   160  	if err != nil {
   161  		c.Fatal(err)
   162  	}
   163  	defer cpty.Close()
   164  	cmd.Stdin = tty
   165  	if err := cmd.Start(); err != nil {
   166  		c.Fatal(err)
   167  	}
   168  	assert.Assert(c, waitRun(name) == nil)
   169  
   170  	if _, err := cpty.Write([]byte("hello\n")); err != nil {
   171  		c.Fatal(err)
   172  	}
   173  
   174  	out, err := bufio.NewReader(stdout).ReadString('\n')
   175  	if err != nil {
   176  		c.Fatal(err)
   177  	}
   178  	if strings.TrimSpace(out) != "hello" {
   179  		c.Fatalf("expected 'hello', got %q", out)
   180  	}
   181  
   182  	// escape sequence
   183  	if _, err := cpty.Write(keyCtrlA); err != nil {
   184  		c.Fatal(err)
   185  	}
   186  	time.Sleep(100 * time.Millisecond)
   187  	if _, err := cpty.Write(keyA); err != nil {
   188  		c.Fatal(err)
   189  	}
   190  
   191  	ch := make(chan struct{}, 1)
   192  	go func() {
   193  		cmd.Wait()
   194  		ch <- struct{}{}
   195  	}()
   196  
   197  	select {
   198  	case <-ch:
   199  	case <-time.After(10 * time.Second):
   200  		c.Fatal("timed out waiting for container to exit")
   201  	}
   202  
   203  	running := inspectField(c, name, "State.Running")
   204  	assert.Equal(c, running, "true", "expected container to still be running")
   205  }
   206  
   207  // TestRunAttachDetachFromInvalidFlag checks attaching and detaching with the escape sequence specified via flags.
   208  func (s *DockerSuite) TestRunAttachDetachFromInvalidFlag(c *testing.T) {
   209  	name := "attach-detach"
   210  	dockerCmd(c, "run", "--name", name, "-itd", "busybox", "top")
   211  	assert.Assert(c, waitRun(name) == nil)
   212  
   213  	// specify an invalid detach key, container will ignore it and use default
   214  	cmd := exec.Command(dockerBinary, "attach", "--detach-keys=ctrl-A,a", name)
   215  	stdout, err := cmd.StdoutPipe()
   216  	if err != nil {
   217  		c.Fatal(err)
   218  	}
   219  	cpty, tty, err := pty.Open()
   220  	if err != nil {
   221  		c.Fatal(err)
   222  	}
   223  	defer cpty.Close()
   224  	cmd.Stdin = tty
   225  	if err := cmd.Start(); err != nil {
   226  		c.Fatal(err)
   227  	}
   228  	go cmd.Wait()
   229  
   230  	bufReader := bufio.NewReader(stdout)
   231  	out, err := bufReader.ReadString('\n')
   232  	if err != nil {
   233  		c.Fatal(err)
   234  	}
   235  	// it should print a warning to indicate the detach key flag is invalid
   236  	errStr := "Invalid detach keys (ctrl-A,a) provided"
   237  	assert.Equal(c, strings.TrimSpace(out), errStr)
   238  }
   239  
   240  // TestRunAttachDetachFromConfig checks attaching and detaching with the escape sequence specified via config file.
   241  func (s *DockerSuite) TestRunAttachDetachFromConfig(c *testing.T) {
   242  	keyCtrlA := []byte{1}
   243  	keyA := []byte{97}
   244  
   245  	// Setup config
   246  	homeKey := homedir.Key()
   247  	homeVal := homedir.Get()
   248  	tmpDir, err := os.MkdirTemp("", "fake-home")
   249  	assert.NilError(c, err)
   250  	defer os.RemoveAll(tmpDir)
   251  
   252  	dotDocker := filepath.Join(tmpDir, ".docker")
   253  	os.Mkdir(dotDocker, 0600)
   254  	tmpCfg := filepath.Join(dotDocker, "config.json")
   255  
   256  	defer func() { os.Setenv(homeKey, homeVal) }()
   257  	os.Setenv(homeKey, tmpDir)
   258  
   259  	data := `{
   260  		"detachKeys": "ctrl-a,a"
   261  	}`
   262  
   263  	err = os.WriteFile(tmpCfg, []byte(data), 0600)
   264  	assert.NilError(c, err)
   265  
   266  	// Then do the work
   267  	name := "attach-detach"
   268  	dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
   269  
   270  	cmd := exec.Command(dockerBinary, "attach", name)
   271  	stdout, err := cmd.StdoutPipe()
   272  	if err != nil {
   273  		c.Fatal(err)
   274  	}
   275  	cpty, tty, err := pty.Open()
   276  	if err != nil {
   277  		c.Fatal(err)
   278  	}
   279  	defer cpty.Close()
   280  	cmd.Stdin = tty
   281  	if err := cmd.Start(); err != nil {
   282  		c.Fatal(err)
   283  	}
   284  	assert.Assert(c, waitRun(name) == nil)
   285  
   286  	if _, err := cpty.Write([]byte("hello\n")); err != nil {
   287  		c.Fatal(err)
   288  	}
   289  
   290  	out, err := bufio.NewReader(stdout).ReadString('\n')
   291  	if err != nil {
   292  		c.Fatal(err)
   293  	}
   294  	if strings.TrimSpace(out) != "hello" {
   295  		c.Fatalf("expected 'hello', got %q", out)
   296  	}
   297  
   298  	// escape sequence
   299  	if _, err := cpty.Write(keyCtrlA); err != nil {
   300  		c.Fatal(err)
   301  	}
   302  	time.Sleep(100 * time.Millisecond)
   303  	if _, err := cpty.Write(keyA); err != nil {
   304  		c.Fatal(err)
   305  	}
   306  
   307  	ch := make(chan struct{}, 1)
   308  	go func() {
   309  		cmd.Wait()
   310  		ch <- struct{}{}
   311  	}()
   312  
   313  	select {
   314  	case <-ch:
   315  	case <-time.After(10 * time.Second):
   316  		c.Fatal("timed out waiting for container to exit")
   317  	}
   318  
   319  	running := inspectField(c, name, "State.Running")
   320  	assert.Equal(c, running, "true", "expected container to still be running")
   321  }
   322  
   323  // TestRunAttachDetachKeysOverrideConfig checks attaching and detaching with the detach flags, making sure it overrides config file
   324  func (s *DockerSuite) TestRunAttachDetachKeysOverrideConfig(c *testing.T) {
   325  	keyCtrlA := []byte{1}
   326  	keyA := []byte{97}
   327  
   328  	// Setup config
   329  	homeKey := homedir.Key()
   330  	homeVal := homedir.Get()
   331  	tmpDir, err := os.MkdirTemp("", "fake-home")
   332  	assert.NilError(c, err)
   333  	defer os.RemoveAll(tmpDir)
   334  
   335  	dotDocker := filepath.Join(tmpDir, ".docker")
   336  	os.Mkdir(dotDocker, 0600)
   337  	tmpCfg := filepath.Join(dotDocker, "config.json")
   338  
   339  	defer func() { os.Setenv(homeKey, homeVal) }()
   340  	os.Setenv(homeKey, tmpDir)
   341  
   342  	data := `{
   343  		"detachKeys": "ctrl-e,e"
   344  	}`
   345  
   346  	err = os.WriteFile(tmpCfg, []byte(data), 0600)
   347  	assert.NilError(c, err)
   348  
   349  	// Then do the work
   350  	name := "attach-detach"
   351  	dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
   352  
   353  	cmd := exec.Command(dockerBinary, "attach", "--detach-keys=ctrl-a,a", name)
   354  	stdout, err := cmd.StdoutPipe()
   355  	if err != nil {
   356  		c.Fatal(err)
   357  	}
   358  	cpty, tty, err := pty.Open()
   359  	if err != nil {
   360  		c.Fatal(err)
   361  	}
   362  	defer cpty.Close()
   363  	cmd.Stdin = tty
   364  	if err := cmd.Start(); err != nil {
   365  		c.Fatal(err)
   366  	}
   367  	assert.Assert(c, waitRun(name) == nil)
   368  
   369  	if _, err := cpty.Write([]byte("hello\n")); err != nil {
   370  		c.Fatal(err)
   371  	}
   372  
   373  	out, err := bufio.NewReader(stdout).ReadString('\n')
   374  	if err != nil {
   375  		c.Fatal(err)
   376  	}
   377  	if strings.TrimSpace(out) != "hello" {
   378  		c.Fatalf("expected 'hello', got %q", out)
   379  	}
   380  
   381  	// escape sequence
   382  	if _, err := cpty.Write(keyCtrlA); err != nil {
   383  		c.Fatal(err)
   384  	}
   385  	time.Sleep(100 * time.Millisecond)
   386  	if _, err := cpty.Write(keyA); err != nil {
   387  		c.Fatal(err)
   388  	}
   389  
   390  	ch := make(chan struct{}, 1)
   391  	go func() {
   392  		cmd.Wait()
   393  		ch <- struct{}{}
   394  	}()
   395  
   396  	select {
   397  	case <-ch:
   398  	case <-time.After(10 * time.Second):
   399  		c.Fatal("timed out waiting for container to exit")
   400  	}
   401  
   402  	running := inspectField(c, name, "State.Running")
   403  	assert.Equal(c, running, "true", "expected container to still be running")
   404  }
   405  
   406  func (s *DockerSuite) TestRunAttachInvalidDetachKeySequencePreserved(c *testing.T) {
   407  	name := "attach-detach"
   408  	keyA := []byte{97}
   409  	keyB := []byte{98}
   410  
   411  	dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
   412  
   413  	cmd := exec.Command(dockerBinary, "attach", "--detach-keys=a,b,c", name)
   414  	stdout, err := cmd.StdoutPipe()
   415  	if err != nil {
   416  		c.Fatal(err)
   417  	}
   418  	cpty, tty, err := pty.Open()
   419  	if err != nil {
   420  		c.Fatal(err)
   421  	}
   422  	defer cpty.Close()
   423  	cmd.Stdin = tty
   424  	if err := cmd.Start(); err != nil {
   425  		c.Fatal(err)
   426  	}
   427  	go cmd.Wait()
   428  	assert.Assert(c, waitRun(name) == nil)
   429  
   430  	// Invalid escape sequence aba, should print aba in output
   431  	if _, err := cpty.Write(keyA); err != nil {
   432  		c.Fatal(err)
   433  	}
   434  	time.Sleep(100 * time.Millisecond)
   435  	if _, err := cpty.Write(keyB); err != nil {
   436  		c.Fatal(err)
   437  	}
   438  	time.Sleep(100 * time.Millisecond)
   439  	if _, err := cpty.Write(keyA); err != nil {
   440  		c.Fatal(err)
   441  	}
   442  	time.Sleep(100 * time.Millisecond)
   443  	if _, err := cpty.Write([]byte("\n")); err != nil {
   444  		c.Fatal(err)
   445  	}
   446  
   447  	out, err := bufio.NewReader(stdout).ReadString('\n')
   448  	if err != nil {
   449  		c.Fatal(err)
   450  	}
   451  	if strings.TrimSpace(out) != "aba" {
   452  		c.Fatalf("expected 'aba', got %q", out)
   453  	}
   454  }
   455  
   456  // "test" should be printed
   457  func (s *DockerSuite) TestRunWithCPUQuota(c *testing.T) {
   458  	testRequires(c, cpuCfsQuota)
   459  
   460  	file := "/sys/fs/cgroup/cpu/cpu.cfs_quota_us"
   461  	out, _ := dockerCmd(c, "run", "--cpu-quota", "8000", "--name", "test", "busybox", "cat", file)
   462  	assert.Equal(c, strings.TrimSpace(out), "8000")
   463  
   464  	out = inspectField(c, "test", "HostConfig.CpuQuota")
   465  	assert.Equal(c, out, "8000", "setting the CPU CFS quota failed")
   466  }
   467  
   468  func (s *DockerSuite) TestRunWithCpuPeriod(c *testing.T) {
   469  	testRequires(c, cpuCfsPeriod)
   470  
   471  	file := "/sys/fs/cgroup/cpu/cpu.cfs_period_us"
   472  	out, _ := dockerCmd(c, "run", "--cpu-period", "50000", "--name", "test", "busybox", "cat", file)
   473  	assert.Equal(c, strings.TrimSpace(out), "50000")
   474  
   475  	out, _ = dockerCmd(c, "run", "--cpu-period", "0", "busybox", "cat", file)
   476  	assert.Equal(c, strings.TrimSpace(out), "100000")
   477  
   478  	out = inspectField(c, "test", "HostConfig.CpuPeriod")
   479  	assert.Equal(c, out, "50000", "setting the CPU CFS period failed")
   480  }
   481  
   482  func (s *DockerSuite) TestRunWithInvalidCpuPeriod(c *testing.T) {
   483  	testRequires(c, cpuCfsPeriod)
   484  	out, _, err := dockerCmdWithError("run", "--cpu-period", "900", "busybox", "true")
   485  	assert.ErrorContains(c, err, "")
   486  	expected := "CPU cfs period can not be less than 1ms (i.e. 1000) or larger than 1s (i.e. 1000000)"
   487  	assert.Assert(c, strings.Contains(out, expected))
   488  
   489  	out, _, err = dockerCmdWithError("run", "--cpu-period", "2000000", "busybox", "true")
   490  	assert.ErrorContains(c, err, "")
   491  	assert.Assert(c, strings.Contains(out, expected))
   492  
   493  	out, _, err = dockerCmdWithError("run", "--cpu-period", "-3", "busybox", "true")
   494  	assert.ErrorContains(c, err, "")
   495  	assert.Assert(c, strings.Contains(out, expected))
   496  }
   497  
   498  func (s *DockerSuite) TestRunWithCPUShares(c *testing.T) {
   499  	testRequires(c, cpuShare)
   500  
   501  	file := "/sys/fs/cgroup/cpu/cpu.shares"
   502  	out, _ := dockerCmd(c, "run", "--cpu-shares", "1000", "--name", "test", "busybox", "cat", file)
   503  	assert.Equal(c, strings.TrimSpace(out), "1000")
   504  
   505  	out = inspectField(c, "test", "HostConfig.CPUShares")
   506  	assert.Equal(c, out, "1000")
   507  }
   508  
   509  // "test" should be printed
   510  func (s *DockerSuite) TestRunEchoStdoutWithCPUSharesAndMemoryLimit(c *testing.T) {
   511  	testRequires(c, cpuShare)
   512  	testRequires(c, memoryLimitSupport)
   513  	cli.DockerCmd(c, "run", "--cpu-shares", "1000", "-m", "32m", "busybox", "echo", "test").Assert(c, icmd.Expected{
   514  		Out: "test\n",
   515  	})
   516  }
   517  
   518  func (s *DockerSuite) TestRunWithCpusetCpus(c *testing.T) {
   519  	testRequires(c, cgroupCpuset)
   520  
   521  	file := "/sys/fs/cgroup/cpuset/cpuset.cpus"
   522  	out, _ := dockerCmd(c, "run", "--cpuset-cpus", "0", "--name", "test", "busybox", "cat", file)
   523  	assert.Equal(c, strings.TrimSpace(out), "0")
   524  
   525  	out = inspectField(c, "test", "HostConfig.CpusetCpus")
   526  	assert.Equal(c, out, "0")
   527  }
   528  
   529  func (s *DockerSuite) TestRunWithCpusetMems(c *testing.T) {
   530  	testRequires(c, cgroupCpuset)
   531  
   532  	file := "/sys/fs/cgroup/cpuset/cpuset.mems"
   533  	out, _ := dockerCmd(c, "run", "--cpuset-mems", "0", "--name", "test", "busybox", "cat", file)
   534  	assert.Equal(c, strings.TrimSpace(out), "0")
   535  
   536  	out = inspectField(c, "test", "HostConfig.CpusetMems")
   537  	assert.Equal(c, out, "0")
   538  }
   539  
   540  func (s *DockerSuite) TestRunWithBlkioWeight(c *testing.T) {
   541  	testRequires(c, blkioWeight)
   542  
   543  	file := "/sys/fs/cgroup/blkio/blkio.weight"
   544  	out, _ := dockerCmd(c, "run", "--blkio-weight", "300", "--name", "test", "busybox", "cat", file)
   545  	assert.Equal(c, strings.TrimSpace(out), "300")
   546  
   547  	out = inspectField(c, "test", "HostConfig.BlkioWeight")
   548  	assert.Equal(c, out, "300")
   549  }
   550  
   551  func (s *DockerSuite) TestRunWithInvalidBlkioWeight(c *testing.T) {
   552  	testRequires(c, blkioWeight)
   553  	out, _, err := dockerCmdWithError("run", "--blkio-weight", "5", "busybox", "true")
   554  	assert.ErrorContains(c, err, "", out)
   555  	expected := "Range of blkio weight is from 10 to 1000"
   556  	assert.Assert(c, strings.Contains(out, expected))
   557  }
   558  
   559  func (s *DockerSuite) TestRunWithInvalidPathforBlkioWeightDevice(c *testing.T) {
   560  	testRequires(c, blkioWeight)
   561  	out, _, err := dockerCmdWithError("run", "--blkio-weight-device", "/dev/sdX:100", "busybox", "true")
   562  	assert.ErrorContains(c, err, "", out)
   563  }
   564  
   565  func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceReadBps(c *testing.T) {
   566  	testRequires(c, blkioWeight)
   567  	out, _, err := dockerCmdWithError("run", "--device-read-bps", "/dev/sdX:500", "busybox", "true")
   568  	assert.ErrorContains(c, err, "", out)
   569  }
   570  
   571  func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceWriteBps(c *testing.T) {
   572  	testRequires(c, blkioWeight)
   573  	out, _, err := dockerCmdWithError("run", "--device-write-bps", "/dev/sdX:500", "busybox", "true")
   574  	assert.ErrorContains(c, err, "", out)
   575  }
   576  
   577  func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceReadIOps(c *testing.T) {
   578  	testRequires(c, blkioWeight)
   579  	out, _, err := dockerCmdWithError("run", "--device-read-iops", "/dev/sdX:500", "busybox", "true")
   580  	assert.ErrorContains(c, err, "", out)
   581  }
   582  
   583  func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceWriteIOps(c *testing.T) {
   584  	testRequires(c, blkioWeight)
   585  	out, _, err := dockerCmdWithError("run", "--device-write-iops", "/dev/sdX:500", "busybox", "true")
   586  	assert.ErrorContains(c, err, "", out)
   587  }
   588  
   589  func (s *DockerSuite) TestRunOOMExitCode(c *testing.T) {
   590  	testRequires(c, memoryLimitSupport, swapMemorySupport, NotPpc64le)
   591  	errChan := make(chan error, 1)
   592  	go func() {
   593  		defer close(errChan)
   594  		// memory limit lower than 8MB will raise an error of "device or resource busy" from docker-runc.
   595  		out, exitCode, _ := dockerCmdWithError("run", "-m", "8MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x$x$x; done")
   596  		if expected := 137; exitCode != expected {
   597  			errChan <- fmt.Errorf("wrong exit code for OOM container: expected %d, got %d (output: %q)", expected, exitCode, out)
   598  		}
   599  	}()
   600  
   601  	select {
   602  	case err := <-errChan:
   603  		assert.NilError(c, err)
   604  	case <-time.After(600 * time.Second):
   605  		c.Fatal("Timeout waiting for container to die on OOM")
   606  	}
   607  }
   608  
   609  func (s *DockerSuite) TestRunWithMemoryLimit(c *testing.T) {
   610  	testRequires(c, memoryLimitSupport)
   611  
   612  	file := "/sys/fs/cgroup/memory/memory.limit_in_bytes"
   613  	cli.DockerCmd(c, "run", "-m", "32M", "--name", "test", "busybox", "cat", file).Assert(c, icmd.Expected{
   614  		Out: "33554432",
   615  	})
   616  	cli.InspectCmd(c, "test", cli.Format(".HostConfig.Memory")).Assert(c, icmd.Expected{
   617  		Out: "33554432",
   618  	})
   619  }
   620  
   621  // TestRunWithoutMemoryswapLimit sets memory limit and disables swap
   622  // memory limit, this means the processes in the container can use
   623  // 16M memory and as much swap memory as they need (if the host
   624  // supports swap memory).
   625  func (s *DockerSuite) TestRunWithoutMemoryswapLimit(c *testing.T) {
   626  	testRequires(c, DaemonIsLinux)
   627  	testRequires(c, memoryLimitSupport)
   628  	testRequires(c, swapMemorySupport)
   629  	dockerCmd(c, "run", "-m", "32m", "--memory-swap", "-1", "busybox", "true")
   630  }
   631  
   632  func (s *DockerSuite) TestRunWithSwappiness(c *testing.T) {
   633  	testRequires(c, memorySwappinessSupport)
   634  	file := "/sys/fs/cgroup/memory/memory.swappiness"
   635  	out, _ := dockerCmd(c, "run", "--memory-swappiness", "0", "--name", "test", "busybox", "cat", file)
   636  	assert.Equal(c, strings.TrimSpace(out), "0")
   637  
   638  	out = inspectField(c, "test", "HostConfig.MemorySwappiness")
   639  	assert.Equal(c, out, "0")
   640  }
   641  
   642  func (s *DockerSuite) TestRunWithSwappinessInvalid(c *testing.T) {
   643  	testRequires(c, memorySwappinessSupport)
   644  	out, _, err := dockerCmdWithError("run", "--memory-swappiness", "101", "busybox", "true")
   645  	assert.ErrorContains(c, err, "")
   646  	expected := "Valid memory swappiness range is 0-100"
   647  	assert.Assert(c, strings.Contains(out, expected), "Expected output to contain %q, not %q", out, expected)
   648  	out, _, err = dockerCmdWithError("run", "--memory-swappiness", "-10", "busybox", "true")
   649  	assert.ErrorContains(c, err, "")
   650  	assert.Assert(c, strings.Contains(out, expected), "Expected output to contain %q, not %q", out, expected)
   651  }
   652  
   653  func (s *DockerSuite) TestRunWithMemoryReservation(c *testing.T) {
   654  	testRequires(c, testEnv.IsLocalDaemon, memoryReservationSupport)
   655  
   656  	file := "/sys/fs/cgroup/memory/memory.soft_limit_in_bytes"
   657  	out, _ := dockerCmd(c, "run", "--memory-reservation", "200M", "--name", "test", "busybox", "cat", file)
   658  	assert.Equal(c, strings.TrimSpace(out), "209715200")
   659  
   660  	out = inspectField(c, "test", "HostConfig.MemoryReservation")
   661  	assert.Equal(c, out, "209715200")
   662  }
   663  
   664  func (s *DockerSuite) TestRunWithMemoryReservationInvalid(c *testing.T) {
   665  	testRequires(c, memoryLimitSupport)
   666  	testRequires(c, testEnv.IsLocalDaemon, memoryReservationSupport)
   667  	out, _, err := dockerCmdWithError("run", "-m", "500M", "--memory-reservation", "800M", "busybox", "true")
   668  	assert.ErrorContains(c, err, "")
   669  	expected := "Minimum memory limit can not be less than memory reservation limit"
   670  	assert.Assert(c, strings.Contains(strings.TrimSpace(out), expected), "run container should fail with invalid memory reservation")
   671  	out, _, err = dockerCmdWithError("run", "--memory-reservation", "1k", "busybox", "true")
   672  	assert.ErrorContains(c, err, "")
   673  	expected = "Minimum memory reservation allowed is 6MB"
   674  	assert.Assert(c, strings.Contains(strings.TrimSpace(out), expected), "run container should fail with invalid memory reservation")
   675  }
   676  
   677  func (s *DockerSuite) TestStopContainerSignal(c *testing.T) {
   678  	out, _ := dockerCmd(c, "run", "--stop-signal", "SIGUSR1", "-d", "busybox", "/bin/sh", "-c", `trap 'echo "exit trapped"; exit 0' USR1; while true; do sleep 1; done`)
   679  	containerID := strings.TrimSpace(out)
   680  
   681  	assert.Assert(c, waitRun(containerID) == nil)
   682  
   683  	dockerCmd(c, "stop", containerID)
   684  	out, _ = dockerCmd(c, "logs", containerID)
   685  
   686  	assert.Assert(c, strings.Contains(out, "exit trapped"), "Expected `exit trapped` in the log")
   687  }
   688  
   689  func (s *DockerSuite) TestRunSwapLessThanMemoryLimit(c *testing.T) {
   690  	testRequires(c, memoryLimitSupport)
   691  	testRequires(c, swapMemorySupport)
   692  	out, _, err := dockerCmdWithError("run", "-m", "16m", "--memory-swap", "15m", "busybox", "echo", "test")
   693  	expected := "Minimum memoryswap limit should be larger than memory limit"
   694  	assert.ErrorContains(c, err, "")
   695  
   696  	assert.Assert(c, strings.Contains(out, expected))
   697  }
   698  
   699  func (s *DockerSuite) TestRunInvalidCpusetCpusFlagValue(c *testing.T) {
   700  	testRequires(c, cgroupCpuset, testEnv.IsLocalDaemon)
   701  
   702  	sysInfo := sysinfo.New(true)
   703  	cpus, err := parsers.ParseUintList(sysInfo.Cpus)
   704  	assert.NilError(c, err)
   705  	var invalid int
   706  	for i := 0; i <= len(cpus)+1; i++ {
   707  		if !cpus[i] {
   708  			invalid = i
   709  			break
   710  		}
   711  	}
   712  	out, _, err := dockerCmdWithError("run", "--cpuset-cpus", strconv.Itoa(invalid), "busybox", "true")
   713  	assert.ErrorContains(c, err, "")
   714  	expected := fmt.Sprintf("Error response from daemon: Requested CPUs are not available - requested %s, available: %s", strconv.Itoa(invalid), sysInfo.Cpus)
   715  	assert.Assert(c, strings.Contains(out, expected))
   716  }
   717  
   718  func (s *DockerSuite) TestRunInvalidCpusetMemsFlagValue(c *testing.T) {
   719  	testRequires(c, cgroupCpuset)
   720  
   721  	sysInfo := sysinfo.New(true)
   722  	mems, err := parsers.ParseUintList(sysInfo.Mems)
   723  	assert.NilError(c, err)
   724  	var invalid int
   725  	for i := 0; i <= len(mems)+1; i++ {
   726  		if !mems[i] {
   727  			invalid = i
   728  			break
   729  		}
   730  	}
   731  	out, _, err := dockerCmdWithError("run", "--cpuset-mems", strconv.Itoa(invalid), "busybox", "true")
   732  	assert.ErrorContains(c, err, "")
   733  	expected := fmt.Sprintf("Error response from daemon: Requested memory nodes are not available - requested %s, available: %s", strconv.Itoa(invalid), sysInfo.Mems)
   734  	assert.Assert(c, strings.Contains(out, expected))
   735  }
   736  
   737  func (s *DockerSuite) TestRunInvalidCPUShares(c *testing.T) {
   738  	testRequires(c, cpuShare, DaemonIsLinux)
   739  	out, _, err := dockerCmdWithError("run", "--cpu-shares", "1", "busybox", "echo", "test")
   740  	assert.ErrorContains(c, err, "", out)
   741  	expected := "minimum allowed cpu-shares is 2"
   742  	assert.Assert(c, strings.Contains(out, expected))
   743  
   744  	out, _, err = dockerCmdWithError("run", "--cpu-shares", "-1", "busybox", "echo", "test")
   745  	assert.ErrorContains(c, err, "", out)
   746  	expected = "shares: invalid argument"
   747  	assert.Assert(c, strings.Contains(out, expected))
   748  
   749  	out, _, err = dockerCmdWithError("run", "--cpu-shares", "99999999", "busybox", "echo", "test")
   750  	assert.ErrorContains(c, err, "", out)
   751  	expected = "maximum allowed cpu-shares is"
   752  	assert.Assert(c, strings.Contains(out, expected))
   753  }
   754  
   755  func (s *DockerSuite) TestRunWithDefaultShmSize(c *testing.T) {
   756  	testRequires(c, DaemonIsLinux)
   757  
   758  	name := "shm-default"
   759  	out, _ := dockerCmd(c, "run", "--name", name, "busybox", "mount")
   760  	shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`)
   761  	if !shmRegex.MatchString(out) {
   762  		c.Fatalf("Expected shm of 64MB in mount command, got %v", out)
   763  	}
   764  	shmSize := inspectField(c, name, "HostConfig.ShmSize")
   765  	assert.Equal(c, shmSize, "67108864")
   766  }
   767  
   768  func (s *DockerSuite) TestRunWithShmSize(c *testing.T) {
   769  	testRequires(c, DaemonIsLinux)
   770  
   771  	name := "shm"
   772  	out, _ := dockerCmd(c, "run", "--name", name, "--shm-size=1G", "busybox", "mount")
   773  	shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=1048576k`)
   774  	if !shmRegex.MatchString(out) {
   775  		c.Fatalf("Expected shm of 1GB in mount command, got %v", out)
   776  	}
   777  	shmSize := inspectField(c, name, "HostConfig.ShmSize")
   778  	assert.Equal(c, shmSize, "1073741824")
   779  }
   780  
   781  func (s *DockerSuite) TestRunTmpfsMountsEnsureOrdered(c *testing.T) {
   782  	tmpFile, err := os.CreateTemp("", "test")
   783  	assert.NilError(c, err)
   784  	defer tmpFile.Close()
   785  	out, _ := dockerCmd(c, "run", "--tmpfs", "/run", "-v", tmpFile.Name()+":/run/test", "busybox", "ls", "/run")
   786  	assert.Assert(c, strings.Contains(out, "test"))
   787  }
   788  
   789  func (s *DockerSuite) TestRunTmpfsMounts(c *testing.T) {
   790  	// TODO Windows (Post TP5): This test cannot run on a Windows daemon as
   791  	// Windows does not support tmpfs mounts.
   792  	testRequires(c, DaemonIsLinux)
   793  	if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run", "busybox", "touch", "/run/somefile"); err != nil {
   794  		c.Fatalf("/run directory not mounted on tmpfs %q %s", err, out)
   795  	}
   796  	if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run:noexec", "busybox", "touch", "/run/somefile"); err != nil {
   797  		c.Fatalf("/run directory not mounted on tmpfs %q %s", err, out)
   798  	}
   799  	if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run:noexec,nosuid,rw,size=5k,mode=700", "busybox", "touch", "/run/somefile"); err != nil {
   800  		c.Fatalf("/run failed to mount on tmpfs with valid options %q %s", err, out)
   801  	}
   802  	if _, _, err := dockerCmdWithError("run", "--tmpfs", "/run:foobar", "busybox", "touch", "/run/somefile"); err == nil {
   803  		c.Fatalf("/run mounted on tmpfs when it should have vailed within invalid mount option")
   804  	}
   805  	if _, _, err := dockerCmdWithError("run", "--tmpfs", "/run", "-v", "/run:/run", "busybox", "touch", "/run/somefile"); err == nil {
   806  		c.Fatalf("Should have generated an error saying Duplicate mount  points")
   807  	}
   808  }
   809  
   810  func (s *DockerSuite) TestRunTmpfsMountsOverrideImageVolumes(c *testing.T) {
   811  	name := "img-with-volumes"
   812  	buildImageSuccessfully(c, name, build.WithDockerfile(`
   813      FROM busybox
   814      VOLUME /run
   815      RUN touch /run/stuff
   816      `))
   817  	out, _ := dockerCmd(c, "run", "--tmpfs", "/run", name, "ls", "/run")
   818  	assert.Assert(c, !strings.Contains(out, "stuff"))
   819  }
   820  
   821  // Test case for #22420
   822  func (s *DockerSuite) TestRunTmpfsMountsWithOptions(c *testing.T) {
   823  	testRequires(c, DaemonIsLinux)
   824  
   825  	expectedOptions := []string{"rw", "nosuid", "nodev", "noexec", "relatime"}
   826  	out, _ := dockerCmd(c, "run", "--tmpfs", "/tmp", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'")
   827  	for _, option := range expectedOptions {
   828  		assert.Assert(c, strings.Contains(out, option))
   829  	}
   830  	assert.Assert(c, !strings.Contains(out, "size="))
   831  	expectedOptions = []string{"rw", "nosuid", "nodev", "noexec", "relatime"}
   832  	out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:rw", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'")
   833  	for _, option := range expectedOptions {
   834  		assert.Assert(c, strings.Contains(out, option))
   835  	}
   836  	assert.Assert(c, !strings.Contains(out, "size="))
   837  	expectedOptions = []string{"rw", "nosuid", "nodev", "relatime", "size=8192k"}
   838  	out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:rw,exec,size=8192k", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'")
   839  	for _, option := range expectedOptions {
   840  		assert.Assert(c, strings.Contains(out, option))
   841  	}
   842  
   843  	expectedOptions = []string{"rw", "nosuid", "nodev", "noexec", "relatime", "size=4096k"}
   844  	out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:rw,size=8192k,exec,size=4096k,noexec", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'")
   845  	for _, option := range expectedOptions {
   846  		assert.Assert(c, strings.Contains(out, option))
   847  	}
   848  
   849  	// We use debian:bullseye-slim as there is no findmnt in busybox. Also the output will be in the format of
   850  	// TARGET PROPAGATION
   851  	// /tmp   shared
   852  	// so we only capture `shared` here.
   853  	expectedOptions = []string{"shared"}
   854  	out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:shared", "debian:bullseye-slim", "findmnt", "-o", "TARGET,PROPAGATION", "/tmp")
   855  	for _, option := range expectedOptions {
   856  		assert.Assert(c, strings.Contains(out, option))
   857  	}
   858  }
   859  
   860  func (s *DockerSuite) TestRunSysctls(c *testing.T) {
   861  	testRequires(c, DaemonIsLinux)
   862  	var err error
   863  
   864  	out, _ := dockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=1", "--name", "test", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward")
   865  	assert.Equal(c, strings.TrimSpace(out), "1")
   866  
   867  	out = inspectFieldJSON(c, "test", "HostConfig.Sysctls")
   868  
   869  	sysctls := make(map[string]string)
   870  	err = json.Unmarshal([]byte(out), &sysctls)
   871  	assert.NilError(c, err)
   872  	assert.Equal(c, sysctls["net.ipv4.ip_forward"], "1")
   873  
   874  	out, _ = dockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=0", "--name", "test1", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward")
   875  	assert.Equal(c, strings.TrimSpace(out), "0")
   876  
   877  	out = inspectFieldJSON(c, "test1", "HostConfig.Sysctls")
   878  
   879  	err = json.Unmarshal([]byte(out), &sysctls)
   880  	assert.NilError(c, err)
   881  	assert.Equal(c, sysctls["net.ipv4.ip_forward"], "0")
   882  
   883  	icmd.RunCommand(dockerBinary, "run", "--sysctl", "kernel.foobar=1", "--name", "test2",
   884  		"busybox", "cat", "/proc/sys/kernel/foobar").Assert(c, icmd.Expected{
   885  		ExitCode: 125,
   886  		Err:      "invalid argument",
   887  	})
   888  }
   889  
   890  // TestRunSeccompProfileDenyUnshare checks that 'docker run --security-opt seccomp=/tmp/profile.json debian:bullseye-slim unshare' exits with operation not permitted.
   891  func (s *DockerSuite) TestRunSeccompProfileDenyUnshare(c *testing.T) {
   892  	testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, NotArm, Apparmor)
   893  	jsonData := `{
   894  	"defaultAction": "SCMP_ACT_ALLOW",
   895  	"syscalls": [
   896  		{
   897  			"name": "unshare",
   898  			"action": "SCMP_ACT_ERRNO"
   899  		}
   900  	]
   901  }`
   902  	tmpFile, err := os.CreateTemp("", "profile.json")
   903  	if err != nil {
   904  		c.Fatal(err)
   905  	}
   906  	defer tmpFile.Close()
   907  
   908  	if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
   909  		c.Fatal(err)
   910  	}
   911  	icmd.RunCommand(dockerBinary, "run", "--security-opt", "apparmor=unconfined",
   912  		"--security-opt", "seccomp="+tmpFile.Name(),
   913  		"debian:bullseye-slim", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc").Assert(c, icmd.Expected{
   914  		ExitCode: 1,
   915  		Err:      "Operation not permitted",
   916  	})
   917  }
   918  
   919  // TestRunSeccompProfileDenyChmod checks that 'docker run --security-opt seccomp=/tmp/profile.json busybox chmod 400 /etc/hostname' exits with operation not permitted.
   920  func (s *DockerSuite) TestRunSeccompProfileDenyChmod(c *testing.T) {
   921  	testRequires(c, testEnv.IsLocalDaemon, seccompEnabled)
   922  	jsonData := `{
   923  	"defaultAction": "SCMP_ACT_ALLOW",
   924  	"syscalls": [
   925  		{
   926  			"name": "chmod",
   927  			"action": "SCMP_ACT_ERRNO"
   928  		},
   929  		{
   930  			"name":"fchmod",
   931  			"action": "SCMP_ACT_ERRNO"
   932  		},
   933  		{
   934  			"name": "fchmodat",
   935  			"action":"SCMP_ACT_ERRNO"
   936  		}
   937  	]
   938  }`
   939  	tmpFile, err := os.CreateTemp("", "profile.json")
   940  	assert.NilError(c, err)
   941  	defer tmpFile.Close()
   942  
   943  	if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
   944  		c.Fatal(err)
   945  	}
   946  	icmd.RunCommand(dockerBinary, "run", "--security-opt", "seccomp="+tmpFile.Name(),
   947  		"busybox", "chmod", "400", "/etc/hostname").Assert(c, icmd.Expected{
   948  		ExitCode: 1,
   949  		Err:      "Operation not permitted",
   950  	})
   951  }
   952  
   953  // TestRunSeccompProfileDenyUnshareUserns checks that 'docker run debian:bullseye-slim unshare --map-root-user --user sh -c whoami' with a specific profile to
   954  // deny unshare of a userns exits with operation not permitted.
   955  func (s *DockerSuite) TestRunSeccompProfileDenyUnshareUserns(c *testing.T) {
   956  	testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, NotArm, Apparmor)
   957  	// from sched.h
   958  	jsonData := fmt.Sprintf(`{
   959  	"defaultAction": "SCMP_ACT_ALLOW",
   960  	"syscalls": [
   961  		{
   962  			"name": "unshare",
   963  			"action": "SCMP_ACT_ERRNO",
   964  			"args": [
   965  				{
   966  					"index": 0,
   967  					"value": %d,
   968  					"op": "SCMP_CMP_EQ"
   969  				}
   970  			]
   971  		}
   972  	]
   973  }`, uint64(0x10000000))
   974  	tmpFile, err := os.CreateTemp("", "profile.json")
   975  	if err != nil {
   976  		c.Fatal(err)
   977  	}
   978  	defer tmpFile.Close()
   979  
   980  	if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
   981  		c.Fatal(err)
   982  	}
   983  	icmd.RunCommand(dockerBinary, "run",
   984  		"--security-opt", "apparmor=unconfined", "--security-opt", "seccomp="+tmpFile.Name(),
   985  		"debian:bullseye-slim", "unshare", "--map-root-user", "--user", "sh", "-c", "whoami").Assert(c, icmd.Expected{
   986  		ExitCode: 1,
   987  		Err:      "Operation not permitted",
   988  	})
   989  }
   990  
   991  // TestRunSeccompProfileDenyCloneUserns checks that 'docker run syscall-test'
   992  // with a the default seccomp profile exits with operation not permitted.
   993  func (s *DockerSuite) TestRunSeccompProfileDenyCloneUserns(c *testing.T) {
   994  	testRequires(c, testEnv.IsLocalDaemon, seccompEnabled)
   995  	ensureSyscallTest(c)
   996  
   997  	icmd.RunCommand(dockerBinary, "run", "syscall-test", "userns-test", "id").Assert(c, icmd.Expected{
   998  		ExitCode: 1,
   999  		Err:      "clone failed: Operation not permitted",
  1000  	})
  1001  }
  1002  
  1003  // TestRunSeccompUnconfinedCloneUserns checks that
  1004  // 'docker run --security-opt seccomp=unconfined syscall-test' allows creating a userns.
  1005  func (s *DockerSuite) TestRunSeccompUnconfinedCloneUserns(c *testing.T) {
  1006  	testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace, unprivilegedUsernsClone)
  1007  	ensureSyscallTest(c)
  1008  
  1009  	// make sure running w privileged is ok
  1010  	icmd.RunCommand(dockerBinary, "run", "--security-opt", "seccomp=unconfined",
  1011  		"syscall-test", "userns-test", "id").Assert(c, icmd.Expected{
  1012  		Out: "nobody",
  1013  	})
  1014  }
  1015  
  1016  // TestRunSeccompAllowPrivCloneUserns checks that 'docker run --privileged syscall-test'
  1017  // allows creating a userns.
  1018  func (s *DockerSuite) TestRunSeccompAllowPrivCloneUserns(c *testing.T) {
  1019  	testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace)
  1020  	ensureSyscallTest(c)
  1021  
  1022  	// make sure running w privileged is ok
  1023  	icmd.RunCommand(dockerBinary, "run", "--privileged", "syscall-test", "userns-test", "id").Assert(c, icmd.Expected{
  1024  		Out: "nobody",
  1025  	})
  1026  }
  1027  
  1028  // TestRunSeccompProfileAllow32Bit checks that 32 bit code can run on x86_64
  1029  // with the default seccomp profile.
  1030  func (s *DockerSuite) TestRunSeccompProfileAllow32Bit(c *testing.T) {
  1031  	testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, IsAmd64)
  1032  	ensureSyscallTest(c)
  1033  
  1034  	icmd.RunCommand(dockerBinary, "run", "syscall-test", "exit32-test").Assert(c, icmd.Success)
  1035  }
  1036  
  1037  // TestRunSeccompAllowSetrlimit checks that 'docker run debian:bullseye-slim ulimit -v 1048510' succeeds.
  1038  func (s *DockerSuite) TestRunSeccompAllowSetrlimit(c *testing.T) {
  1039  	testRequires(c, testEnv.IsLocalDaemon, seccompEnabled)
  1040  
  1041  	// ulimit uses setrlimit, so we want to make sure we don't break it
  1042  	icmd.RunCommand(dockerBinary, "run", "debian:bullseye-slim", "bash", "-c", "ulimit -v 1048510").Assert(c, icmd.Success)
  1043  }
  1044  
  1045  func (s *DockerSuite) TestRunSeccompDefaultProfileAcct(c *testing.T) {
  1046  	testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, NotUserNamespace)
  1047  	ensureSyscallTest(c)
  1048  
  1049  	out, _, err := dockerCmdWithError("run", "syscall-test", "acct-test")
  1050  	if err == nil || !strings.Contains(out, "Operation not permitted") {
  1051  		c.Fatalf("test 0: expected Operation not permitted, got: %s", out)
  1052  	}
  1053  
  1054  	out, _, err = dockerCmdWithError("run", "--cap-add", "sys_admin", "syscall-test", "acct-test")
  1055  	if err == nil || !strings.Contains(out, "Operation not permitted") {
  1056  		c.Fatalf("test 1: expected Operation not permitted, got: %s", out)
  1057  	}
  1058  
  1059  	out, _, err = dockerCmdWithError("run", "--cap-add", "sys_pacct", "syscall-test", "acct-test")
  1060  	if err == nil || !strings.Contains(out, "No such file or directory") {
  1061  		c.Fatalf("test 2: expected No such file or directory, got: %s", out)
  1062  	}
  1063  
  1064  	out, _, err = dockerCmdWithError("run", "--cap-add", "ALL", "syscall-test", "acct-test")
  1065  	if err == nil || !strings.Contains(out, "No such file or directory") {
  1066  		c.Fatalf("test 3: expected No such file or directory, got: %s", out)
  1067  	}
  1068  
  1069  	out, _, err = dockerCmdWithError("run", "--cap-drop", "ALL", "--cap-add", "sys_pacct", "syscall-test", "acct-test")
  1070  	if err == nil || !strings.Contains(out, "No such file or directory") {
  1071  		c.Fatalf("test 4: expected No such file or directory, got: %s", out)
  1072  	}
  1073  }
  1074  
  1075  func (s *DockerSuite) TestRunSeccompDefaultProfileNS(c *testing.T) {
  1076  	testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, NotUserNamespace)
  1077  	ensureSyscallTest(c)
  1078  
  1079  	out, _, err := dockerCmdWithError("run", "syscall-test", "ns-test", "echo", "hello0")
  1080  	if err == nil || !strings.Contains(out, "Operation not permitted") {
  1081  		c.Fatalf("test 0: expected Operation not permitted, got: %s", out)
  1082  	}
  1083  
  1084  	out, _, err = dockerCmdWithError("run", "--cap-add", "sys_admin", "syscall-test", "ns-test", "echo", "hello1")
  1085  	if err != nil || !strings.Contains(out, "hello1") {
  1086  		c.Fatalf("test 1: expected hello1, got: %s, %v", out, err)
  1087  	}
  1088  
  1089  	out, _, err = dockerCmdWithError("run", "--cap-drop", "all", "--cap-add", "sys_admin", "syscall-test", "ns-test", "echo", "hello2")
  1090  	if err != nil || !strings.Contains(out, "hello2") {
  1091  		c.Fatalf("test 2: expected hello2, got: %s, %v", out, err)
  1092  	}
  1093  
  1094  	out, _, err = dockerCmdWithError("run", "--cap-add", "ALL", "syscall-test", "ns-test", "echo", "hello3")
  1095  	if err != nil || !strings.Contains(out, "hello3") {
  1096  		c.Fatalf("test 3: expected hello3, got: %s, %v", out, err)
  1097  	}
  1098  
  1099  	out, _, err = dockerCmdWithError("run", "--cap-add", "ALL", "--security-opt", "seccomp=unconfined", "syscall-test", "acct-test")
  1100  	if err == nil || !strings.Contains(out, "No such file or directory") {
  1101  		c.Fatalf("test 4: expected No such file or directory, got: %s", out)
  1102  	}
  1103  
  1104  	out, _, err = dockerCmdWithError("run", "--cap-add", "ALL", "--security-opt", "seccomp=unconfined", "syscall-test", "ns-test", "echo", "hello4")
  1105  	if err != nil || !strings.Contains(out, "hello4") {
  1106  		c.Fatalf("test 5: expected hello4, got: %s, %v", out, err)
  1107  	}
  1108  }
  1109  
  1110  // TestRunNoNewPrivSetuid checks that --security-opt='no-new-privileges=true' prevents
  1111  // effective uid transitions on executing setuid binaries.
  1112  func (s *DockerSuite) TestRunNoNewPrivSetuid(c *testing.T) {
  1113  	testRequires(c, DaemonIsLinux, NotUserNamespace, testEnv.IsLocalDaemon)
  1114  	ensureNNPTest(c)
  1115  
  1116  	// test that running a setuid binary results in no effective uid transition
  1117  	icmd.RunCommand(dockerBinary, "run", "--security-opt", "no-new-privileges=true", "--user", "1000",
  1118  		"nnp-test", "/usr/bin/nnp-test").Assert(c, icmd.Expected{
  1119  		Out: "EUID=1000",
  1120  	})
  1121  }
  1122  
  1123  // TestLegacyRunNoNewPrivSetuid checks that --security-opt=no-new-privileges prevents
  1124  // effective uid transitions on executing setuid binaries.
  1125  func (s *DockerSuite) TestLegacyRunNoNewPrivSetuid(c *testing.T) {
  1126  	testRequires(c, DaemonIsLinux, NotUserNamespace, testEnv.IsLocalDaemon)
  1127  	ensureNNPTest(c)
  1128  
  1129  	// test that running a setuid binary results in no effective uid transition
  1130  	icmd.RunCommand(dockerBinary, "run", "--security-opt", "no-new-privileges", "--user", "1000",
  1131  		"nnp-test", "/usr/bin/nnp-test").Assert(c, icmd.Expected{
  1132  		Out: "EUID=1000",
  1133  	})
  1134  }
  1135  
  1136  func (s *DockerSuite) TestUserNoEffectiveCapabilitiesChown(c *testing.T) {
  1137  	testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
  1138  	ensureSyscallTest(c)
  1139  
  1140  	// test that a root user has default capability CAP_CHOWN
  1141  	dockerCmd(c, "run", "busybox", "chown", "100", "/tmp")
  1142  	// test that non root user does not have default capability CAP_CHOWN
  1143  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "chown", "100", "/tmp").Assert(c, icmd.Expected{
  1144  		ExitCode: 1,
  1145  		Err:      "Operation not permitted",
  1146  	})
  1147  	// test that root user can drop default capability CAP_CHOWN
  1148  	icmd.RunCommand(dockerBinary, "run", "--cap-drop", "chown", "busybox", "chown", "100", "/tmp").Assert(c, icmd.Expected{
  1149  		ExitCode: 1,
  1150  		Err:      "Operation not permitted",
  1151  	})
  1152  }
  1153  
  1154  func (s *DockerSuite) TestUserNoEffectiveCapabilitiesDacOverride(c *testing.T) {
  1155  	testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
  1156  	ensureSyscallTest(c)
  1157  
  1158  	// test that a root user has default capability CAP_DAC_OVERRIDE
  1159  	dockerCmd(c, "run", "busybox", "sh", "-c", "echo test > /etc/passwd")
  1160  	// test that non root user does not have default capability CAP_DAC_OVERRIDE
  1161  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "sh", "-c", "echo test > /etc/passwd").Assert(c, icmd.Expected{
  1162  		ExitCode: 1,
  1163  		Err:      "Permission denied",
  1164  	})
  1165  }
  1166  
  1167  func (s *DockerSuite) TestUserNoEffectiveCapabilitiesFowner(c *testing.T) {
  1168  	testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
  1169  	ensureSyscallTest(c)
  1170  
  1171  	// test that a root user has default capability CAP_FOWNER
  1172  	dockerCmd(c, "run", "busybox", "chmod", "777", "/etc/passwd")
  1173  	// test that non root user does not have default capability CAP_FOWNER
  1174  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "chmod", "777", "/etc/passwd").Assert(c, icmd.Expected{
  1175  		ExitCode: 1,
  1176  		Err:      "Operation not permitted",
  1177  	})
  1178  	// TODO test that root user can drop default capability CAP_FOWNER
  1179  }
  1180  
  1181  // TODO CAP_KILL
  1182  
  1183  func (s *DockerSuite) TestUserNoEffectiveCapabilitiesSetuid(c *testing.T) {
  1184  	testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
  1185  	ensureSyscallTest(c)
  1186  
  1187  	// test that a root user has default capability CAP_SETUID
  1188  	dockerCmd(c, "run", "syscall-test", "setuid-test")
  1189  	// test that non root user does not have default capability CAP_SETUID
  1190  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "syscall-test", "setuid-test").Assert(c, icmd.Expected{
  1191  		ExitCode: 1,
  1192  		Err:      "Operation not permitted",
  1193  	})
  1194  	// test that root user can drop default capability CAP_SETUID
  1195  	icmd.RunCommand(dockerBinary, "run", "--cap-drop", "setuid", "syscall-test", "setuid-test").Assert(c, icmd.Expected{
  1196  		ExitCode: 1,
  1197  		Err:      "Operation not permitted",
  1198  	})
  1199  }
  1200  
  1201  func (s *DockerSuite) TestUserNoEffectiveCapabilitiesSetgid(c *testing.T) {
  1202  	testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
  1203  	ensureSyscallTest(c)
  1204  
  1205  	// test that a root user has default capability CAP_SETGID
  1206  	dockerCmd(c, "run", "syscall-test", "setgid-test")
  1207  	// test that non root user does not have default capability CAP_SETGID
  1208  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "syscall-test", "setgid-test").Assert(c, icmd.Expected{
  1209  		ExitCode: 1,
  1210  		Err:      "Operation not permitted",
  1211  	})
  1212  	// test that root user can drop default capability CAP_SETGID
  1213  	icmd.RunCommand(dockerBinary, "run", "--cap-drop", "setgid", "syscall-test", "setgid-test").Assert(c, icmd.Expected{
  1214  		ExitCode: 1,
  1215  		Err:      "Operation not permitted",
  1216  	})
  1217  }
  1218  
  1219  // TODO CAP_SETPCAP
  1220  
  1221  // sysctlExists checks if a sysctl exists; runc will error if we add any that do not actually
  1222  // exist, so do not add the default ones if running on an old kernel.
  1223  func sysctlExists(s string) bool {
  1224  	f := filepath.Join("/proc", "sys", strings.Replace(s, ".", "/", -1))
  1225  	_, err := os.Stat(f)
  1226  	return err == nil
  1227  }
  1228  
  1229  func (s *DockerSuite) TestUserNoEffectiveCapabilitiesNetBindService(c *testing.T) {
  1230  	testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
  1231  	ensureSyscallTest(c)
  1232  
  1233  	// test that a root user has default capability CAP_NET_BIND_SERVICE
  1234  	dockerCmd(c, "run", "syscall-test", "socket-test")
  1235  	// test that non root user does not have default capability CAP_NET_BIND_SERVICE
  1236  	// as we allow this via sysctl, also tweak the sysctl back to default
  1237  	args := []string{"run", "--user", "1000:1000"}
  1238  	if sysctlExists("net.ipv4.ip_unprivileged_port_start") {
  1239  		args = append(args, "--sysctl", "net.ipv4.ip_unprivileged_port_start=1024")
  1240  	}
  1241  	args = append(args, "syscall-test", "socket-test")
  1242  	icmd.RunCommand(dockerBinary, args...).Assert(c, icmd.Expected{
  1243  		ExitCode: 1,
  1244  		Err:      "Permission denied",
  1245  	})
  1246  	// test that root user can drop default capability CAP_NET_BIND_SERVICE
  1247  	args = []string{"run", "--cap-drop", "net_bind_service"}
  1248  	if sysctlExists("net.ipv4.ip_unprivileged_port_start") {
  1249  		args = append(args, "--sysctl", "net.ipv4.ip_unprivileged_port_start=1024")
  1250  	}
  1251  	args = append(args, "syscall-test", "socket-test")
  1252  	icmd.RunCommand(dockerBinary, args...).Assert(c, icmd.Expected{
  1253  		ExitCode: 1,
  1254  		Err:      "Permission denied",
  1255  	})
  1256  }
  1257  
  1258  func (s *DockerSuite) TestUserNoEffectiveCapabilitiesNetRaw(c *testing.T) {
  1259  	testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
  1260  	ensureSyscallTest(c)
  1261  
  1262  	// test that a root user has default capability CAP_NET_RAW
  1263  	dockerCmd(c, "run", "syscall-test", "raw-test")
  1264  	// test that non root user does not have default capability CAP_NET_RAW
  1265  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "syscall-test", "raw-test").Assert(c, icmd.Expected{
  1266  		ExitCode: 1,
  1267  		Err:      "Operation not permitted",
  1268  	})
  1269  	// test that root user can drop default capability CAP_NET_RAW
  1270  	icmd.RunCommand(dockerBinary, "run", "--cap-drop", "net_raw", "syscall-test", "raw-test").Assert(c, icmd.Expected{
  1271  		ExitCode: 1,
  1272  		Err:      "Operation not permitted",
  1273  	})
  1274  }
  1275  
  1276  func (s *DockerSuite) TestUserNoEffectiveCapabilitiesChroot(c *testing.T) {
  1277  	testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
  1278  	ensureSyscallTest(c)
  1279  
  1280  	// test that a root user has default capability CAP_SYS_CHROOT
  1281  	dockerCmd(c, "run", "busybox", "chroot", "/", "/bin/true")
  1282  	// test that non root user does not have default capability CAP_SYS_CHROOT
  1283  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "chroot", "/", "/bin/true").Assert(c, icmd.Expected{
  1284  		ExitCode: 1,
  1285  		Err:      "Operation not permitted",
  1286  	})
  1287  	// test that root user can drop default capability CAP_SYS_CHROOT
  1288  	icmd.RunCommand(dockerBinary, "run", "--cap-drop", "sys_chroot", "busybox", "chroot", "/", "/bin/true").Assert(c, icmd.Expected{
  1289  		ExitCode: 1,
  1290  		Err:      "Operation not permitted",
  1291  	})
  1292  }
  1293  
  1294  func (s *DockerSuite) TestUserNoEffectiveCapabilitiesMknod(c *testing.T) {
  1295  	testRequires(c, DaemonIsLinux, NotUserNamespace, testEnv.IsLocalDaemon)
  1296  	ensureSyscallTest(c)
  1297  
  1298  	// test that a root user has default capability CAP_MKNOD
  1299  	dockerCmd(c, "run", "busybox", "mknod", "/tmp/node", "b", "1", "2")
  1300  	// test that non root user does not have default capability CAP_MKNOD
  1301  	// test that root user can drop default capability CAP_SYS_CHROOT
  1302  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "mknod", "/tmp/node", "b", "1", "2").Assert(c, icmd.Expected{
  1303  		ExitCode: 1,
  1304  		Err:      "Operation not permitted",
  1305  	})
  1306  	// test that root user can drop default capability CAP_MKNOD
  1307  	icmd.RunCommand(dockerBinary, "run", "--cap-drop", "mknod", "busybox", "mknod", "/tmp/node", "b", "1", "2").Assert(c, icmd.Expected{
  1308  		ExitCode: 1,
  1309  		Err:      "Operation not permitted",
  1310  	})
  1311  }
  1312  
  1313  // TODO CAP_AUDIT_WRITE
  1314  // TODO CAP_SETFCAP
  1315  
  1316  func (s *DockerSuite) TestRunApparmorProcDirectory(c *testing.T) {
  1317  	testRequires(c, testEnv.IsLocalDaemon, Apparmor)
  1318  
  1319  	// running w seccomp unconfined tests the apparmor profile
  1320  	result := icmd.RunCommand(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "busybox", "chmod", "777", "/proc/1/cgroup")
  1321  	result.Assert(c, icmd.Expected{ExitCode: 1})
  1322  	if !(strings.Contains(result.Combined(), "Permission denied") || strings.Contains(result.Combined(), "Operation not permitted")) {
  1323  		c.Fatalf("expected chmod 777 /proc/1/cgroup to fail, got %s: %v", result.Combined(), result.Error)
  1324  	}
  1325  
  1326  	result = icmd.RunCommand(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "busybox", "chmod", "777", "/proc/1/attr/current")
  1327  	result.Assert(c, icmd.Expected{ExitCode: 1})
  1328  	if !(strings.Contains(result.Combined(), "Permission denied") || strings.Contains(result.Combined(), "Operation not permitted")) {
  1329  		c.Fatalf("expected chmod 777 /proc/1/attr/current to fail, got %s: %v", result.Combined(), result.Error)
  1330  	}
  1331  }
  1332  
  1333  // make sure the default profile can be successfully parsed (using unshare as it is
  1334  // something which we know is blocked in the default profile)
  1335  func (s *DockerSuite) TestRunSeccompWithDefaultProfile(c *testing.T) {
  1336  	testRequires(c, testEnv.IsLocalDaemon, seccompEnabled)
  1337  
  1338  	out, _, err := dockerCmdWithError("run", "--security-opt", "seccomp=../profiles/seccomp/default.json", "debian:bullseye-slim", "unshare", "--map-root-user", "--user", "sh", "-c", "whoami")
  1339  	assert.ErrorContains(c, err, "", out)
  1340  	assert.Equal(c, strings.TrimSpace(out), "unshare: unshare failed: Operation not permitted")
  1341  }
  1342  
  1343  // TestRunDeviceSymlink checks run with device that follows symlink (#13840 and #22271)
  1344  func (s *DockerSuite) TestRunDeviceSymlink(c *testing.T) {
  1345  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm, testEnv.IsLocalDaemon)
  1346  	if _, err := os.Stat("/dev/zero"); err != nil {
  1347  		c.Skip("Host does not have /dev/zero")
  1348  	}
  1349  
  1350  	// Create a temporary directory to create symlink
  1351  	tmpDir, err := os.MkdirTemp("", "docker_device_follow_symlink_tests")
  1352  	assert.NilError(c, err)
  1353  
  1354  	defer os.RemoveAll(tmpDir)
  1355  
  1356  	// Create a symbolic link to /dev/zero
  1357  	symZero := filepath.Join(tmpDir, "zero")
  1358  	err = os.Symlink("/dev/zero", symZero)
  1359  	assert.NilError(c, err)
  1360  
  1361  	// Create a temporary file "temp" inside tmpDir, write some data to "tmpDir/temp",
  1362  	// then create a symlink "tmpDir/file" to the temporary file "tmpDir/temp".
  1363  	tmpFile := filepath.Join(tmpDir, "temp")
  1364  	err = os.WriteFile(tmpFile, []byte("temp"), 0666)
  1365  	assert.NilError(c, err)
  1366  	symFile := filepath.Join(tmpDir, "file")
  1367  	err = os.Symlink(tmpFile, symFile)
  1368  	assert.NilError(c, err)
  1369  
  1370  	// Create a symbolic link to /dev/zero, this time with a relative path (#22271)
  1371  	err = os.Symlink("zero", "/dev/symzero")
  1372  	if err != nil {
  1373  		c.Fatal("/dev/symzero creation failed")
  1374  	}
  1375  	// We need to remove this symbolic link here as it is created in /dev/, not temporary directory as above
  1376  	defer os.Remove("/dev/symzero")
  1377  
  1378  	// md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23
  1379  	out, _ := dockerCmd(c, "run", "--device", symZero+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  1380  	assert.Assert(c, strings.Contains(strings.Trim(out, "\r\n"), "bb7df04e1b0a2570657527a7e108ae23"), "expected output bb7df04e1b0a2570657527a7e108ae23")
  1381  	// symlink "tmpDir/file" to a file "tmpDir/temp" will result in an error as it is not a device.
  1382  	out, _, err = dockerCmdWithError("run", "--device", symFile+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  1383  	assert.ErrorContains(c, err, "")
  1384  	assert.Assert(c, strings.Contains(strings.Trim(out, "\r\n"), "not a device node"), "expected output 'not a device node'")
  1385  	// md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23 (this time check with relative path backed, see #22271)
  1386  	out, _ = dockerCmd(c, "run", "--device", "/dev/symzero:/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  1387  	assert.Assert(c, strings.Contains(strings.Trim(out, "\r\n"), "bb7df04e1b0a2570657527a7e108ae23"), "expected output bb7df04e1b0a2570657527a7e108ae23")
  1388  }
  1389  
  1390  // TestRunPIDsLimit makes sure the pids cgroup is set with --pids-limit
  1391  func (s *DockerSuite) TestRunPIDsLimit(c *testing.T) {
  1392  	testRequires(c, testEnv.IsLocalDaemon, pidsLimit)
  1393  
  1394  	file := "/sys/fs/cgroup/pids/pids.max"
  1395  	out, _ := dockerCmd(c, "run", "--name", "skittles", "--pids-limit", "4", "busybox", "cat", file)
  1396  	assert.Equal(c, strings.TrimSpace(out), "4")
  1397  
  1398  	out = inspectField(c, "skittles", "HostConfig.PidsLimit")
  1399  	assert.Equal(c, out, "4", "setting the pids limit failed")
  1400  }
  1401  
  1402  func (s *DockerSuite) TestRunPrivilegedAllowedDevices(c *testing.T) {
  1403  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  1404  
  1405  	file := "/sys/fs/cgroup/devices/devices.list"
  1406  	out, _ := dockerCmd(c, "run", "--privileged", "busybox", "cat", file)
  1407  	c.Logf("out: %q", out)
  1408  	assert.Equal(c, strings.TrimSpace(out), "a *:* rwm")
  1409  }
  1410  
  1411  func (s *DockerSuite) TestRunUserDeviceAllowed(c *testing.T) {
  1412  	testRequires(c, DaemonIsLinux)
  1413  
  1414  	fi, err := os.Stat("/dev/snd/timer")
  1415  	if err != nil {
  1416  		c.Skip("Host does not have /dev/snd/timer")
  1417  	}
  1418  	stat, ok := fi.Sys().(*syscall.Stat_t)
  1419  	if !ok {
  1420  		c.Skip("Could not stat /dev/snd/timer")
  1421  	}
  1422  
  1423  	file := "/sys/fs/cgroup/devices/devices.list"
  1424  	out, _ := dockerCmd(c, "run", "--device", "/dev/snd/timer:w", "busybox", "cat", file)
  1425  	assert.Assert(c, strings.Contains(out, fmt.Sprintf("c %d:%d w", stat.Rdev/256, stat.Rdev%256)))
  1426  }
  1427  
  1428  func (s *DockerDaemonSuite) TestRunSeccompJSONNewFormat(c *testing.T) {
  1429  	testRequires(c, seccompEnabled)
  1430  
  1431  	s.d.StartWithBusybox(c)
  1432  
  1433  	jsonData := `{
  1434  	"defaultAction": "SCMP_ACT_ALLOW",
  1435  	"syscalls": [
  1436  		{
  1437  			"names": ["chmod", "fchmod", "fchmodat"],
  1438  			"action": "SCMP_ACT_ERRNO"
  1439  		}
  1440  	]
  1441  }`
  1442  	tmpFile, err := os.CreateTemp("", "profile.json")
  1443  	assert.NilError(c, err)
  1444  	defer tmpFile.Close()
  1445  	_, err = tmpFile.Write([]byte(jsonData))
  1446  	assert.NilError(c, err)
  1447  
  1448  	out, err := s.d.Cmd("run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "777", ".")
  1449  	assert.ErrorContains(c, err, "")
  1450  	assert.Assert(c, strings.Contains(out, "Operation not permitted"))
  1451  }
  1452  
  1453  func (s *DockerDaemonSuite) TestRunSeccompJSONNoNameAndNames(c *testing.T) {
  1454  	testRequires(c, seccompEnabled)
  1455  
  1456  	s.d.StartWithBusybox(c)
  1457  
  1458  	jsonData := `{
  1459  	"defaultAction": "SCMP_ACT_ALLOW",
  1460  	"syscalls": [
  1461  		{
  1462  			"name": "chmod",
  1463  			"names": ["fchmod", "fchmodat"],
  1464  			"action": "SCMP_ACT_ERRNO"
  1465  		}
  1466  	]
  1467  }`
  1468  	tmpFile, err := os.CreateTemp("", "profile.json")
  1469  	assert.NilError(c, err)
  1470  	defer tmpFile.Close()
  1471  	_, err = tmpFile.Write([]byte(jsonData))
  1472  	assert.NilError(c, err)
  1473  
  1474  	out, err := s.d.Cmd("run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "777", ".")
  1475  	assert.ErrorContains(c, err, "")
  1476  	assert.Assert(c, strings.Contains(out, "'name' and 'names' were specified in the seccomp profile, use either 'name' or 'names'"))
  1477  }
  1478  
  1479  func (s *DockerDaemonSuite) TestRunSeccompJSONNoArchAndArchMap(c *testing.T) {
  1480  	testRequires(c, seccompEnabled)
  1481  
  1482  	s.d.StartWithBusybox(c)
  1483  
  1484  	jsonData := `{
  1485  	"archMap": [
  1486  		{
  1487  			"architecture": "SCMP_ARCH_X86_64",
  1488  			"subArchitectures": [
  1489  				"SCMP_ARCH_X86",
  1490  				"SCMP_ARCH_X32"
  1491  			]
  1492  		}
  1493  	],
  1494  	"architectures": [
  1495  		"SCMP_ARCH_X32"
  1496  	],
  1497  	"defaultAction": "SCMP_ACT_ALLOW",
  1498  	"syscalls": [
  1499  		{
  1500  			"names": ["chmod", "fchmod", "fchmodat"],
  1501  			"action": "SCMP_ACT_ERRNO"
  1502  		}
  1503  	]
  1504  }`
  1505  	tmpFile, err := os.CreateTemp("", "profile.json")
  1506  	assert.NilError(c, err)
  1507  	defer tmpFile.Close()
  1508  	_, err = tmpFile.Write([]byte(jsonData))
  1509  	assert.NilError(c, err)
  1510  
  1511  	out, err := s.d.Cmd("run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "777", ".")
  1512  	assert.ErrorContains(c, err, "")
  1513  	assert.Assert(c, strings.Contains(out, "'architectures' and 'archMap' were specified in the seccomp profile, use either 'architectures' or 'archMap'"))
  1514  }
  1515  
  1516  func (s *DockerDaemonSuite) TestRunWithDaemonDefaultSeccompProfile(c *testing.T) {
  1517  	testRequires(c, seccompEnabled)
  1518  
  1519  	s.d.StartWithBusybox(c)
  1520  
  1521  	// 1) verify I can run containers with the Docker default shipped profile which allows chmod
  1522  	_, err := s.d.Cmd("run", "busybox", "chmod", "777", ".")
  1523  	assert.NilError(c, err)
  1524  
  1525  	jsonData := `{
  1526  	"defaultAction": "SCMP_ACT_ALLOW",
  1527  	"syscalls": [
  1528  		{
  1529  			"name": "chmod",
  1530  			"action": "SCMP_ACT_ERRNO"
  1531  		},
  1532  		{
  1533  			"name": "fchmodat",
  1534  			"action": "SCMP_ACT_ERRNO"
  1535  		}
  1536  	]
  1537  }`
  1538  	tmpFile, err := os.CreateTemp("", "profile.json")
  1539  	assert.NilError(c, err)
  1540  	defer tmpFile.Close()
  1541  	_, err = tmpFile.Write([]byte(jsonData))
  1542  	assert.NilError(c, err)
  1543  
  1544  	// 2) restart the daemon and add a custom seccomp profile in which we deny chmod
  1545  	s.d.Restart(c, "--seccomp-profile="+tmpFile.Name())
  1546  
  1547  	out, err := s.d.Cmd("run", "busybox", "chmod", "777", ".")
  1548  	assert.ErrorContains(c, err, "")
  1549  	assert.Assert(c, strings.Contains(out, "Operation not permitted"))
  1550  }
  1551  
  1552  func (s *DockerSuite) TestRunWithNanoCPUs(c *testing.T) {
  1553  	testRequires(c, cpuCfsQuota, cpuCfsPeriod)
  1554  
  1555  	file1 := "/sys/fs/cgroup/cpu/cpu.cfs_quota_us"
  1556  	file2 := "/sys/fs/cgroup/cpu/cpu.cfs_period_us"
  1557  	out, _ := dockerCmd(c, "run", "--cpus", "0.5", "--name", "test", "busybox", "sh", "-c", fmt.Sprintf("cat %s && cat %s", file1, file2))
  1558  	assert.Equal(c, strings.TrimSpace(out), "50000\n100000")
  1559  
  1560  	clt, err := client.NewClientWithOpts(client.FromEnv)
  1561  	assert.NilError(c, err)
  1562  	inspect, err := clt.ContainerInspect(context.Background(), "test")
  1563  	assert.NilError(c, err)
  1564  	assert.Equal(c, inspect.HostConfig.NanoCPUs, int64(500000000))
  1565  
  1566  	out = inspectField(c, "test", "HostConfig.CpuQuota")
  1567  	assert.Equal(c, out, "0", "CPU CFS quota should be 0")
  1568  	out = inspectField(c, "test", "HostConfig.CpuPeriod")
  1569  	assert.Equal(c, out, "0", "CPU CFS period should be 0")
  1570  
  1571  	out, _, err = dockerCmdWithError("run", "--cpus", "0.5", "--cpu-quota", "50000", "--cpu-period", "100000", "busybox", "sh")
  1572  	assert.ErrorContains(c, err, "")
  1573  	assert.Assert(c, strings.Contains(out, "Conflicting options: Nano CPUs and CPU Period cannot both be set"))
  1574  }