rootfs_linux.go 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  1. // +build linux
  2. package libcontainer
  3. import (
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "os"
  8. "os/exec"
  9. "path"
  10. "path/filepath"
  11. "strings"
  12. "time"
  13. securejoin "github.com/cyphar/filepath-securejoin"
  14. "github.com/mrunalp/fileutils"
  15. "github.com/opencontainers/runc/libcontainer/cgroups"
  16. "github.com/opencontainers/runc/libcontainer/configs"
  17. "github.com/opencontainers/runc/libcontainer/mount"
  18. "github.com/opencontainers/runc/libcontainer/system"
  19. libcontainerUtils "github.com/opencontainers/runc/libcontainer/utils"
  20. "github.com/opencontainers/selinux/go-selinux/label"
  21. "golang.org/x/sys/unix"
  22. )
  23. const defaultMountFlags = unix.MS_NOEXEC | unix.MS_NOSUID | unix.MS_NODEV
  24. // needsSetupDev returns true if /dev needs to be set up.
  25. func needsSetupDev(config *configs.Config) bool {
  26. for _, m := range config.Mounts {
  27. if m.Device == "bind" && libcontainerUtils.CleanPath(m.Destination) == "/dev" {
  28. return false
  29. }
  30. }
  31. return true
  32. }
  33. // prepareRootfs sets up the devices, mount points, and filesystems for use
  34. // inside a new mount namespace. It doesn't set anything as ro. You must call
  35. // finalizeRootfs after this function to finish setting up the rootfs.
  36. func prepareRootfs(pipe io.ReadWriter, iConfig *initConfig) (err error) {
  37. config := iConfig.Config
  38. if err := prepareRoot(config); err != nil {
  39. return newSystemErrorWithCause(err, "preparing rootfs")
  40. }
  41. hasCgroupns := config.Namespaces.Contains(configs.NEWCGROUP)
  42. setupDev := needsSetupDev(config)
  43. for _, m := range config.Mounts {
  44. for _, precmd := range m.PremountCmds {
  45. if err := mountCmd(precmd); err != nil {
  46. return newSystemErrorWithCause(err, "running premount command")
  47. }
  48. }
  49. if err := mountToRootfs(m, config.Rootfs, config.MountLabel, hasCgroupns); err != nil {
  50. return newSystemErrorWithCausef(err, "mounting %q to rootfs %q at %q", m.Source, config.Rootfs, m.Destination)
  51. }
  52. for _, postcmd := range m.PostmountCmds {
  53. if err := mountCmd(postcmd); err != nil {
  54. return newSystemErrorWithCause(err, "running postmount command")
  55. }
  56. }
  57. }
  58. if setupDev {
  59. if err := createDevices(config); err != nil {
  60. return newSystemErrorWithCause(err, "creating device nodes")
  61. }
  62. if err := setupPtmx(config); err != nil {
  63. return newSystemErrorWithCause(err, "setting up ptmx")
  64. }
  65. if err := setupDevSymlinks(config.Rootfs); err != nil {
  66. return newSystemErrorWithCause(err, "setting up /dev symlinks")
  67. }
  68. }
  69. // Signal the parent to run the pre-start hooks.
  70. // The hooks are run after the mounts are setup, but before we switch to the new
  71. // root, so that the old root is still available in the hooks for any mount
  72. // manipulations.
  73. // Note that iConfig.Cwd is not guaranteed to exist here.
  74. if err := syncParentHooks(pipe); err != nil {
  75. return err
  76. }
  77. // The reason these operations are done here rather than in finalizeRootfs
  78. // is because the console-handling code gets quite sticky if we have to set
  79. // up the console before doing the pivot_root(2). This is because the
  80. // Console API has to also work with the ExecIn case, which means that the
  81. // API must be able to deal with being inside as well as outside the
  82. // container. It's just cleaner to do this here (at the expense of the
  83. // operation not being perfectly split).
  84. if err := unix.Chdir(config.Rootfs); err != nil {
  85. return newSystemErrorWithCausef(err, "changing dir to %q", config.Rootfs)
  86. }
  87. if config.NoPivotRoot {
  88. err = msMoveRoot(config.Rootfs)
  89. } else if config.Namespaces.Contains(configs.NEWNS) {
  90. err = pivotRoot(config.Rootfs)
  91. } else {
  92. err = chroot(config.Rootfs)
  93. }
  94. if err != nil {
  95. return newSystemErrorWithCause(err, "jailing process inside rootfs")
  96. }
  97. if setupDev {
  98. if err := reOpenDevNull(); err != nil {
  99. return newSystemErrorWithCause(err, "reopening /dev/null inside container")
  100. }
  101. }
  102. if cwd := iConfig.Cwd; cwd != "" {
  103. // Note that spec.Process.Cwd can contain unclean value like "../../../../foo/bar...".
  104. // However, we are safe to call MkDirAll directly because we are in the jail here.
  105. if err := os.MkdirAll(cwd, 0755); err != nil {
  106. return err
  107. }
  108. }
  109. return nil
  110. }
  111. // finalizeRootfs sets anything to ro if necessary. You must call
  112. // prepareRootfs first.
  113. func finalizeRootfs(config *configs.Config) (err error) {
  114. // remount dev as ro if specified
  115. for _, m := range config.Mounts {
  116. if libcontainerUtils.CleanPath(m.Destination) == "/dev" {
  117. if m.Flags&unix.MS_RDONLY == unix.MS_RDONLY {
  118. if err := remountReadonly(m); err != nil {
  119. return newSystemErrorWithCausef(err, "remounting %q as readonly", m.Destination)
  120. }
  121. }
  122. break
  123. }
  124. }
  125. // set rootfs ( / ) as readonly
  126. if config.Readonlyfs {
  127. if err := setReadonly(); err != nil {
  128. return newSystemErrorWithCause(err, "setting rootfs as readonly")
  129. }
  130. }
  131. unix.Umask(0022)
  132. return nil
  133. }
  134. // /tmp has to be mounted as private to allow MS_MOVE to work in all situations
  135. func prepareTmp(topTmpDir string) (string, error) {
  136. tmpdir, err := ioutil.TempDir(topTmpDir, "runctop")
  137. if err != nil {
  138. return "", err
  139. }
  140. if err := unix.Mount(tmpdir, tmpdir, "bind", unix.MS_BIND, ""); err != nil {
  141. return "", err
  142. }
  143. if err := unix.Mount("", tmpdir, "", uintptr(unix.MS_PRIVATE), ""); err != nil {
  144. return "", err
  145. }
  146. return tmpdir, nil
  147. }
  148. func cleanupTmp(tmpdir string) error {
  149. unix.Unmount(tmpdir, 0)
  150. return os.RemoveAll(tmpdir)
  151. }
  152. func mountCmd(cmd configs.Command) error {
  153. command := exec.Command(cmd.Path, cmd.Args[:]...)
  154. command.Env = cmd.Env
  155. command.Dir = cmd.Dir
  156. if out, err := command.CombinedOutput(); err != nil {
  157. return fmt.Errorf("%#v failed: %s: %v", cmd, string(out), err)
  158. }
  159. return nil
  160. }
  161. func prepareBindMount(m *configs.Mount, rootfs string) error {
  162. stat, err := os.Stat(m.Source)
  163. if err != nil {
  164. // error out if the source of a bind mount does not exist as we will be
  165. // unable to bind anything to it.
  166. return err
  167. }
  168. // ensure that the destination of the bind mount is resolved of symlinks at mount time because
  169. // any previous mounts can invalidate the next mount's destination.
  170. // this can happen when a user specifies mounts within other mounts to cause breakouts or other
  171. // evil stuff to try to escape the container's rootfs.
  172. var dest string
  173. if dest, err = securejoin.SecureJoin(rootfs, m.Destination); err != nil {
  174. return err
  175. }
  176. if err := checkProcMount(rootfs, dest, m.Source); err != nil {
  177. return err
  178. }
  179. // update the mount with the correct dest after symlinks are resolved.
  180. m.Destination = dest
  181. if err := createIfNotExists(dest, stat.IsDir()); err != nil {
  182. return err
  183. }
  184. return nil
  185. }
  186. func mountCgroupV1(m *configs.Mount, rootfs, mountLabel string, enableCgroupns bool) error {
  187. binds, err := getCgroupMounts(m)
  188. if err != nil {
  189. return err
  190. }
  191. var merged []string
  192. for _, b := range binds {
  193. ss := filepath.Base(b.Destination)
  194. if strings.Contains(ss, ",") {
  195. merged = append(merged, ss)
  196. }
  197. }
  198. tmpfs := &configs.Mount{
  199. Source: "tmpfs",
  200. Device: "tmpfs",
  201. Destination: m.Destination,
  202. Flags: defaultMountFlags,
  203. Data: "mode=755",
  204. PropagationFlags: m.PropagationFlags,
  205. }
  206. if err := mountToRootfs(tmpfs, rootfs, mountLabel, enableCgroupns); err != nil {
  207. return err
  208. }
  209. for _, b := range binds {
  210. if enableCgroupns {
  211. subsystemPath := filepath.Join(rootfs, b.Destination)
  212. if err := os.MkdirAll(subsystemPath, 0755); err != nil {
  213. return err
  214. }
  215. flags := defaultMountFlags
  216. if m.Flags&unix.MS_RDONLY != 0 {
  217. flags = flags | unix.MS_RDONLY
  218. }
  219. cgroupmount := &configs.Mount{
  220. Source: "cgroup",
  221. Device: "cgroup",
  222. Destination: subsystemPath,
  223. Flags: flags,
  224. Data: filepath.Base(subsystemPath),
  225. }
  226. if err := mountNewCgroup(cgroupmount); err != nil {
  227. return err
  228. }
  229. } else {
  230. if err := mountToRootfs(b, rootfs, mountLabel, enableCgroupns); err != nil {
  231. return err
  232. }
  233. }
  234. }
  235. for _, mc := range merged {
  236. for _, ss := range strings.Split(mc, ",") {
  237. // symlink(2) is very dumb, it will just shove the path into
  238. // the link and doesn't do any checks or relative path
  239. // conversion. Also, don't error out if the cgroup already exists.
  240. if err := os.Symlink(mc, filepath.Join(rootfs, m.Destination, ss)); err != nil && !os.IsExist(err) {
  241. return err
  242. }
  243. }
  244. }
  245. return nil
  246. }
  247. func mountCgroupV2(m *configs.Mount, rootfs, mountLabel string, enableCgroupns bool) error {
  248. cgroupPath, err := securejoin.SecureJoin(rootfs, m.Destination)
  249. if err != nil {
  250. return err
  251. }
  252. if err := os.MkdirAll(cgroupPath, 0755); err != nil {
  253. return err
  254. }
  255. if err := unix.Mount(m.Source, cgroupPath, "cgroup2", uintptr(m.Flags), m.Data); err != nil {
  256. // when we are in UserNS but CgroupNS is not unshared, we cannot mount cgroup2 (#2158)
  257. if err == unix.EPERM || err == unix.EBUSY {
  258. return unix.Mount("/sys/fs/cgroup", cgroupPath, "", uintptr(m.Flags)|unix.MS_BIND, "")
  259. }
  260. return err
  261. }
  262. return nil
  263. }
  264. func mountToRootfs(m *configs.Mount, rootfs, mountLabel string, enableCgroupns bool) error {
  265. var (
  266. dest = m.Destination
  267. )
  268. if !strings.HasPrefix(dest, rootfs) {
  269. dest = filepath.Join(rootfs, dest)
  270. }
  271. switch m.Device {
  272. case "proc", "sysfs":
  273. // If the destination already exists and is not a directory, we bail
  274. // out This is to avoid mounting through a symlink or similar -- which
  275. // has been a "fun" attack scenario in the past.
  276. // TODO: This won't be necessary once we switch to libpathrs and we can
  277. // stop all of these symlink-exchange attacks.
  278. if fi, err := os.Lstat(dest); err != nil {
  279. if !os.IsNotExist(err) {
  280. return err
  281. }
  282. } else if fi.Mode()&os.ModeDir == 0 {
  283. return fmt.Errorf("filesystem %q must be mounted on ordinary directory", m.Device)
  284. }
  285. if err := os.MkdirAll(dest, 0755); err != nil {
  286. return err
  287. }
  288. // Selinux kernels do not support labeling of /proc or /sys
  289. return mountPropagate(m, rootfs, "")
  290. case "mqueue":
  291. if err := os.MkdirAll(dest, 0755); err != nil {
  292. return err
  293. }
  294. if err := mountPropagate(m, rootfs, mountLabel); err != nil {
  295. // older kernels do not support labeling of /dev/mqueue
  296. if err := mountPropagate(m, rootfs, ""); err != nil {
  297. return err
  298. }
  299. return label.SetFileLabel(dest, mountLabel)
  300. }
  301. return nil
  302. case "tmpfs":
  303. copyUp := m.Extensions&configs.EXT_COPYUP == configs.EXT_COPYUP
  304. tmpDir := ""
  305. stat, err := os.Stat(dest)
  306. if err != nil {
  307. if err := os.MkdirAll(dest, 0755); err != nil {
  308. return err
  309. }
  310. }
  311. if copyUp {
  312. tmpdir, err := prepareTmp("/tmp")
  313. if err != nil {
  314. return newSystemErrorWithCause(err, "tmpcopyup: failed to setup tmpdir")
  315. }
  316. defer cleanupTmp(tmpdir)
  317. tmpDir, err = ioutil.TempDir(tmpdir, "runctmpdir")
  318. if err != nil {
  319. return newSystemErrorWithCause(err, "tmpcopyup: failed to create tmpdir")
  320. }
  321. defer os.RemoveAll(tmpDir)
  322. m.Destination = tmpDir
  323. }
  324. if err := mountPropagate(m, rootfs, mountLabel); err != nil {
  325. return err
  326. }
  327. if copyUp {
  328. if err := fileutils.CopyDirectory(dest, tmpDir); err != nil {
  329. errMsg := fmt.Errorf("tmpcopyup: failed to copy %s to %s: %v", dest, tmpDir, err)
  330. if err1 := unix.Unmount(tmpDir, unix.MNT_DETACH); err1 != nil {
  331. return newSystemErrorWithCausef(err1, "tmpcopyup: %v: failed to unmount", errMsg)
  332. }
  333. return errMsg
  334. }
  335. if err := unix.Mount(tmpDir, dest, "", unix.MS_MOVE, ""); err != nil {
  336. errMsg := fmt.Errorf("tmpcopyup: failed to move mount %s to %s: %v", tmpDir, dest, err)
  337. if err1 := unix.Unmount(tmpDir, unix.MNT_DETACH); err1 != nil {
  338. return newSystemErrorWithCausef(err1, "tmpcopyup: %v: failed to unmount", errMsg)
  339. }
  340. return errMsg
  341. }
  342. }
  343. if stat != nil {
  344. if err = os.Chmod(dest, stat.Mode()); err != nil {
  345. return err
  346. }
  347. }
  348. return nil
  349. case "bind":
  350. if err := prepareBindMount(m, rootfs); err != nil {
  351. return err
  352. }
  353. if err := mountPropagate(m, rootfs, mountLabel); err != nil {
  354. return err
  355. }
  356. // bind mount won't change mount options, we need remount to make mount options effective.
  357. // first check that we have non-default options required before attempting a remount
  358. if m.Flags&^(unix.MS_REC|unix.MS_REMOUNT|unix.MS_BIND) != 0 {
  359. // only remount if unique mount options are set
  360. if err := remount(m, rootfs); err != nil {
  361. return err
  362. }
  363. }
  364. if m.Relabel != "" {
  365. if err := label.Validate(m.Relabel); err != nil {
  366. return err
  367. }
  368. shared := label.IsShared(m.Relabel)
  369. if err := label.Relabel(m.Source, mountLabel, shared); err != nil {
  370. return err
  371. }
  372. }
  373. case "cgroup":
  374. if cgroups.IsCgroup2UnifiedMode() {
  375. if err := mountCgroupV2(m, rootfs, mountLabel, enableCgroupns); err != nil {
  376. return err
  377. }
  378. } else {
  379. if err := mountCgroupV1(m, rootfs, mountLabel, enableCgroupns); err != nil {
  380. return err
  381. }
  382. }
  383. if m.Flags&unix.MS_RDONLY != 0 {
  384. // remount cgroup root as readonly
  385. mcgrouproot := &configs.Mount{
  386. Source: m.Destination,
  387. Device: "bind",
  388. Destination: m.Destination,
  389. Flags: defaultMountFlags | unix.MS_RDONLY | unix.MS_BIND,
  390. }
  391. if err := remount(mcgrouproot, rootfs); err != nil {
  392. return err
  393. }
  394. }
  395. default:
  396. // ensure that the destination of the mount is resolved of symlinks at mount time because
  397. // any previous mounts can invalidate the next mount's destination.
  398. // this can happen when a user specifies mounts within other mounts to cause breakouts or other
  399. // evil stuff to try to escape the container's rootfs.
  400. var err error
  401. if dest, err = securejoin.SecureJoin(rootfs, m.Destination); err != nil {
  402. return err
  403. }
  404. if err := checkProcMount(rootfs, dest, m.Source); err != nil {
  405. return err
  406. }
  407. // update the mount with the correct dest after symlinks are resolved.
  408. m.Destination = dest
  409. if err := os.MkdirAll(dest, 0755); err != nil {
  410. return err
  411. }
  412. return mountPropagate(m, rootfs, mountLabel)
  413. }
  414. return nil
  415. }
  416. func getCgroupMounts(m *configs.Mount) ([]*configs.Mount, error) {
  417. mounts, err := cgroups.GetCgroupMounts(false)
  418. if err != nil {
  419. return nil, err
  420. }
  421. cgroupPaths, err := cgroups.ParseCgroupFile("/proc/self/cgroup")
  422. if err != nil {
  423. return nil, err
  424. }
  425. var binds []*configs.Mount
  426. for _, mm := range mounts {
  427. dir, err := mm.GetOwnCgroup(cgroupPaths)
  428. if err != nil {
  429. return nil, err
  430. }
  431. relDir, err := filepath.Rel(mm.Root, dir)
  432. if err != nil {
  433. return nil, err
  434. }
  435. binds = append(binds, &configs.Mount{
  436. Device: "bind",
  437. Source: filepath.Join(mm.Mountpoint, relDir),
  438. Destination: filepath.Join(m.Destination, filepath.Base(mm.Mountpoint)),
  439. Flags: unix.MS_BIND | unix.MS_REC | m.Flags,
  440. PropagationFlags: m.PropagationFlags,
  441. })
  442. }
  443. return binds, nil
  444. }
  445. // checkProcMount checks to ensure that the mount destination is not over the top of /proc.
  446. // dest is required to be an abs path and have any symlinks resolved before calling this function.
  447. //
  448. // if source is nil, don't stat the filesystem. This is used for restore of a checkpoint.
  449. func checkProcMount(rootfs, dest, source string) error {
  450. const procPath = "/proc"
  451. // White list, it should be sub directories of invalid destinations
  452. validDestinations := []string{
  453. // These entries can be bind mounted by files emulated by fuse,
  454. // so commands like top, free displays stats in container.
  455. "/proc/cpuinfo",
  456. "/proc/diskstats",
  457. "/proc/meminfo",
  458. "/proc/stat",
  459. "/proc/swaps",
  460. "/proc/uptime",
  461. "/proc/loadavg",
  462. "/proc/net/dev",
  463. }
  464. for _, valid := range validDestinations {
  465. path, err := filepath.Rel(filepath.Join(rootfs, valid), dest)
  466. if err != nil {
  467. return err
  468. }
  469. if path == "." {
  470. return nil
  471. }
  472. }
  473. path, err := filepath.Rel(filepath.Join(rootfs, procPath), dest)
  474. if err != nil {
  475. return err
  476. }
  477. // pass if the mount path is located outside of /proc
  478. if strings.HasPrefix(path, "..") {
  479. return nil
  480. }
  481. if path == "." {
  482. // an empty source is pasted on restore
  483. if source == "" {
  484. return nil
  485. }
  486. // only allow a mount on-top of proc if it's source is "proc"
  487. isproc, err := isProc(source)
  488. if err != nil {
  489. return err
  490. }
  491. // pass if the mount is happening on top of /proc and the source of
  492. // the mount is a proc filesystem
  493. if isproc {
  494. return nil
  495. }
  496. return fmt.Errorf("%q cannot be mounted because it is not of type proc", dest)
  497. }
  498. return fmt.Errorf("%q cannot be mounted because it is inside /proc", dest)
  499. }
  500. func isProc(path string) (bool, error) {
  501. var s unix.Statfs_t
  502. if err := unix.Statfs(path, &s); err != nil {
  503. return false, err
  504. }
  505. return s.Type == unix.PROC_SUPER_MAGIC, nil
  506. }
  507. func setupDevSymlinks(rootfs string) error {
  508. var links = [][2]string{
  509. {"/proc/self/fd", "/dev/fd"},
  510. {"/proc/self/fd/0", "/dev/stdin"},
  511. {"/proc/self/fd/1", "/dev/stdout"},
  512. {"/proc/self/fd/2", "/dev/stderr"},
  513. }
  514. // kcore support can be toggled with CONFIG_PROC_KCORE; only create a symlink
  515. // in /dev if it exists in /proc.
  516. if _, err := os.Stat("/proc/kcore"); err == nil {
  517. links = append(links, [2]string{"/proc/kcore", "/dev/core"})
  518. }
  519. for _, link := range links {
  520. var (
  521. src = link[0]
  522. dst = filepath.Join(rootfs, link[1])
  523. )
  524. if err := os.Symlink(src, dst); err != nil && !os.IsExist(err) {
  525. return fmt.Errorf("symlink %s %s %s", src, dst, err)
  526. }
  527. }
  528. return nil
  529. }
  530. // If stdin, stdout, and/or stderr are pointing to `/dev/null` in the parent's rootfs
  531. // this method will make them point to `/dev/null` in this container's rootfs. This
  532. // needs to be called after we chroot/pivot into the container's rootfs so that any
  533. // symlinks are resolved locally.
  534. func reOpenDevNull() error {
  535. var stat, devNullStat unix.Stat_t
  536. file, err := os.OpenFile("/dev/null", os.O_RDWR, 0)
  537. if err != nil {
  538. return fmt.Errorf("Failed to open /dev/null - %s", err)
  539. }
  540. defer file.Close()
  541. if err := unix.Fstat(int(file.Fd()), &devNullStat); err != nil {
  542. return err
  543. }
  544. for fd := 0; fd < 3; fd++ {
  545. if err := unix.Fstat(fd, &stat); err != nil {
  546. return err
  547. }
  548. if stat.Rdev == devNullStat.Rdev {
  549. // Close and re-open the fd.
  550. if err := unix.Dup3(int(file.Fd()), fd, 0); err != nil {
  551. return err
  552. }
  553. }
  554. }
  555. return nil
  556. }
  557. // Create the device nodes in the container.
  558. func createDevices(config *configs.Config) error {
  559. useBindMount := system.RunningInUserNS() || config.Namespaces.Contains(configs.NEWUSER)
  560. oldMask := unix.Umask(0000)
  561. for _, node := range config.Devices {
  562. // containers running in a user namespace are not allowed to mknod
  563. // devices so we can just bind mount it from the host.
  564. if err := createDeviceNode(config.Rootfs, node, useBindMount); err != nil {
  565. unix.Umask(oldMask)
  566. return err
  567. }
  568. }
  569. unix.Umask(oldMask)
  570. return nil
  571. }
  572. func bindMountDeviceNode(dest string, node *configs.Device) error {
  573. f, err := os.Create(dest)
  574. if err != nil && !os.IsExist(err) {
  575. return err
  576. }
  577. if f != nil {
  578. f.Close()
  579. }
  580. return unix.Mount(node.Path, dest, "bind", unix.MS_BIND, "")
  581. }
  582. // Creates the device node in the rootfs of the container.
  583. func createDeviceNode(rootfs string, node *configs.Device, bind bool) error {
  584. dest := filepath.Join(rootfs, node.Path)
  585. if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
  586. return err
  587. }
  588. if bind {
  589. return bindMountDeviceNode(dest, node)
  590. }
  591. if err := mknodDevice(dest, node); err != nil {
  592. if os.IsExist(err) {
  593. return nil
  594. } else if os.IsPermission(err) {
  595. return bindMountDeviceNode(dest, node)
  596. }
  597. return err
  598. }
  599. return nil
  600. }
  601. func mknodDevice(dest string, node *configs.Device) error {
  602. fileMode := node.FileMode
  603. switch node.Type {
  604. case 'c', 'u':
  605. fileMode |= unix.S_IFCHR
  606. case 'b':
  607. fileMode |= unix.S_IFBLK
  608. case 'p':
  609. fileMode |= unix.S_IFIFO
  610. default:
  611. return fmt.Errorf("%c is not a valid device type for device %s", node.Type, node.Path)
  612. }
  613. if err := unix.Mknod(dest, uint32(fileMode), node.Mkdev()); err != nil {
  614. return err
  615. }
  616. return unix.Chown(dest, int(node.Uid), int(node.Gid))
  617. }
  618. func getMountInfo(mountinfo []*mount.Info, dir string) *mount.Info {
  619. for _, m := range mountinfo {
  620. if m.Mountpoint == dir {
  621. return m
  622. }
  623. }
  624. return nil
  625. }
  626. // Get the parent mount point of directory passed in as argument. Also return
  627. // optional fields.
  628. func getParentMount(rootfs string) (string, string, error) {
  629. var path string
  630. mountinfos, err := mount.GetMounts()
  631. if err != nil {
  632. return "", "", err
  633. }
  634. mountinfo := getMountInfo(mountinfos, rootfs)
  635. if mountinfo != nil {
  636. return rootfs, mountinfo.Optional, nil
  637. }
  638. path = rootfs
  639. for {
  640. path = filepath.Dir(path)
  641. mountinfo = getMountInfo(mountinfos, path)
  642. if mountinfo != nil {
  643. return path, mountinfo.Optional, nil
  644. }
  645. if path == "/" {
  646. break
  647. }
  648. }
  649. // If we are here, we did not find parent mount. Something is wrong.
  650. return "", "", fmt.Errorf("Could not find parent mount of %s", rootfs)
  651. }
  652. // Make parent mount private if it was shared
  653. func rootfsParentMountPrivate(rootfs string) error {
  654. sharedMount := false
  655. parentMount, optionalOpts, err := getParentMount(rootfs)
  656. if err != nil {
  657. return err
  658. }
  659. optsSplit := strings.Split(optionalOpts, " ")
  660. for _, opt := range optsSplit {
  661. if strings.HasPrefix(opt, "shared:") {
  662. sharedMount = true
  663. break
  664. }
  665. }
  666. // Make parent mount PRIVATE if it was shared. It is needed for two
  667. // reasons. First of all pivot_root() will fail if parent mount is
  668. // shared. Secondly when we bind mount rootfs it will propagate to
  669. // parent namespace and we don't want that to happen.
  670. if sharedMount {
  671. return unix.Mount("", parentMount, "", unix.MS_PRIVATE, "")
  672. }
  673. return nil
  674. }
  675. func prepareRoot(config *configs.Config) error {
  676. flag := unix.MS_SLAVE | unix.MS_REC
  677. if config.RootPropagation != 0 {
  678. flag = config.RootPropagation
  679. }
  680. if err := unix.Mount("", "/", "", uintptr(flag), ""); err != nil {
  681. return err
  682. }
  683. // Make parent mount private to make sure following bind mount does
  684. // not propagate in other namespaces. Also it will help with kernel
  685. // check pass in pivot_root. (IS_SHARED(new_mnt->mnt_parent))
  686. if err := rootfsParentMountPrivate(config.Rootfs); err != nil {
  687. return err
  688. }
  689. return unix.Mount(config.Rootfs, config.Rootfs, "bind", unix.MS_BIND|unix.MS_REC, "")
  690. }
  691. func setReadonly() error {
  692. return unix.Mount("/", "/", "bind", unix.MS_BIND|unix.MS_REMOUNT|unix.MS_RDONLY|unix.MS_REC, "")
  693. }
  694. func setupPtmx(config *configs.Config) error {
  695. ptmx := filepath.Join(config.Rootfs, "dev/ptmx")
  696. if err := os.Remove(ptmx); err != nil && !os.IsNotExist(err) {
  697. return err
  698. }
  699. if err := os.Symlink("pts/ptmx", ptmx); err != nil {
  700. return fmt.Errorf("symlink dev ptmx %s", err)
  701. }
  702. return nil
  703. }
  704. // pivotRoot will call pivot_root such that rootfs becomes the new root
  705. // filesystem, and everything else is cleaned up.
  706. func pivotRoot(rootfs string) error {
  707. // While the documentation may claim otherwise, pivot_root(".", ".") is
  708. // actually valid. What this results in is / being the new root but
  709. // /proc/self/cwd being the old root. Since we can play around with the cwd
  710. // with pivot_root this allows us to pivot without creating directories in
  711. // the rootfs. Shout-outs to the LXC developers for giving us this idea.
  712. oldroot, err := unix.Open("/", unix.O_DIRECTORY|unix.O_RDONLY, 0)
  713. if err != nil {
  714. return err
  715. }
  716. defer unix.Close(oldroot)
  717. newroot, err := unix.Open(rootfs, unix.O_DIRECTORY|unix.O_RDONLY, 0)
  718. if err != nil {
  719. return err
  720. }
  721. defer unix.Close(newroot)
  722. // Change to the new root so that the pivot_root actually acts on it.
  723. if err := unix.Fchdir(newroot); err != nil {
  724. return err
  725. }
  726. if err := unix.PivotRoot(".", "."); err != nil {
  727. return fmt.Errorf("pivot_root %s", err)
  728. }
  729. // Currently our "." is oldroot (according to the current kernel code).
  730. // However, purely for safety, we will fchdir(oldroot) since there isn't
  731. // really any guarantee from the kernel what /proc/self/cwd will be after a
  732. // pivot_root(2).
  733. if err := unix.Fchdir(oldroot); err != nil {
  734. return err
  735. }
  736. // Make oldroot rslave to make sure our unmounts don't propagate to the
  737. // host (and thus bork the machine). We don't use rprivate because this is
  738. // known to cause issues due to races where we still have a reference to a
  739. // mount while a process in the host namespace are trying to operate on
  740. // something they think has no mounts (devicemapper in particular).
  741. if err := unix.Mount("", ".", "", unix.MS_SLAVE|unix.MS_REC, ""); err != nil {
  742. return err
  743. }
  744. // Preform the unmount. MNT_DETACH allows us to unmount /proc/self/cwd.
  745. if err := unix.Unmount(".", unix.MNT_DETACH); err != nil {
  746. return err
  747. }
  748. // Switch back to our shiny new root.
  749. if err := unix.Chdir("/"); err != nil {
  750. return fmt.Errorf("chdir / %s", err)
  751. }
  752. return nil
  753. }
  754. func msMoveRoot(rootfs string) error {
  755. mountinfos, err := mount.GetMounts()
  756. if err != nil {
  757. return err
  758. }
  759. absRootfs, err := filepath.Abs(rootfs)
  760. if err != nil {
  761. return err
  762. }
  763. for _, info := range mountinfos {
  764. p, err := filepath.Abs(info.Mountpoint)
  765. if err != nil {
  766. return err
  767. }
  768. // Umount every syfs and proc file systems, except those under the container rootfs
  769. if (info.Fstype != "proc" && info.Fstype != "sysfs") || filepath.HasPrefix(p, absRootfs) {
  770. continue
  771. }
  772. // Be sure umount events are not propagated to the host.
  773. if err := unix.Mount("", p, "", unix.MS_SLAVE|unix.MS_REC, ""); err != nil {
  774. return err
  775. }
  776. if err := unix.Unmount(p, unix.MNT_DETACH); err != nil {
  777. if err != unix.EINVAL && err != unix.EPERM {
  778. return err
  779. } else {
  780. // If we have not privileges for umounting (e.g. rootless), then
  781. // cover the path.
  782. if err := unix.Mount("tmpfs", p, "tmpfs", 0, ""); err != nil {
  783. return err
  784. }
  785. }
  786. }
  787. }
  788. if err := unix.Mount(rootfs, "/", "", unix.MS_MOVE, ""); err != nil {
  789. return err
  790. }
  791. return chroot(rootfs)
  792. }
  793. func chroot(rootfs string) error {
  794. if err := unix.Chroot("."); err != nil {
  795. return err
  796. }
  797. return unix.Chdir("/")
  798. }
  799. // createIfNotExists creates a file or a directory only if it does not already exist.
  800. func createIfNotExists(path string, isDir bool) error {
  801. if _, err := os.Stat(path); err != nil {
  802. if os.IsNotExist(err) {
  803. if isDir {
  804. return os.MkdirAll(path, 0755)
  805. }
  806. if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
  807. return err
  808. }
  809. f, err := os.OpenFile(path, os.O_CREATE, 0755)
  810. if err != nil {
  811. return err
  812. }
  813. f.Close()
  814. }
  815. }
  816. return nil
  817. }
  818. // readonlyPath will make a path read only.
  819. func readonlyPath(path string) error {
  820. if err := unix.Mount(path, path, "", unix.MS_BIND|unix.MS_REC, ""); err != nil {
  821. if os.IsNotExist(err) {
  822. return nil
  823. }
  824. return err
  825. }
  826. return unix.Mount(path, path, "", unix.MS_BIND|unix.MS_REMOUNT|unix.MS_RDONLY|unix.MS_REC, "")
  827. }
  828. // remountReadonly will remount an existing mount point and ensure that it is read-only.
  829. func remountReadonly(m *configs.Mount) error {
  830. var (
  831. dest = m.Destination
  832. flags = m.Flags
  833. )
  834. for i := 0; i < 5; i++ {
  835. // There is a special case in the kernel for
  836. // MS_REMOUNT | MS_BIND, which allows us to change only the
  837. // flags even as an unprivileged user (i.e. user namespace)
  838. // assuming we don't drop any security related flags (nodev,
  839. // nosuid, etc.). So, let's use that case so that we can do
  840. // this re-mount without failing in a userns.
  841. flags |= unix.MS_REMOUNT | unix.MS_BIND | unix.MS_RDONLY
  842. if err := unix.Mount("", dest, "", uintptr(flags), ""); err != nil {
  843. switch err {
  844. case unix.EBUSY:
  845. time.Sleep(100 * time.Millisecond)
  846. continue
  847. default:
  848. return err
  849. }
  850. }
  851. return nil
  852. }
  853. return fmt.Errorf("unable to mount %s as readonly max retries reached", dest)
  854. }
  855. // maskPath masks the top of the specified path inside a container to avoid
  856. // security issues from processes reading information from non-namespace aware
  857. // mounts ( proc/kcore ).
  858. // For files, maskPath bind mounts /dev/null over the top of the specified path.
  859. // For directories, maskPath mounts read-only tmpfs over the top of the specified path.
  860. func maskPath(path string, mountLabel string) error {
  861. if err := unix.Mount("/dev/null", path, "", unix.MS_BIND, ""); err != nil && !os.IsNotExist(err) {
  862. if err == unix.ENOTDIR {
  863. return unix.Mount("tmpfs", path, "tmpfs", unix.MS_RDONLY, label.FormatMountLabel("", mountLabel))
  864. }
  865. return err
  866. }
  867. return nil
  868. }
  869. // writeSystemProperty writes the value to a path under /proc/sys as determined from the key.
  870. // For e.g. net.ipv4.ip_forward translated to /proc/sys/net/ipv4/ip_forward.
  871. func writeSystemProperty(key, value string) error {
  872. keyPath := strings.Replace(key, ".", "/", -1)
  873. return ioutil.WriteFile(path.Join("/proc/sys", keyPath), []byte(value), 0644)
  874. }
  875. func remount(m *configs.Mount, rootfs string) error {
  876. var (
  877. dest = m.Destination
  878. )
  879. if !strings.HasPrefix(dest, rootfs) {
  880. dest = filepath.Join(rootfs, dest)
  881. }
  882. return unix.Mount(m.Source, dest, m.Device, uintptr(m.Flags|unix.MS_REMOUNT), "")
  883. }
  884. // Do the mount operation followed by additional mounts required to take care
  885. // of propagation flags.
  886. func mountPropagate(m *configs.Mount, rootfs string, mountLabel string) error {
  887. var (
  888. dest = m.Destination
  889. data = label.FormatMountLabel(m.Data, mountLabel)
  890. flags = m.Flags
  891. )
  892. if libcontainerUtils.CleanPath(dest) == "/dev" {
  893. flags &= ^unix.MS_RDONLY
  894. }
  895. copyUp := m.Extensions&configs.EXT_COPYUP == configs.EXT_COPYUP
  896. if !(copyUp || strings.HasPrefix(dest, rootfs)) {
  897. dest = filepath.Join(rootfs, dest)
  898. }
  899. if err := unix.Mount(m.Source, dest, m.Device, uintptr(flags), data); err != nil {
  900. return err
  901. }
  902. for _, pflag := range m.PropagationFlags {
  903. if err := unix.Mount("", dest, "", uintptr(pflag), ""); err != nil {
  904. return err
  905. }
  906. }
  907. return nil
  908. }
  909. func mountNewCgroup(m *configs.Mount) error {
  910. var (
  911. data = m.Data
  912. source = m.Source
  913. )
  914. if data == "systemd" {
  915. data = cgroups.CgroupNamePrefix + data
  916. source = "systemd"
  917. }
  918. if err := unix.Mount(source, m.Destination, m.Device, uintptr(m.Flags), data); err != nil {
  919. return err
  920. }
  921. return nil
  922. }