docker_cli_run_unix_test.go 56 KB

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