rootfs_linux.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. // +build linux
  2. package libcontainer
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "os/exec"
  8. "path"
  9. "path/filepath"
  10. "strings"
  11. "syscall"
  12. "time"
  13. "github.com/docker/docker/pkg/symlink"
  14. "github.com/docker/libcontainer/cgroups"
  15. "github.com/docker/libcontainer/configs"
  16. "github.com/docker/libcontainer/label"
  17. )
  18. const defaultMountFlags = syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NODEV
  19. // setupRootfs sets up the devices, mount points, and filesystems for use inside a
  20. // new mount namespace.
  21. func setupRootfs(config *configs.Config, console *linuxConsole) (err error) {
  22. if err := prepareRoot(config); err != nil {
  23. return newSystemError(err)
  24. }
  25. for _, m := range config.Mounts {
  26. for _, precmd := range m.PremountCmds {
  27. if err := mountCmd(precmd); err != nil {
  28. return newSystemError(err)
  29. }
  30. }
  31. if err := mountToRootfs(m, config.Rootfs, config.MountLabel); err != nil {
  32. return newSystemError(err)
  33. }
  34. for _, postcmd := range m.PostmountCmds {
  35. if err := mountCmd(postcmd); err != nil {
  36. return newSystemError(err)
  37. }
  38. }
  39. }
  40. if err := createDevices(config); err != nil {
  41. return newSystemError(err)
  42. }
  43. if err := setupPtmx(config, console); err != nil {
  44. return newSystemError(err)
  45. }
  46. if err := setupDevSymlinks(config.Rootfs); err != nil {
  47. return newSystemError(err)
  48. }
  49. if err := syscall.Chdir(config.Rootfs); err != nil {
  50. return newSystemError(err)
  51. }
  52. if config.NoPivotRoot {
  53. err = msMoveRoot(config.Rootfs)
  54. } else {
  55. err = pivotRoot(config.Rootfs, config.PivotDir)
  56. }
  57. if err != nil {
  58. return newSystemError(err)
  59. }
  60. if err := reOpenDevNull(config.Rootfs); err != nil {
  61. return newSystemError(err)
  62. }
  63. if config.Readonlyfs {
  64. if err := setReadonly(); err != nil {
  65. return newSystemError(err)
  66. }
  67. }
  68. syscall.Umask(0022)
  69. return nil
  70. }
  71. func mountCmd(cmd configs.Command) error {
  72. command := exec.Command(cmd.Path, cmd.Args[:]...)
  73. command.Env = cmd.Env
  74. command.Dir = cmd.Dir
  75. if out, err := command.CombinedOutput(); err != nil {
  76. return fmt.Errorf("%#v failed: %s: %v", cmd, string(out), err)
  77. }
  78. return nil
  79. }
  80. func mountToRootfs(m *configs.Mount, rootfs, mountLabel string) error {
  81. var (
  82. dest = m.Destination
  83. data = label.FormatMountLabel(m.Data, mountLabel)
  84. )
  85. if !strings.HasPrefix(dest, rootfs) {
  86. dest = filepath.Join(rootfs, dest)
  87. }
  88. switch m.Device {
  89. case "proc", "sysfs":
  90. if err := os.MkdirAll(dest, 0755); err != nil && !os.IsExist(err) {
  91. return err
  92. }
  93. return syscall.Mount(m.Source, dest, m.Device, uintptr(m.Flags), "")
  94. case "mqueue":
  95. if err := os.MkdirAll(dest, 0755); err != nil && !os.IsExist(err) {
  96. return err
  97. }
  98. if err := syscall.Mount(m.Source, dest, m.Device, uintptr(m.Flags), ""); err != nil {
  99. return err
  100. }
  101. return label.SetFileLabel(dest, mountLabel)
  102. case "tmpfs":
  103. stat, err := os.Stat(dest)
  104. if err != nil {
  105. if err := os.MkdirAll(dest, 0755); err != nil && !os.IsExist(err) {
  106. return err
  107. }
  108. }
  109. if err := syscall.Mount(m.Source, dest, m.Device, uintptr(m.Flags), data); err != nil {
  110. return err
  111. }
  112. if stat != nil {
  113. if err = os.Chmod(dest, stat.Mode()); err != nil {
  114. return err
  115. }
  116. }
  117. return nil
  118. case "devpts":
  119. if err := os.MkdirAll(dest, 0755); err != nil && !os.IsExist(err) {
  120. return err
  121. }
  122. return syscall.Mount(m.Source, dest, m.Device, uintptr(m.Flags), data)
  123. case "bind":
  124. stat, err := os.Stat(m.Source)
  125. if err != nil {
  126. // error out if the source of a bind mount does not exist as we will be
  127. // unable to bind anything to it.
  128. return err
  129. }
  130. // ensure that the destination of the bind mount is resolved of symlinks at mount time because
  131. // any previous mounts can invalidate the next mount's destination.
  132. // this can happen when a user specifies mounts within other mounts to cause breakouts or other
  133. // evil stuff to try to escape the container's rootfs.
  134. if dest, err = symlink.FollowSymlinkInScope(filepath.Join(rootfs, m.Destination), rootfs); err != nil {
  135. return err
  136. }
  137. if err := checkMountDestination(rootfs, dest); err != nil {
  138. return err
  139. }
  140. if err := createIfNotExists(dest, stat.IsDir()); err != nil {
  141. return err
  142. }
  143. if err := syscall.Mount(m.Source, dest, m.Device, uintptr(m.Flags), data); err != nil {
  144. return err
  145. }
  146. if m.Flags&syscall.MS_RDONLY != 0 {
  147. if err := syscall.Mount(m.Source, dest, m.Device, uintptr(m.Flags|syscall.MS_REMOUNT), ""); err != nil {
  148. return err
  149. }
  150. }
  151. if m.Relabel != "" {
  152. if err := label.Relabel(m.Source, mountLabel, m.Relabel); err != nil {
  153. return err
  154. }
  155. }
  156. if m.Flags&syscall.MS_PRIVATE != 0 {
  157. if err := syscall.Mount("", dest, "none", uintptr(syscall.MS_PRIVATE), ""); err != nil {
  158. return err
  159. }
  160. }
  161. case "cgroup":
  162. mounts, err := cgroups.GetCgroupMounts()
  163. if err != nil {
  164. return err
  165. }
  166. var binds []*configs.Mount
  167. for _, mm := range mounts {
  168. dir, err := mm.GetThisCgroupDir()
  169. if err != nil {
  170. return err
  171. }
  172. binds = append(binds, &configs.Mount{
  173. Device: "bind",
  174. Source: filepath.Join(mm.Mountpoint, dir),
  175. Destination: filepath.Join(m.Destination, strings.Join(mm.Subsystems, ",")),
  176. Flags: syscall.MS_BIND | syscall.MS_REC | syscall.MS_RDONLY,
  177. })
  178. }
  179. tmpfs := &configs.Mount{
  180. Device: "tmpfs",
  181. Destination: m.Destination,
  182. Flags: syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NODEV,
  183. }
  184. if err := mountToRootfs(tmpfs, rootfs, mountLabel); err != nil {
  185. return err
  186. }
  187. for _, b := range binds {
  188. if err := mountToRootfs(b, rootfs, mountLabel); err != nil {
  189. return err
  190. }
  191. }
  192. default:
  193. return fmt.Errorf("unknown mount device %q to %q", m.Device, m.Destination)
  194. }
  195. return nil
  196. }
  197. // checkMountDestination checks to ensure that the mount destination is not over the
  198. // top of /proc or /sys.
  199. // dest is required to be an abs path and have any symlinks resolved before calling this function.
  200. func checkMountDestination(rootfs, dest string) error {
  201. if filepath.Clean(rootfs) == filepath.Clean(dest) {
  202. return fmt.Errorf("mounting into / is prohibited")
  203. }
  204. invalidDestinations := []string{
  205. "/proc",
  206. "/sys",
  207. }
  208. for _, invalid := range invalidDestinations {
  209. path, err := filepath.Rel(filepath.Join(rootfs, invalid), dest)
  210. if err != nil {
  211. return err
  212. }
  213. if path == "." || !strings.HasPrefix(path, "..") {
  214. return fmt.Errorf("%q cannot be mounted because it is located inside %q", dest, invalid)
  215. }
  216. }
  217. return nil
  218. }
  219. func setupDevSymlinks(rootfs string) error {
  220. var links = [][2]string{
  221. {"/proc/self/fd", "/dev/fd"},
  222. {"/proc/self/fd/0", "/dev/stdin"},
  223. {"/proc/self/fd/1", "/dev/stdout"},
  224. {"/proc/self/fd/2", "/dev/stderr"},
  225. }
  226. // kcore support can be toggled with CONFIG_PROC_KCORE; only create a symlink
  227. // in /dev if it exists in /proc.
  228. if _, err := os.Stat("/proc/kcore"); err == nil {
  229. links = append(links, [2]string{"/proc/kcore", "/dev/kcore"})
  230. }
  231. for _, link := range links {
  232. var (
  233. src = link[0]
  234. dst = filepath.Join(rootfs, link[1])
  235. )
  236. if err := os.Symlink(src, dst); err != nil && !os.IsExist(err) {
  237. return fmt.Errorf("symlink %s %s %s", src, dst, err)
  238. }
  239. }
  240. return nil
  241. }
  242. // If stdin, stdout, and/or stderr are pointing to `/dev/null` in the parent's rootfs
  243. // this method will make them point to `/dev/null` in this container's rootfs. This
  244. // needs to be called after we chroot/pivot into the container's rootfs so that any
  245. // symlinks are resolved locally.
  246. func reOpenDevNull(rootfs string) error {
  247. var stat, devNullStat syscall.Stat_t
  248. file, err := os.Open("/dev/null")
  249. if err != nil {
  250. return fmt.Errorf("Failed to open /dev/null - %s", err)
  251. }
  252. defer file.Close()
  253. if err := syscall.Fstat(int(file.Fd()), &devNullStat); err != nil {
  254. return err
  255. }
  256. for fd := 0; fd < 3; fd++ {
  257. if err := syscall.Fstat(fd, &stat); err != nil {
  258. return err
  259. }
  260. if stat.Rdev == devNullStat.Rdev {
  261. // Close and re-open the fd.
  262. if err := syscall.Dup2(int(file.Fd()), fd); err != nil {
  263. return err
  264. }
  265. }
  266. }
  267. return nil
  268. }
  269. // Create the device nodes in the container.
  270. func createDevices(config *configs.Config) error {
  271. oldMask := syscall.Umask(0000)
  272. for _, node := range config.Devices {
  273. // containers running in a user namespace are not allowed to mknod
  274. // devices so we can just bind mount it from the host.
  275. if err := createDeviceNode(config.Rootfs, node, config.Namespaces.Contains(configs.NEWUSER)); err != nil {
  276. syscall.Umask(oldMask)
  277. return err
  278. }
  279. }
  280. syscall.Umask(oldMask)
  281. return nil
  282. }
  283. // Creates the device node in the rootfs of the container.
  284. func createDeviceNode(rootfs string, node *configs.Device, bind bool) error {
  285. dest := filepath.Join(rootfs, node.Path)
  286. if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
  287. return err
  288. }
  289. if bind {
  290. f, err := os.Create(dest)
  291. if err != nil && !os.IsExist(err) {
  292. return err
  293. }
  294. if f != nil {
  295. f.Close()
  296. }
  297. return syscall.Mount(node.Path, dest, "bind", syscall.MS_BIND, "")
  298. }
  299. if err := mknodDevice(dest, node); err != nil {
  300. if os.IsExist(err) {
  301. return nil
  302. }
  303. return err
  304. }
  305. return nil
  306. }
  307. func mknodDevice(dest string, node *configs.Device) error {
  308. fileMode := node.FileMode
  309. switch node.Type {
  310. case 'c':
  311. fileMode |= syscall.S_IFCHR
  312. case 'b':
  313. fileMode |= syscall.S_IFBLK
  314. default:
  315. return fmt.Errorf("%c is not a valid device type for device %s", node.Type, node.Path)
  316. }
  317. if err := syscall.Mknod(dest, uint32(fileMode), node.Mkdev()); err != nil {
  318. return err
  319. }
  320. return syscall.Chown(dest, int(node.Uid), int(node.Gid))
  321. }
  322. func prepareRoot(config *configs.Config) error {
  323. flag := syscall.MS_SLAVE | syscall.MS_REC
  324. if config.Privatefs {
  325. flag = syscall.MS_PRIVATE | syscall.MS_REC
  326. }
  327. if err := syscall.Mount("", "/", "", uintptr(flag), ""); err != nil {
  328. return err
  329. }
  330. return syscall.Mount(config.Rootfs, config.Rootfs, "bind", syscall.MS_BIND|syscall.MS_REC, "")
  331. }
  332. func setReadonly() error {
  333. return syscall.Mount("/", "/", "bind", syscall.MS_BIND|syscall.MS_REMOUNT|syscall.MS_RDONLY|syscall.MS_REC, "")
  334. }
  335. func setupPtmx(config *configs.Config, console *linuxConsole) error {
  336. ptmx := filepath.Join(config.Rootfs, "dev/ptmx")
  337. if err := os.Remove(ptmx); err != nil && !os.IsNotExist(err) {
  338. return err
  339. }
  340. if err := os.Symlink("pts/ptmx", ptmx); err != nil {
  341. return fmt.Errorf("symlink dev ptmx %s", err)
  342. }
  343. if console != nil {
  344. return console.mount(config.Rootfs, config.MountLabel, 0, 0)
  345. }
  346. return nil
  347. }
  348. func pivotRoot(rootfs, pivotBaseDir string) error {
  349. if pivotBaseDir == "" {
  350. pivotBaseDir = "/"
  351. }
  352. tmpDir := filepath.Join(rootfs, pivotBaseDir)
  353. if err := os.MkdirAll(tmpDir, 0755); err != nil {
  354. return fmt.Errorf("can't create tmp dir %s, error %v", tmpDir, err)
  355. }
  356. pivotDir, err := ioutil.TempDir(tmpDir, ".pivot_root")
  357. if err != nil {
  358. return fmt.Errorf("can't create pivot_root dir %s, error %v", pivotDir, err)
  359. }
  360. if err := syscall.PivotRoot(rootfs, pivotDir); err != nil {
  361. return fmt.Errorf("pivot_root %s", err)
  362. }
  363. if err := syscall.Chdir("/"); err != nil {
  364. return fmt.Errorf("chdir / %s", err)
  365. }
  366. // path to pivot dir now changed, update
  367. pivotDir = filepath.Join(pivotBaseDir, filepath.Base(pivotDir))
  368. if err := syscall.Unmount(pivotDir, syscall.MNT_DETACH); err != nil {
  369. return fmt.Errorf("unmount pivot_root dir %s", err)
  370. }
  371. return os.Remove(pivotDir)
  372. }
  373. func msMoveRoot(rootfs string) error {
  374. if err := syscall.Mount(rootfs, "/", "", syscall.MS_MOVE, ""); err != nil {
  375. return err
  376. }
  377. if err := syscall.Chroot("."); err != nil {
  378. return err
  379. }
  380. return syscall.Chdir("/")
  381. }
  382. // createIfNotExists creates a file or a directory only if it does not already exist.
  383. func createIfNotExists(path string, isDir bool) error {
  384. if _, err := os.Stat(path); err != nil {
  385. if os.IsNotExist(err) {
  386. if isDir {
  387. return os.MkdirAll(path, 0755)
  388. }
  389. if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
  390. return err
  391. }
  392. f, err := os.OpenFile(path, os.O_CREATE, 0755)
  393. if err != nil {
  394. return err
  395. }
  396. f.Close()
  397. }
  398. }
  399. return nil
  400. }
  401. // remountReadonly will bind over the top of an existing path and ensure that it is read-only.
  402. func remountReadonly(path string) error {
  403. for i := 0; i < 5; i++ {
  404. if err := syscall.Mount("", path, "", syscall.MS_REMOUNT|syscall.MS_RDONLY, ""); err != nil && !os.IsNotExist(err) {
  405. switch err {
  406. case syscall.EINVAL:
  407. // Probably not a mountpoint, use bind-mount
  408. if err := syscall.Mount(path, path, "", syscall.MS_BIND, ""); err != nil {
  409. return err
  410. }
  411. return syscall.Mount(path, path, "", syscall.MS_BIND|syscall.MS_REMOUNT|syscall.MS_RDONLY|syscall.MS_REC|defaultMountFlags, "")
  412. case syscall.EBUSY:
  413. time.Sleep(100 * time.Millisecond)
  414. continue
  415. default:
  416. return err
  417. }
  418. }
  419. return nil
  420. }
  421. return fmt.Errorf("unable to mount %s as readonly max retries reached", path)
  422. }
  423. // maskFile bind mounts /dev/null over the top of the specified path inside a container
  424. // to avoid security issues from processes reading information from non-namespace aware mounts ( proc/kcore ).
  425. func maskFile(path string) error {
  426. if err := syscall.Mount("/dev/null", path, "", syscall.MS_BIND, ""); err != nil && !os.IsNotExist(err) {
  427. return err
  428. }
  429. return nil
  430. }
  431. // writeSystemProperty writes the value to a path under /proc/sys as determined from the key.
  432. // For e.g. net.ipv4.ip_forward translated to /proc/sys/net/ipv4/ip_forward.
  433. func writeSystemProperty(key, value string) error {
  434. keyPath := strings.Replace(key, ".", "/", -1)
  435. return ioutil.WriteFile(path.Join("/proc/sys", keyPath), []byte(value), 0644)
  436. }