Skip to content

Commit

Permalink
loopback: use fstat on the open file descriptor
Browse files Browse the repository at this point in the history
move the stat call later after the file is already opened so it is
less vulnerable to the file being removed between the stat and the
open syscall.

Signed-off-by: Giuseppe Scrivano <[email protected]>
  • Loading branch information
giuseppe committed Jul 23, 2024
1 parent 2713872 commit 7bd2cce
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions pkg/loopback/attach_loopback.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package loopback
import (
"errors"
"fmt"
"io/fs"
"os"
"syscall"

Expand Down Expand Up @@ -53,26 +54,28 @@ func openNextAvailableLoopback(index int, sparseName string, sparseFile *os.File
target := fmt.Sprintf("/dev/loop%d", index)
index++

fi, err := os.Stat(target)
// OpenFile adds O_CLOEXEC
loopFile, err = os.OpenFile(target, os.O_RDWR, 0o644)
if err != nil {
if os.IsNotExist(err) {
logrus.Debug("There are no more loopback devices available.")
if errors.Is(err, fs.ErrNotExist) {
continue
}
logrus.Errorf("Opening loopback device: %s", err)
return nil, ErrAttachLoopbackDevice
}

fi, err := loopFile.Stat()
if err != nil {
loopFile.Close()
logrus.Errorf("Stat loopback device: %s", err)
return nil, ErrAttachLoopbackDevice
}
if fi.Mode()&os.ModeDevice != os.ModeDevice {
loopFile.Close()
logrus.Errorf("Loopback device %s is not a block device.", target)
continue
}

// OpenFile adds O_CLOEXEC
loopFile, err = os.OpenFile(target, os.O_RDWR, 0o644)
if err != nil {
logrus.Errorf("Opening loopback device: %s", err)
return nil, ErrAttachLoopbackDevice
}

// Try to attach to the loop file
if err := ioctlLoopSetFd(loopFile.Fd(), sparseFile.Fd()); err != nil {
loopFile.Close()
Expand Down

0 comments on commit 7bd2cce

Please sign in to comment.