rootfs_linux.go 25 KB

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