2014-05-01 10:09:25 +08:00
|
|
|
// +build linux
|
|
|
|
|
2014-04-11 07:03:52 +08:00
|
|
|
package restrict
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2014-04-24 09:12:07 +08:00
|
|
|
"os"
|
2014-04-11 07:03:52 +08:00
|
|
|
"path/filepath"
|
|
|
|
"syscall"
|
2014-04-24 09:12:07 +08:00
|
|
|
|
|
|
|
"github.com/dotcloud/docker/pkg/system"
|
2014-04-11 07:03:52 +08:00
|
|
|
)
|
|
|
|
|
2014-05-01 09:00:42 +08: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-02 01:08:18 +08: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-11 07:03:52 +08:00
|
|
|
}
|
|
|
|
}
|
2014-05-01 09:00:42 +08:00
|
|
|
|
2014-05-02 01:08:18 +08:00
|
|
|
if err := system.Mount("/proc/kcore", "/dev/null", "", syscall.MS_BIND, ""); err != nil {
|
|
|
|
return fmt.Errorf("unable to bind-mount /dev/null over /proc/kcore")
|
|
|
|
}
|
|
|
|
|
2014-05-01 09:00:42 +08: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-02 01:08:18 +08:00
|
|
|
if err := os.Mkdir(".proc", 0700); err != nil {
|
|
|
|
return fmt.Errorf("unable to create temporary proc mountpoint .proc: %s", err)
|
2014-05-01 09:00:42 +08:00
|
|
|
}
|
2014-05-02 01:08:18 +08:00
|
|
|
if err := system.Mount("proc", ".proc", "proc", 0, ""); err != nil {
|
2014-05-01 09:00:42 +08:00
|
|
|
return fmt.Errorf("unable to mount proc on temporary proc mountpoint: %s", err)
|
|
|
|
}
|
2014-05-02 01:08:18 +08:00
|
|
|
if err := system.Mount("proc", ".proc", "", syscall.MS_REMOUNT, ""); err != nil {
|
2014-05-01 09:00:42 +08:00
|
|
|
return fmt.Errorf("unable to remount proc read-write: %s", err)
|
|
|
|
}
|
2014-05-02 02:11:29 +08: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 09:00:42 +08:00
|
|
|
}
|
2014-05-02 01:08:18 +08:00
|
|
|
if err := system.Unmount(".proc", 0); err != nil {
|
2014-05-01 09:00:42 +08:00
|
|
|
return fmt.Errorf("unable to unmount temporary proc filesystem: %s", err)
|
|
|
|
}
|
2014-05-02 01:08:18 +08:00
|
|
|
return os.RemoveAll(".proc")
|
2014-04-11 07:03:52 +08:00
|
|
|
}
|