From 5f9d14115983f1cfd70e7aaad63e0b23d0944221 Mon Sep 17 00:00:00 2001 From: Julio Montes Date: Tue, 26 May 2020 00:33:35 -0700 Subject: [PATCH] virtcontainers: update sandbox's device cgroup Update sandbox's device cgroup before hotpluggin a device and after it has been removed from the VM, this way the device cgroup in the host is fully honoured and the hypervisor will have access only to the devices needed for the sandbox, improving the security. Signed-off-by: Julio Montes Signed-off-by: Peng Tao --- src/runtime/virtcontainers/sandbox.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/runtime/virtcontainers/sandbox.go b/src/runtime/virtcontainers/sandbox.go index 41439cc36d..083b9a5f1a 100644 --- a/src/runtime/virtcontainers/sandbox.go +++ b/src/runtime/virtcontainers/sandbox.go @@ -1648,6 +1648,17 @@ func (s *Sandbox) HotplugAddDevice(device api.Device, devType config.DeviceType) span, _ := s.trace("HotplugAddDevice") defer span.Finish() + if s.config.SandboxCgroupOnly { + // We are about to add a device to the hypervisor, + // the device cgroup MUST be updated since the hypervisor + // will need access to such device + hdev := device.GetHostPath() + if err := s.cgroupMgr.AddDevice(hdev); err != nil { + s.Logger().WithError(err).WithField("device", hdev). + Warn("Could not add device to cgroup") + } + } + switch devType { case config.DeviceVFIO: vfioDevices, ok := device.GetDeviceInfo().([]*config.VFIODev) @@ -1692,6 +1703,18 @@ func (s *Sandbox) HotplugAddDevice(device api.Device, devType config.DeviceType) // HotplugRemoveDevice is used for removing a device from sandbox // Sandbox implement DeviceReceiver interface from device/api/interface.go func (s *Sandbox) HotplugRemoveDevice(device api.Device, devType config.DeviceType) error { + defer func() { + if s.config.SandboxCgroupOnly { + // Remove device from cgroup, the hypervisor + // should not have access to such device anymore. + hdev := device.GetHostPath() + if err := s.cgroupMgr.RemoveDevice(hdev); err != nil { + s.Logger().WithError(err).WithField("device", hdev). + Warn("Could not remove device from cgroup") + } + } + }() + switch devType { case config.DeviceVFIO: vfioDevices, ok := device.GetDeviceInfo().([]*config.VFIODev)