github.com/Prakhar-Agarwal-byte/moby@v0.0.0-20231027092010-a14e3e8ab87e/integration-cli/docker_cli_run_unix_test.go (about) 1 //go:build !windows 2 3 package main 4 5 import ( 6 "bufio" 7 "encoding/json" 8 "fmt" 9 "os" 10 "os/exec" 11 "path/filepath" 12 "regexp" 13 "runtime" 14 "strconv" 15 "strings" 16 "syscall" 17 "testing" 18 "time" 19 20 "github.com/Prakhar-Agarwal-byte/moby/client" 21 "github.com/Prakhar-Agarwal-byte/moby/integration-cli/cli" 22 "github.com/Prakhar-Agarwal-byte/moby/integration-cli/cli/build" 23 "github.com/Prakhar-Agarwal-byte/moby/pkg/parsers" 24 "github.com/Prakhar-Agarwal-byte/moby/pkg/sysinfo" 25 "github.com/Prakhar-Agarwal-byte/moby/testutil" 26 "github.com/creack/pty" 27 "github.com/moby/sys/mount" 28 "gotest.tools/v3/assert" 29 "gotest.tools/v3/icmd" 30 ) 31 32 // #6509 33 func (s *DockerCLIRunSuite) TestRunRedirectStdout(c *testing.T) { 34 checkRedirect := func(command string) { 35 _, tty, err := pty.Open() 36 assert.Assert(c, err == nil, "Could not open pty") 37 cmd := exec.Command("sh", "-c", command) 38 cmd.Stdin = tty 39 cmd.Stdout = tty 40 cmd.Stderr = tty 41 assert.NilError(c, cmd.Start()) 42 ch := make(chan error, 1) 43 go func() { 44 ch <- cmd.Wait() 45 close(ch) 46 }() 47 48 select { 49 case <-time.After(10 * time.Second): 50 c.Fatal("command timeout") 51 case err := <-ch: 52 assert.Assert(c, err == nil, "wait err") 53 } 54 } 55 56 checkRedirect(dockerBinary + " run -i busybox cat /etc/passwd | grep -q root") 57 checkRedirect(dockerBinary + " run busybox cat /etc/passwd | grep -q root") 58 } 59 60 // Test recursive bind mount works by default 61 func (s *DockerCLIRunSuite) TestRunWithVolumesIsRecursive(c *testing.T) { 62 // /tmp gets permission denied 63 testRequires(c, NotUserNamespace, testEnv.IsLocalDaemon) 64 tmpDir, err := os.MkdirTemp("", "docker_recursive_mount_test") 65 assert.NilError(c, err) 66 67 defer os.RemoveAll(tmpDir) 68 69 // Create a temporary tmpfs mount. 70 tmpfsDir := filepath.Join(tmpDir, "tmpfs") 71 assert.Assert(c, os.MkdirAll(tmpfsDir, 0o777) == nil, "failed to mkdir at %s", tmpfsDir) 72 assert.Assert(c, mount.Mount("tmpfs", tmpfsDir, "tmpfs", "") == nil, "failed to create a tmpfs mount at %s", tmpfsDir) 73 74 f, err := os.CreateTemp(tmpfsDir, "touch-me") 75 assert.NilError(c, err) 76 defer f.Close() 77 78 out := cli.DockerCmd(c, "run", "--name", "test-data", "--volume", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox:latest", "ls", "/tmp/tmpfs").Combined() 79 assert.Assert(c, strings.Contains(out, filepath.Base(f.Name())), "Recursive bind mount test failed. Expected file not found") 80 } 81 82 func (s *DockerCLIRunSuite) TestRunDeviceDirectory(c *testing.T) { 83 testRequires(c, DaemonIsLinux, NotUserNamespace) 84 if _, err := os.Stat("/dev/snd"); err != nil { 85 c.Skip("Host does not have /dev/snd") 86 } 87 88 out := cli.DockerCmd(c, "run", "--device", "/dev/snd:/dev/snd", "busybox", "sh", "-c", "ls /dev/snd/").Combined() 89 assert.Assert(c, strings.Contains(strings.Trim(out, "\r\n"), "timer"), "expected output /dev/snd/timer") 90 out = cli.DockerCmd(c, "run", "--device", "/dev/snd:/dev/othersnd", "busybox", "sh", "-c", "ls /dev/othersnd/").Combined() 91 assert.Assert(c, strings.Contains(strings.Trim(out, "\r\n"), "seq"), "expected output /dev/othersnd/seq") 92 } 93 94 // TestRunAttachDetach checks attaching and detaching with the default escape sequence. 95 func (s *DockerCLIRunSuite) TestRunAttachDetach(c *testing.T) { 96 const name = "attach-detach" 97 98 cli.DockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat") 99 100 cmd := exec.Command(dockerBinary, "attach", name) 101 stdout, err := cmd.StdoutPipe() 102 assert.NilError(c, err) 103 cpty, tty, err := pty.Open() 104 assert.NilError(c, err) 105 defer cpty.Close() 106 cmd.Stdin = tty 107 assert.NilError(c, cmd.Start()) 108 cli.WaitRun(c, name) 109 110 _, err = cpty.Write([]byte("hello\n")) 111 assert.NilError(c, err) 112 113 out, err := bufio.NewReader(stdout).ReadString('\n') 114 assert.NilError(c, err) 115 assert.Equal(c, strings.TrimSpace(out), "hello") 116 117 // escape sequence 118 _, err = cpty.Write([]byte{16}) 119 assert.NilError(c, err) 120 time.Sleep(100 * time.Millisecond) 121 _, err = cpty.Write([]byte{17}) 122 assert.NilError(c, err) 123 124 ch := make(chan struct{}, 1) 125 go func() { 126 cmd.Wait() 127 ch <- struct{}{} 128 }() 129 130 select { 131 case <-ch: 132 case <-time.After(10 * time.Second): 133 c.Fatal("timed out waiting for container to exit") 134 } 135 136 running := inspectField(c, name, "State.Running") 137 assert.Equal(c, running, "true", "expected container to still be running") 138 139 out = cli.DockerCmd(c, "events", "--since=0", "--until", daemonUnixTime(c), "-f", "container="+name).Stdout() 140 // attach and detach event should be monitored 141 assert.Assert(c, strings.Contains(out, "attach")) 142 assert.Assert(c, strings.Contains(out, "detach")) 143 } 144 145 // TestRunAttachDetachFromFlag checks attaching and detaching with the escape sequence specified via flags. 146 func (s *DockerCLIRunSuite) TestRunAttachDetachFromFlag(c *testing.T) { 147 const name = "attach-detach" 148 keyCtrlA := []byte{1} 149 keyA := []byte{97} 150 151 cli.DockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat") 152 153 cmd := exec.Command(dockerBinary, "attach", "--detach-keys=ctrl-a,a", name) 154 stdout, err := cmd.StdoutPipe() 155 if err != nil { 156 c.Fatal(err) 157 } 158 cpty, tty, err := pty.Open() 159 if err != nil { 160 c.Fatal(err) 161 } 162 defer cpty.Close() 163 cmd.Stdin = tty 164 if err := cmd.Start(); err != nil { 165 c.Fatal(err) 166 } 167 cli.WaitRun(c, name) 168 169 if _, err := cpty.Write([]byte("hello\n")); err != nil { 170 c.Fatal(err) 171 } 172 173 out, err := bufio.NewReader(stdout).ReadString('\n') 174 if err != nil { 175 c.Fatal(err) 176 } 177 if strings.TrimSpace(out) != "hello" { 178 c.Fatalf("expected 'hello', got %q", out) 179 } 180 181 // escape sequence 182 if _, err := cpty.Write(keyCtrlA); err != nil { 183 c.Fatal(err) 184 } 185 time.Sleep(100 * time.Millisecond) 186 if _, err := cpty.Write(keyA); err != nil { 187 c.Fatal(err) 188 } 189 190 ch := make(chan struct{}, 1) 191 go func() { 192 cmd.Wait() 193 ch <- struct{}{} 194 }() 195 196 select { 197 case <-ch: 198 case <-time.After(10 * time.Second): 199 c.Fatal("timed out waiting for container to exit") 200 } 201 202 running := inspectField(c, name, "State.Running") 203 assert.Equal(c, running, "true", "expected container to still be running") 204 } 205 206 // TestRunAttachDetachFromInvalidFlag checks attaching and detaching with the escape sequence specified via flags. 207 func (s *DockerCLIRunSuite) TestRunAttachDetachFromInvalidFlag(c *testing.T) { 208 const name = "attach-detach" 209 cli.DockerCmd(c, "run", "--name", name, "-itd", "busybox", "top") 210 cli.WaitRun(c, name) 211 212 // specify an invalid detach key, container will ignore it and use default 213 cmd := exec.Command(dockerBinary, "attach", "--detach-keys=ctrl-A,a", name) 214 stdout, err := cmd.StdoutPipe() 215 if err != nil { 216 c.Fatal(err) 217 } 218 cpty, tty, err := pty.Open() 219 if err != nil { 220 c.Fatal(err) 221 } 222 defer cpty.Close() 223 cmd.Stdin = tty 224 if err := cmd.Start(); err != nil { 225 c.Fatal(err) 226 } 227 go cmd.Wait() 228 229 bufReader := bufio.NewReader(stdout) 230 out, err := bufReader.ReadString('\n') 231 if err != nil { 232 c.Fatal(err) 233 } 234 // it should print a warning to indicate the detach key flag is invalid 235 errStr := "Invalid detach keys (ctrl-A,a) provided" 236 assert.Equal(c, strings.TrimSpace(out), errStr) 237 } 238 239 // TestRunAttachDetachFromConfig checks attaching and detaching with the escape sequence specified via config file. 240 func (s *DockerCLIRunSuite) TestRunAttachDetachFromConfig(c *testing.T) { 241 keyCtrlA := []byte{1} 242 keyA := []byte{97} 243 244 // Setup config 245 tmpDir, err := os.MkdirTemp("", "fake-home") 246 assert.NilError(c, err) 247 defer os.RemoveAll(tmpDir) 248 249 dotDocker := filepath.Join(tmpDir, ".docker") 250 os.Mkdir(dotDocker, 0o600) 251 tmpCfg := filepath.Join(dotDocker, "config.json") 252 253 if runtime.GOOS == "windows" { 254 c.Setenv("USERPROFILE", tmpDir) 255 } else { 256 c.Setenv("HOME", tmpDir) 257 } 258 259 data := `{ 260 "detachKeys": "ctrl-a,a" 261 }` 262 263 err = os.WriteFile(tmpCfg, []byte(data), 0o600) 264 assert.NilError(c, err) 265 266 // Then do the work 267 const name = "attach-detach" 268 cli.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 cli.WaitRun(c, name) 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 *DockerCLIRunSuite) TestRunAttachDetachKeysOverrideConfig(c *testing.T) { 325 keyCtrlA := []byte{1} 326 keyA := []byte{97} 327 328 // Setup config 329 tmpDir, err := os.MkdirTemp("", "fake-home") 330 assert.NilError(c, err) 331 defer os.RemoveAll(tmpDir) 332 333 dotDocker := filepath.Join(tmpDir, ".docker") 334 os.Mkdir(dotDocker, 0o600) 335 tmpCfg := filepath.Join(dotDocker, "config.json") 336 337 if runtime.GOOS == "windows" { 338 c.Setenv("USERPROFILE", tmpDir) 339 } else { 340 c.Setenv("HOME", tmpDir) 341 } 342 343 data := `{ 344 "detachKeys": "ctrl-e,e" 345 }` 346 347 err = os.WriteFile(tmpCfg, []byte(data), 0o600) 348 assert.NilError(c, err) 349 350 // Then do the work 351 const name = "attach-detach" 352 cli.DockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat") 353 354 cmd := exec.Command(dockerBinary, "attach", "--detach-keys=ctrl-a,a", name) 355 stdout, err := cmd.StdoutPipe() 356 if err != nil { 357 c.Fatal(err) 358 } 359 cpty, tty, err := pty.Open() 360 if err != nil { 361 c.Fatal(err) 362 } 363 defer cpty.Close() 364 cmd.Stdin = tty 365 if err := cmd.Start(); err != nil { 366 c.Fatal(err) 367 } 368 cli.WaitRun(c, name) 369 370 if _, err := cpty.Write([]byte("hello\n")); err != nil { 371 c.Fatal(err) 372 } 373 374 out, err := bufio.NewReader(stdout).ReadString('\n') 375 if err != nil { 376 c.Fatal(err) 377 } 378 if strings.TrimSpace(out) != "hello" { 379 c.Fatalf("expected 'hello', got %q", out) 380 } 381 382 // escape sequence 383 if _, err := cpty.Write(keyCtrlA); err != nil { 384 c.Fatal(err) 385 } 386 time.Sleep(100 * time.Millisecond) 387 if _, err := cpty.Write(keyA); err != nil { 388 c.Fatal(err) 389 } 390 391 ch := make(chan struct{}, 1) 392 go func() { 393 cmd.Wait() 394 ch <- struct{}{} 395 }() 396 397 select { 398 case <-ch: 399 case <-time.After(10 * time.Second): 400 c.Fatal("timed out waiting for container to exit") 401 } 402 403 running := inspectField(c, name, "State.Running") 404 assert.Equal(c, running, "true", "expected container to still be running") 405 } 406 407 func (s *DockerCLIRunSuite) TestRunAttachInvalidDetachKeySequencePreserved(c *testing.T) { 408 const name = "attach-detach" 409 keyA := []byte{97} 410 keyB := []byte{98} 411 412 cli.DockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat") 413 414 cmd := exec.Command(dockerBinary, "attach", "--detach-keys=a,b,c", name) 415 stdout, err := cmd.StdoutPipe() 416 if err != nil { 417 c.Fatal(err) 418 } 419 cpty, tty, err := pty.Open() 420 if err != nil { 421 c.Fatal(err) 422 } 423 defer cpty.Close() 424 cmd.Stdin = tty 425 if err := cmd.Start(); err != nil { 426 c.Fatal(err) 427 } 428 go cmd.Wait() 429 cli.WaitRun(c, name) 430 431 // Invalid escape sequence aba, should print aba in output 432 if _, err := cpty.Write(keyA); err != nil { 433 c.Fatal(err) 434 } 435 time.Sleep(100 * time.Millisecond) 436 if _, err := cpty.Write(keyB); err != nil { 437 c.Fatal(err) 438 } 439 time.Sleep(100 * time.Millisecond) 440 if _, err := cpty.Write(keyA); err != nil { 441 c.Fatal(err) 442 } 443 time.Sleep(100 * time.Millisecond) 444 if _, err := cpty.Write([]byte("\n")); err != nil { 445 c.Fatal(err) 446 } 447 448 out, err := bufio.NewReader(stdout).ReadString('\n') 449 if err != nil { 450 c.Fatal(err) 451 } 452 if strings.TrimSpace(out) != "aba" { 453 c.Fatalf("expected 'aba', got %q", out) 454 } 455 } 456 457 // "test" should be printed 458 func (s *DockerCLIRunSuite) TestRunWithCPUQuota(c *testing.T) { 459 testRequires(c, cpuCfsQuota) 460 461 const file = "/sys/fs/cgroup/cpu/cpu.cfs_quota_us" 462 out := cli.DockerCmd(c, "run", "--cpu-quota", "8000", "--name", "test", "busybox", "cat", file).Combined() 463 assert.Equal(c, strings.TrimSpace(out), "8000") 464 465 out = inspectField(c, "test", "HostConfig.CpuQuota") 466 assert.Equal(c, out, "8000", "setting the CPU CFS quota failed") 467 } 468 469 func (s *DockerCLIRunSuite) TestRunWithCpuPeriod(c *testing.T) { 470 testRequires(c, cpuCfsPeriod) 471 472 const file = "/sys/fs/cgroup/cpu/cpu.cfs_period_us" 473 out := cli.DockerCmd(c, "run", "--cpu-period", "50000", "--name", "test", "busybox", "cat", file).Combined() 474 assert.Equal(c, strings.TrimSpace(out), "50000") 475 476 out = cli.DockerCmd(c, "run", "--cpu-period", "0", "busybox", "cat", file).Combined() 477 assert.Equal(c, strings.TrimSpace(out), "100000") 478 479 out = inspectField(c, "test", "HostConfig.CpuPeriod") 480 assert.Equal(c, out, "50000", "setting the CPU CFS period failed") 481 } 482 483 func (s *DockerCLIRunSuite) TestRunWithInvalidCpuPeriod(c *testing.T) { 484 testRequires(c, cpuCfsPeriod) 485 out, _, err := dockerCmdWithError("run", "--cpu-period", "900", "busybox", "true") 486 assert.ErrorContains(c, err, "") 487 expected := "CPU cfs period can not be less than 1ms (i.e. 1000) or larger than 1s (i.e. 1000000)" 488 assert.Assert(c, strings.Contains(out, expected)) 489 490 out, _, err = dockerCmdWithError("run", "--cpu-period", "2000000", "busybox", "true") 491 assert.ErrorContains(c, err, "") 492 assert.Assert(c, strings.Contains(out, expected)) 493 494 out, _, err = dockerCmdWithError("run", "--cpu-period", "-3", "busybox", "true") 495 assert.ErrorContains(c, err, "") 496 assert.Assert(c, strings.Contains(out, expected)) 497 } 498 499 func (s *DockerCLIRunSuite) TestRunWithCPUShares(c *testing.T) { 500 testRequires(c, cpuShare) 501 502 const file = "/sys/fs/cgroup/cpu/cpu.shares" 503 out := cli.DockerCmd(c, "run", "--cpu-shares", "1000", "--name", "test", "busybox", "cat", file).Combined() 504 assert.Equal(c, strings.TrimSpace(out), "1000") 505 506 out = inspectField(c, "test", "HostConfig.CPUShares") 507 assert.Equal(c, out, "1000") 508 } 509 510 // "test" should be printed 511 func (s *DockerCLIRunSuite) TestRunEchoStdoutWithCPUSharesAndMemoryLimit(c *testing.T) { 512 testRequires(c, cpuShare) 513 testRequires(c, memoryLimitSupport) 514 cli.DockerCmd(c, "run", "--cpu-shares", "1000", "-m", "32m", "busybox", "echo", "test").Assert(c, icmd.Expected{ 515 Out: "test\n", 516 }) 517 } 518 519 func (s *DockerCLIRunSuite) TestRunWithCpusetCpus(c *testing.T) { 520 testRequires(c, cgroupCpuset) 521 522 const file = "/sys/fs/cgroup/cpuset/cpuset.cpus" 523 out := cli.DockerCmd(c, "run", "--cpuset-cpus", "0", "--name", "test", "busybox", "cat", file).Combined() 524 assert.Equal(c, strings.TrimSpace(out), "0") 525 526 out = inspectField(c, "test", "HostConfig.CpusetCpus") 527 assert.Equal(c, out, "0") 528 } 529 530 func (s *DockerCLIRunSuite) TestRunWithCpusetMems(c *testing.T) { 531 testRequires(c, cgroupCpuset) 532 533 const file = "/sys/fs/cgroup/cpuset/cpuset.mems" 534 out := cli.DockerCmd(c, "run", "--cpuset-mems", "0", "--name", "test", "busybox", "cat", file).Combined() 535 assert.Equal(c, strings.TrimSpace(out), "0") 536 537 out = inspectField(c, "test", "HostConfig.CpusetMems") 538 assert.Equal(c, out, "0") 539 } 540 541 func (s *DockerCLIRunSuite) TestRunWithBlkioWeight(c *testing.T) { 542 testRequires(c, blkioWeight) 543 544 const file = "/sys/fs/cgroup/blkio/blkio.weight" 545 out := cli.DockerCmd(c, "run", "--blkio-weight", "300", "--name", "test", "busybox", "cat", file).Combined() 546 assert.Equal(c, strings.TrimSpace(out), "300") 547 548 out = inspectField(c, "test", "HostConfig.BlkioWeight") 549 assert.Equal(c, out, "300") 550 } 551 552 func (s *DockerCLIRunSuite) TestRunWithInvalidBlkioWeight(c *testing.T) { 553 testRequires(c, blkioWeight) 554 out, _, err := dockerCmdWithError("run", "--blkio-weight", "5", "busybox", "true") 555 assert.ErrorContains(c, err, "", out) 556 expected := "Range of blkio weight is from 10 to 1000" 557 assert.Assert(c, strings.Contains(out, expected)) 558 } 559 560 func (s *DockerCLIRunSuite) TestRunWithInvalidPathforBlkioWeightDevice(c *testing.T) { 561 testRequires(c, blkioWeight) 562 out, _, err := dockerCmdWithError("run", "--blkio-weight-device", "/dev/sdX:100", "busybox", "true") 563 assert.ErrorContains(c, err, "", out) 564 } 565 566 func (s *DockerCLIRunSuite) TestRunWithInvalidPathforBlkioDeviceReadBps(c *testing.T) { 567 testRequires(c, blkioWeight) 568 out, _, err := dockerCmdWithError("run", "--device-read-bps", "/dev/sdX:500", "busybox", "true") 569 assert.ErrorContains(c, err, "", out) 570 } 571 572 func (s *DockerCLIRunSuite) TestRunWithInvalidPathforBlkioDeviceWriteBps(c *testing.T) { 573 testRequires(c, blkioWeight) 574 out, _, err := dockerCmdWithError("run", "--device-write-bps", "/dev/sdX:500", "busybox", "true") 575 assert.ErrorContains(c, err, "", out) 576 } 577 578 func (s *DockerCLIRunSuite) TestRunWithInvalidPathforBlkioDeviceReadIOps(c *testing.T) { 579 testRequires(c, blkioWeight) 580 out, _, err := dockerCmdWithError("run", "--device-read-iops", "/dev/sdX:500", "busybox", "true") 581 assert.ErrorContains(c, err, "", out) 582 } 583 584 func (s *DockerCLIRunSuite) TestRunWithInvalidPathforBlkioDeviceWriteIOps(c *testing.T) { 585 testRequires(c, blkioWeight) 586 out, _, err := dockerCmdWithError("run", "--device-write-iops", "/dev/sdX:500", "busybox", "true") 587 assert.ErrorContains(c, err, "", out) 588 } 589 590 func (s *DockerCLIRunSuite) TestRunOOMExitCode(c *testing.T) { 591 testRequires(c, memoryLimitSupport, swapMemorySupport, NotPpc64le) 592 errChan := make(chan error, 1) 593 go func() { 594 defer close(errChan) 595 // memory limit lower than 8MB will raise an error of "device or resource busy" from docker-runc. 596 out, exitCode, _ := dockerCmdWithError("run", "-m", "8MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x$x$x; done") 597 if expected := 137; exitCode != expected { 598 errChan <- fmt.Errorf("wrong exit code for OOM container: expected %d, got %d (output: %q)", expected, exitCode, out) 599 } 600 }() 601 602 select { 603 case err := <-errChan: 604 assert.NilError(c, err) 605 case <-time.After(600 * time.Second): 606 c.Fatal("Timeout waiting for container to die on OOM") 607 } 608 } 609 610 func (s *DockerCLIRunSuite) TestRunWithMemoryLimit(c *testing.T) { 611 testRequires(c, memoryLimitSupport) 612 613 const file = "/sys/fs/cgroup/memory/memory.limit_in_bytes" 614 cli.DockerCmd(c, "run", "-m", "32M", "--name", "test", "busybox", "cat", file).Assert(c, icmd.Expected{ 615 Out: "33554432", 616 }) 617 cli.InspectCmd(c, "test", cli.Format(".HostConfig.Memory")).Assert(c, icmd.Expected{ 618 Out: "33554432", 619 }) 620 } 621 622 // TestRunWithoutMemoryswapLimit sets memory limit and disables swap 623 // memory limit, this means the processes in the container can use 624 // 16M memory and as much swap memory as they need (if the host 625 // supports swap memory). 626 func (s *DockerCLIRunSuite) TestRunWithoutMemoryswapLimit(c *testing.T) { 627 testRequires(c, DaemonIsLinux) 628 testRequires(c, memoryLimitSupport) 629 testRequires(c, swapMemorySupport) 630 cli.DockerCmd(c, "run", "-m", "32m", "--memory-swap", "-1", "busybox", "true") 631 } 632 633 func (s *DockerCLIRunSuite) TestRunWithSwappiness(c *testing.T) { 634 testRequires(c, memorySwappinessSupport) 635 const file = "/sys/fs/cgroup/memory/memory.swappiness" 636 out := cli.DockerCmd(c, "run", "--memory-swappiness", "0", "--name", "test", "busybox", "cat", file).Combined() 637 assert.Equal(c, strings.TrimSpace(out), "0") 638 639 out = inspectField(c, "test", "HostConfig.MemorySwappiness") 640 assert.Equal(c, out, "0") 641 } 642 643 func (s *DockerCLIRunSuite) TestRunWithSwappinessInvalid(c *testing.T) { 644 testRequires(c, memorySwappinessSupport) 645 out, _, err := dockerCmdWithError("run", "--memory-swappiness", "101", "busybox", "true") 646 assert.ErrorContains(c, err, "") 647 expected := "Valid memory swappiness range is 0-100" 648 assert.Assert(c, strings.Contains(out, expected), "Expected output to contain %q, not %q", out, expected) 649 out, _, err = dockerCmdWithError("run", "--memory-swappiness", "-10", "busybox", "true") 650 assert.ErrorContains(c, err, "") 651 assert.Assert(c, strings.Contains(out, expected), "Expected output to contain %q, not %q", out, expected) 652 } 653 654 func (s *DockerCLIRunSuite) TestRunWithMemoryReservation(c *testing.T) { 655 testRequires(c, testEnv.IsLocalDaemon, memoryReservationSupport) 656 657 const file = "/sys/fs/cgroup/memory/memory.soft_limit_in_bytes" 658 out := cli.DockerCmd(c, "run", "--memory-reservation", "200M", "--name", "test", "busybox", "cat", file).Combined() 659 assert.Equal(c, strings.TrimSpace(out), "209715200") 660 661 out = inspectField(c, "test", "HostConfig.MemoryReservation") 662 assert.Equal(c, out, "209715200") 663 } 664 665 func (s *DockerCLIRunSuite) TestRunWithMemoryReservationInvalid(c *testing.T) { 666 testRequires(c, memoryLimitSupport) 667 testRequires(c, testEnv.IsLocalDaemon, memoryReservationSupport) 668 out, _, err := dockerCmdWithError("run", "-m", "500M", "--memory-reservation", "800M", "busybox", "true") 669 assert.ErrorContains(c, err, "") 670 expected := "Minimum memory limit can not be less than memory reservation limit" 671 assert.Assert(c, strings.Contains(strings.TrimSpace(out), expected), "run container should fail with invalid memory reservation") 672 out, _, err = dockerCmdWithError("run", "--memory-reservation", "1k", "busybox", "true") 673 assert.ErrorContains(c, err, "") 674 expected = "Minimum memory reservation allowed is 6MB" 675 assert.Assert(c, strings.Contains(strings.TrimSpace(out), expected), "run container should fail with invalid memory reservation") 676 } 677 678 func (s *DockerCLIRunSuite) TestStopContainerSignal(c *testing.T) { 679 containerID := cli.DockerCmd(c, "run", "--stop-signal", "SIGUSR1", "-d", "busybox", "/bin/sh", "-c", `trap 'echo "exit trapped"; exit 0' USR1; while true; do sleep 1; done`).Stdout() 680 containerID = strings.TrimSpace(containerID) 681 cli.WaitRun(c, containerID) 682 683 cli.DockerCmd(c, "stop", containerID) 684 out := cli.DockerCmd(c, "logs", containerID).Combined() 685 686 assert.Assert(c, strings.Contains(out, "exit trapped"), "Expected `exit trapped` in the log") 687 } 688 689 func (s *DockerCLIRunSuite) 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 *DockerCLIRunSuite) TestRunInvalidCpusetCpusFlagValue(c *testing.T) { 700 testRequires(c, cgroupCpuset, testEnv.IsLocalDaemon) 701 702 sysInfo := sysinfo.New() 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 *DockerCLIRunSuite) TestRunInvalidCpusetMemsFlagValue(c *testing.T) { 719 testRequires(c, cgroupCpuset) 720 721 sysInfo := sysinfo.New() 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 *DockerCLIRunSuite) 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 *DockerCLIRunSuite) TestRunWithDefaultShmSize(c *testing.T) { 756 testRequires(c, DaemonIsLinux) 757 758 const name = "shm-default" 759 out := cli.DockerCmd(c, "run", "--name", name, "busybox", "mount").Combined() 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 *DockerCLIRunSuite) TestRunWithShmSize(c *testing.T) { 769 testRequires(c, DaemonIsLinux) 770 771 const name = "shm" 772 out := cli.DockerCmd(c, "run", "--name", name, "--shm-size=1G", "busybox", "mount").Combined() 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 *DockerCLIRunSuite) TestRunTmpfsMountsEnsureOrdered(c *testing.T) { 782 tmpFile, err := os.CreateTemp("", "test") 783 assert.NilError(c, err) 784 defer tmpFile.Close() 785 out := cli.DockerCmd(c, "run", "--tmpfs", "/run", "-v", tmpFile.Name()+":/run/test", "busybox", "ls", "/run").Combined() 786 assert.Assert(c, strings.Contains(out, "test")) 787 } 788 789 func (s *DockerCLIRunSuite) 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 *DockerCLIRunSuite) TestRunTmpfsMountsOverrideImageVolumes(c *testing.T) { 811 const name = "img-with-volumes" 812 buildImageSuccessfully(c, name, build.WithDockerfile(` 813 FROM busybox 814 VOLUME /run 815 RUN touch /run/stuff 816 `)) 817 out := cli.DockerCmd(c, "run", "--tmpfs", "/run", name, "ls", "/run").Combined() 818 assert.Assert(c, !strings.Contains(out, "stuff")) 819 } 820 821 // Test case for #22420 822 func (s *DockerCLIRunSuite) TestRunTmpfsMountsWithOptions(c *testing.T) { 823 testRequires(c, DaemonIsLinux) 824 825 expectedOptions := []string{"rw", "nosuid", "nodev", "noexec", "relatime"} 826 out := cli.DockerCmd(c, "run", "--tmpfs", "/tmp", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'").Combined() 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 = cli.DockerCmd(c, "run", "--tmpfs", "/tmp:rw", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'").Combined() 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 = cli.DockerCmd(c, "run", "--tmpfs", "/tmp:rw,exec,size=8192k", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'").Combined() 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 = cli.DockerCmd(c, "run", "--tmpfs", "/tmp:rw,size=8192k,exec,size=4096k,noexec", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'").Combined() 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 = cli.DockerCmd(c, "run", "--tmpfs", "/tmp:shared", "debian:bullseye-slim", "findmnt", "-o", "TARGET,PROPAGATION", "/tmp").Combined() 855 for _, option := range expectedOptions { 856 assert.Assert(c, strings.Contains(out, option)) 857 } 858 } 859 860 func (s *DockerCLIRunSuite) TestRunSysctls(c *testing.T) { 861 testRequires(c, DaemonIsLinux) 862 var err error 863 864 out := cli.DockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=1", "--name", "test", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward").Combined() 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 = cli.DockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=0", "--name", "test1", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward").Combined() 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 *DockerCLIRunSuite) TestRunSeccompProfileDenyUnshare(c *testing.T) { 892 testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, Apparmor) 893 const 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 *DockerCLIRunSuite) TestRunSeccompProfileDenyChmod(c *testing.T) { 921 testRequires(c, testEnv.IsLocalDaemon, seccompEnabled) 922 const 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 *DockerCLIRunSuite) TestRunSeccompProfileDenyUnshareUserns(c *testing.T) { 956 testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, 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 *DockerCLIRunSuite) TestRunSeccompProfileDenyCloneUserns(c *testing.T) { 994 testRequires(c, testEnv.IsLocalDaemon, seccompEnabled) 995 ensureSyscallTest(testutil.GetContext(c), 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 *DockerCLIRunSuite) TestRunSeccompUnconfinedCloneUserns(c *testing.T) { 1006 testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace, unprivilegedUsernsClone) 1007 ensureSyscallTest(testutil.GetContext(c), 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 *DockerCLIRunSuite) TestRunSeccompAllowPrivCloneUserns(c *testing.T) { 1019 testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace) 1020 ensureSyscallTest(testutil.GetContext(c), 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 *DockerCLIRunSuite) TestRunSeccompProfileAllow32Bit(c *testing.T) { 1031 testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, IsAmd64) 1032 ensureSyscallTest(testutil.GetContext(c), 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 *DockerCLIRunSuite) 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 *DockerCLIRunSuite) TestRunSeccompDefaultProfileAcct(c *testing.T) { 1046 testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, NotUserNamespace) 1047 ensureSyscallTest(testutil.GetContext(c), 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 *DockerCLIRunSuite) TestRunSeccompDefaultProfileNS(c *testing.T) { 1076 testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, NotUserNamespace) 1077 ensureSyscallTest(testutil.GetContext(c), 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 *DockerCLIRunSuite) TestRunNoNewPrivSetuid(c *testing.T) { 1113 testRequires(c, DaemonIsLinux, NotUserNamespace, testEnv.IsLocalDaemon) 1114 ensureNNPTest(testutil.GetContext(c), 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 *DockerCLIRunSuite) TestLegacyRunNoNewPrivSetuid(c *testing.T) { 1126 testRequires(c, DaemonIsLinux, NotUserNamespace, testEnv.IsLocalDaemon) 1127 ensureNNPTest(testutil.GetContext(c), 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 *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesChown(c *testing.T) { 1137 testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) 1138 ensureSyscallTest(testutil.GetContext(c), c) 1139 1140 // test that a root user has default capability CAP_CHOWN 1141 cli.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 *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesDacOverride(c *testing.T) { 1155 testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) 1156 ensureSyscallTest(testutil.GetContext(c), c) 1157 1158 // test that a root user has default capability CAP_DAC_OVERRIDE 1159 cli.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 *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesFowner(c *testing.T) { 1168 testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) 1169 ensureSyscallTest(testutil.GetContext(c), c) 1170 1171 // test that a root user has default capability CAP_FOWNER 1172 cli.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 *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesSetuid(c *testing.T) { 1184 testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) 1185 ensureSyscallTest(testutil.GetContext(c), c) 1186 1187 // test that a root user has default capability CAP_SETUID 1188 cli.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 *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesSetgid(c *testing.T) { 1202 testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) 1203 ensureSyscallTest(testutil.GetContext(c), c) 1204 1205 // test that a root user has default capability CAP_SETGID 1206 cli.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.ReplaceAll(s, ".", "/")) 1225 _, err := os.Stat(f) 1226 return err == nil 1227 } 1228 1229 func (s *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesNetBindService(c *testing.T) { 1230 testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) 1231 ensureSyscallTest(testutil.GetContext(c), c) 1232 1233 // test that a root user has default capability CAP_NET_BIND_SERVICE 1234 cli.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 *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesNetRaw(c *testing.T) { 1259 testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) 1260 ensureSyscallTest(testutil.GetContext(c), c) 1261 1262 // test that a root user has default capability CAP_NET_RAW 1263 cli.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 *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesChroot(c *testing.T) { 1277 testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) 1278 ensureSyscallTest(testutil.GetContext(c), c) 1279 1280 // test that a root user has default capability CAP_SYS_CHROOT 1281 cli.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 *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesMknod(c *testing.T) { 1295 testRequires(c, DaemonIsLinux, NotUserNamespace, testEnv.IsLocalDaemon) 1296 ensureSyscallTest(testutil.GetContext(c), c) 1297 1298 // test that a root user has default capability CAP_MKNOD 1299 cli.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 *DockerCLIRunSuite) 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 *DockerCLIRunSuite) 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 *DockerCLIRunSuite) TestRunDeviceSymlink(c *testing.T) { 1345 testRequires(c, DaemonIsLinux, NotUserNamespace, 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"), 0o666) 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 := cli.DockerCmd(c, "run", "--device", symZero+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum").Combined() 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 = cli.DockerCmd(c, "run", "--device", "/dev/symzero:/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum").Combined() 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 *DockerCLIRunSuite) TestRunPIDsLimit(c *testing.T) { 1392 testRequires(c, testEnv.IsLocalDaemon, pidsLimit) 1393 1394 const file = "/sys/fs/cgroup/pids/pids.max" 1395 out := cli.DockerCmd(c, "run", "--name", "skittles", "--pids-limit", "4", "busybox", "cat", file).Combined() 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 *DockerCLIRunSuite) TestRunPrivilegedAllowedDevices(c *testing.T) { 1403 testRequires(c, DaemonIsLinux, NotUserNamespace) 1404 1405 const file = "/sys/fs/cgroup/devices/devices.list" 1406 out := cli.DockerCmd(c, "run", "--privileged", "busybox", "cat", file).Combined() 1407 c.Logf("out: %q", out) 1408 assert.Equal(c, strings.TrimSpace(out), "a *:* rwm") 1409 } 1410 1411 func (s *DockerCLIRunSuite) 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 const file = "/sys/fs/cgroup/devices/devices.list" 1424 out := cli.DockerCmd(c, "run", "--device", "/dev/snd/timer:w", "busybox", "cat", file).Combined() 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 ctx := testutil.GetContext(c) 1431 1432 s.d.StartWithBusybox(ctx, c) 1433 1434 const jsonData = `{ 1435 "defaultAction": "SCMP_ACT_ALLOW", 1436 "syscalls": [ 1437 { 1438 "names": ["chmod", "fchmod", "fchmodat"], 1439 "action": "SCMP_ACT_ERRNO" 1440 } 1441 ] 1442 }` 1443 tmpFile, err := os.CreateTemp("", "profile.json") 1444 assert.NilError(c, err) 1445 defer tmpFile.Close() 1446 _, err = tmpFile.Write([]byte(jsonData)) 1447 assert.NilError(c, err) 1448 1449 out, err := s.d.Cmd("run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "777", ".") 1450 assert.ErrorContains(c, err, "") 1451 assert.Assert(c, strings.Contains(out, "Operation not permitted")) 1452 } 1453 1454 func (s *DockerDaemonSuite) TestRunSeccompJSONNoNameAndNames(c *testing.T) { 1455 testRequires(c, seccompEnabled) 1456 ctx := testutil.GetContext(c) 1457 1458 s.d.StartWithBusybox(ctx, c) 1459 1460 const jsonData = `{ 1461 "defaultAction": "SCMP_ACT_ALLOW", 1462 "syscalls": [ 1463 { 1464 "name": "chmod", 1465 "names": ["fchmod", "fchmodat"], 1466 "action": "SCMP_ACT_ERRNO" 1467 } 1468 ] 1469 }` 1470 tmpFile, err := os.CreateTemp("", "profile.json") 1471 assert.NilError(c, err) 1472 defer tmpFile.Close() 1473 _, err = tmpFile.Write([]byte(jsonData)) 1474 assert.NilError(c, err) 1475 1476 out, err := s.d.Cmd("run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "777", ".") 1477 assert.ErrorContains(c, err, "") 1478 assert.Assert(c, strings.Contains(out, "use either 'name' or 'names'")) 1479 } 1480 1481 func (s *DockerDaemonSuite) TestRunSeccompJSONNoArchAndArchMap(c *testing.T) { 1482 testRequires(c, seccompEnabled) 1483 ctx := testutil.GetContext(c) 1484 1485 s.d.StartWithBusybox(ctx, c) 1486 1487 const jsonData = `{ 1488 "archMap": [ 1489 { 1490 "architecture": "SCMP_ARCH_X86_64", 1491 "subArchitectures": [ 1492 "SCMP_ARCH_X86", 1493 "SCMP_ARCH_X32" 1494 ] 1495 } 1496 ], 1497 "architectures": [ 1498 "SCMP_ARCH_X32" 1499 ], 1500 "defaultAction": "SCMP_ACT_ALLOW", 1501 "syscalls": [ 1502 { 1503 "names": ["chmod", "fchmod", "fchmodat"], 1504 "action": "SCMP_ACT_ERRNO" 1505 } 1506 ] 1507 }` 1508 tmpFile, err := os.CreateTemp("", "profile.json") 1509 assert.NilError(c, err) 1510 defer tmpFile.Close() 1511 _, err = tmpFile.Write([]byte(jsonData)) 1512 assert.NilError(c, err) 1513 1514 out, err := s.d.Cmd("run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "777", ".") 1515 assert.ErrorContains(c, err, "") 1516 assert.Assert(c, strings.Contains(out, "use either 'architectures' or 'archMap'")) 1517 } 1518 1519 func (s *DockerDaemonSuite) TestRunWithDaemonDefaultSeccompProfile(c *testing.T) { 1520 testRequires(c, seccompEnabled) 1521 ctx := testutil.GetContext(c) 1522 1523 s.d.StartWithBusybox(ctx, c) 1524 1525 // 1) verify I can run containers with the Docker default shipped profile which allows chmod 1526 _, err := s.d.Cmd("run", "busybox", "chmod", "777", ".") 1527 assert.NilError(c, err) 1528 1529 const jsonData = `{ 1530 "defaultAction": "SCMP_ACT_ALLOW", 1531 "syscalls": [ 1532 { 1533 "name": "chmod", 1534 "action": "SCMP_ACT_ERRNO" 1535 }, 1536 { 1537 "name": "fchmodat", 1538 "action": "SCMP_ACT_ERRNO" 1539 } 1540 ] 1541 }` 1542 tmpFile, err := os.CreateTemp("", "profile.json") 1543 assert.NilError(c, err) 1544 defer tmpFile.Close() 1545 _, err = tmpFile.Write([]byte(jsonData)) 1546 assert.NilError(c, err) 1547 1548 // 2) restart the daemon and add a custom seccomp profile in which we deny chmod 1549 s.d.Restart(c, "--seccomp-profile="+tmpFile.Name()) 1550 1551 out, err := s.d.Cmd("run", "busybox", "chmod", "777", ".") 1552 assert.ErrorContains(c, err, "") 1553 assert.Assert(c, strings.Contains(out, "Operation not permitted")) 1554 } 1555 1556 func (s *DockerCLIRunSuite) TestRunWithNanoCPUs(c *testing.T) { 1557 testRequires(c, cpuCfsQuota, cpuCfsPeriod) 1558 1559 const file1 = "/sys/fs/cgroup/cpu/cpu.cfs_quota_us" 1560 const file2 = "/sys/fs/cgroup/cpu/cpu.cfs_period_us" 1561 out := cli.DockerCmd(c, "run", "--cpus", "0.5", "--name", "test", "busybox", "sh", "-c", fmt.Sprintf("cat %s && cat %s", file1, file2)).Combined() 1562 assert.Equal(c, strings.TrimSpace(out), "50000\n100000") 1563 1564 clt, err := client.NewClientWithOpts(client.FromEnv) 1565 assert.NilError(c, err) 1566 inspect, err := clt.ContainerInspect(testutil.GetContext(c), "test") 1567 assert.NilError(c, err) 1568 assert.Equal(c, inspect.HostConfig.NanoCPUs, int64(500000000)) 1569 1570 out = inspectField(c, "test", "HostConfig.CpuQuota") 1571 assert.Equal(c, out, "0", "CPU CFS quota should be 0") 1572 out = inspectField(c, "test", "HostConfig.CpuPeriod") 1573 assert.Equal(c, out, "0", "CPU CFS period should be 0") 1574 1575 out, _, err = dockerCmdWithError("run", "--cpus", "0.5", "--cpu-quota", "50000", "--cpu-period", "100000", "busybox", "sh") 1576 assert.ErrorContains(c, err, "") 1577 assert.Assert(c, strings.Contains(out, "Conflicting options: Nano CPUs and CPU Period cannot both be set")) 1578 }