2014-05-01 02:09:25 +00:00
|
|
|
// +build linux
|
|
|
|
|
2014-04-10 23:03:52 +00:00
|
|
|
package restrict
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2014-04-24 01:12:07 +00:00
|
|
|
"os"
|
2014-04-10 23:03:52 +00:00
|
|
|
"path/filepath"
|
|
|
|
"syscall"
|
2014-04-24 01:12:07 +00:00
|
|
|
|
|
|
|
"github.com/dotcloud/docker/pkg/system"
|
2014-04-10 23:03:52 +00:00
|
|
|
)
|
|
|
|
|
2014-05-01 01:00:42 +00:00
|
|
|
// This has to be called while the container still has CAP_SYS_ADMIN (to be able to perform mounts).
|
|
|
|
// However, afterwards, CAP_SYS_ADMIN should be dropped (otherwise the user will be able to revert those changes).
|
2014-05-01 17:08:18 +00:00
|
|
|
func Restrict() error {
|
|
|
|
// remount proc and sys as readonly
|
|
|
|
for _, dest := range []string{"proc", "sys"} {
|
|
|
|
if err := system.Mount("", dest, "", syscall.MS_REMOUNT|syscall.MS_RDONLY, ""); err != nil {
|
|
|
|
return fmt.Errorf("unable to remount %s readonly: %s", dest, err)
|
2014-04-10 23:03:52 +00:00
|
|
|
}
|
|
|
|
}
|
2014-05-01 20:55:23 +00:00
|
|
|
if err := system.Mount("/dev/null", "/proc/kcore", "", syscall.MS_BIND, ""); err != nil {
|
2014-05-01 17:08:18 +00:00
|
|
|
return fmt.Errorf("unable to bind-mount /dev/null over /proc/kcore")
|
|
|
|
}
|
|
|
|
|
2014-05-01 01:00:42 +00:00
|
|
|
// This weird trick will allow us to mount /proc read-only, while being able to use AppArmor.
|
|
|
|
// This is because apparently, loading an AppArmor profile requires write access to /proc/1/attr.
|
|
|
|
// So we do another mount of procfs, ensure it's write-able, and bind-mount a subset of it.
|
2014-05-01 17:08:18 +00:00
|
|
|
if err := os.Mkdir(".proc", 0700); err != nil {
|
|
|
|
return fmt.Errorf("unable to create temporary proc mountpoint .proc: %s", err)
|
2014-05-01 01:00:42 +00:00
|
|
|
}
|
2014-05-01 17:08:18 +00:00
|
|
|
if err := system.Mount("proc", ".proc", "proc", 0, ""); err != nil {
|
2014-05-01 01:00:42 +00:00
|
|
|
return fmt.Errorf("unable to mount proc on temporary proc mountpoint: %s", err)
|
|
|
|
}
|
2014-05-01 17:08:18 +00:00
|
|
|
if err := system.Mount("proc", ".proc", "", syscall.MS_REMOUNT, ""); err != nil {
|
2014-05-01 01:00:42 +00:00
|
|
|
return fmt.Errorf("unable to remount proc read-write: %s", err)
|
|
|
|
}
|
2014-05-01 18:11:29 +00:00
|
|
|
for _, path := range []string{"attr", "task"} {
|
|
|
|
if err := system.Mount(filepath.Join(".proc", "1", path), filepath.Join("proc", "1", path), "", syscall.MS_BIND, ""); err != nil {
|
|
|
|
return fmt.Errorf("unable to bind-mount %s: %s", path, err)
|
|
|
|
}
|
2014-05-01 01:00:42 +00:00
|
|
|
}
|
2014-05-01 17:08:18 +00:00
|
|
|
if err := system.Unmount(".proc", 0); err != nil {
|
2014-05-01 01:00:42 +00:00
|
|
|
return fmt.Errorf("unable to unmount temporary proc filesystem: %s", err)
|
|
|
|
}
|
2014-05-01 17:08:18 +00:00
|
|
|
return os.RemoveAll(".proc")
|
2014-04-10 23:03:52 +00:00
|
|
|
}
|