rootfs_linux.go 35 KB

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