rootfs_linux.go 24 KB

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