docker_cli_run_unix_test.go 55 KB

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