fix: harden maintenance operations
This commit is contained in:
@@ -5,7 +5,6 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
@@ -30,39 +29,13 @@ func (l *Lock) Lock(ctx context.Context) (func(), error) {
|
||||
if !filepath.IsAbs(l.path) {
|
||||
return nil, errors.New("operation lock path must be absolute")
|
||||
}
|
||||
directory := filepath.Dir(l.path)
|
||||
if err := os.MkdirAll(directory, 0o700); err != nil {
|
||||
return nil, fmt.Errorf("create operation lock directory: %w", err)
|
||||
store := securefs.Store{TrustedRoot: securefs.ExistingTrustedRoot(l.path)}
|
||||
if l.owned {
|
||||
store.Owner = &securefs.Owner{UID: l.uid, GID: l.gid}
|
||||
}
|
||||
if err := os.Chmod(directory, 0o700); err != nil {
|
||||
return nil, fmt.Errorf("secure operation lock directory: %w", err)
|
||||
}
|
||||
if l.owned && (os.Geteuid() != l.uid || os.Getegid() != l.gid) {
|
||||
if err := os.Chown(directory, l.uid, l.gid); err != nil {
|
||||
return nil, fmt.Errorf("set operation lock directory owner: %w", err)
|
||||
}
|
||||
}
|
||||
file, err := securefs.OpenNoFollow(l.path, unix.O_CREAT|unix.O_RDWR|unix.O_NONBLOCK, 0o600)
|
||||
file, err := store.OpenRegular(l.path, unix.O_CREAT|unix.O_RDWR|unix.O_NONBLOCK, 0o600)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open operation lock: %w", err)
|
||||
}
|
||||
info, err := file.Stat()
|
||||
if err != nil || !info.Mode().IsRegular() {
|
||||
file.Close()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("inspect operation lock: %w", err)
|
||||
}
|
||||
return nil, errors.New("operation lock is not a regular file")
|
||||
}
|
||||
if err := file.Chmod(0o600); err != nil {
|
||||
file.Close()
|
||||
return nil, fmt.Errorf("secure operation lock: %w", err)
|
||||
}
|
||||
if l.owned && (os.Geteuid() != l.uid || os.Getegid() != l.gid) {
|
||||
if err := file.Chown(l.uid, l.gid); err != nil {
|
||||
file.Close()
|
||||
return nil, fmt.Errorf("set operation lock owner: %w", err)
|
||||
}
|
||||
return nil, fmt.Errorf("open operation lock securely: %w", err)
|
||||
}
|
||||
for {
|
||||
err = unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB)
|
||||
|
||||
Reference in New Issue
Block a user