2014-05-01 10:09:25 +08:00
|
|
|
// +build linux
|
|
|
|
|
2014-04-11 07:03:52 +08:00
|
|
|
package restrict
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2014-05-08 15:03:45 +08:00
|
|
|
"os"
|
2014-04-11 07:03:52 +08:00
|
|
|
"syscall"
|
2014-05-29 09:09:05 +08:00
|
|
|
"time"
|
2014-04-24 09:12:07 +08:00
|
|
|
|
|
|
|
"github.com/dotcloud/docker/pkg/system"
|
2014-04-11 07:03:52 +08:00
|
|
|
)
|
|
|
|
|
2014-05-19 15:51:20 +08:00
|
|
|
const defaultMountFlags = syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NODEV
|
|
|
|
|
|
|
|
func mountReadonly(path string) error {
|
2014-05-29 09:09:05 +08:00
|
|
|
for i := 0; i < 5; i++ {
|
|
|
|
if err := system.Mount("", path, "", syscall.MS_REMOUNT|syscall.MS_RDONLY, ""); err != nil {
|
|
|
|
switch err {
|
|
|
|
case syscall.EINVAL:
|
|
|
|
// Probably not a mountpoint, use bind-mount
|
|
|
|
if err := system.Mount(path, path, "", syscall.MS_BIND, ""); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return system.Mount(path, path, "", syscall.MS_BIND|syscall.MS_REMOUNT|syscall.MS_RDONLY|syscall.MS_REC|defaultMountFlags, "")
|
|
|
|
case syscall.EBUSY:
|
|
|
|
time.Sleep(100 * time.Millisecond)
|
|
|
|
continue
|
|
|
|
default:
|
2014-05-19 15:51:20 +08:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2014-05-29 09:09:05 +08:00
|
|
|
return nil
|
2014-05-19 15:51:20 +08:00
|
|
|
}
|
2014-05-29 09:09:05 +08:00
|
|
|
return fmt.Errorf("unable to mount %s as readonly max retries reached", path)
|
2014-05-19 15:51:20 +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-03 02:14:24 +08:00
|
|
|
func Restrict(mounts ...string) error {
|
2014-05-02 01:08:18 +08:00
|
|
|
// remount proc and sys as readonly
|
2014-05-03 02:14:24 +08:00
|
|
|
for _, dest := range mounts {
|
2014-05-19 15:51:20 +08:00
|
|
|
if err := mountReadonly(dest); err != nil {
|
2014-05-02 01:08:18 +08:00
|
|
|
return fmt.Errorf("unable to remount %s readonly: %s", dest, err)
|
2014-04-11 07:03:52 +08:00
|
|
|
}
|
|
|
|
}
|
2014-05-29 09:09:05 +08:00
|
|
|
|
2014-05-08 15:03:45 +08:00
|
|
|
if err := system.Mount("/dev/null", "/proc/kcore", "", syscall.MS_BIND, ""); err != nil && !os.IsNotExist(err) {
|
|
|
|
return fmt.Errorf("unable to bind-mount /dev/null over /proc/kcore: %s", err)
|
2014-05-02 01:08:18 +08:00
|
|
|
}
|
2014-05-02 10:09:12 +08:00
|
|
|
return nil
|
2014-04-11 07:03:52 +08:00
|
|
|
}
|