fix(auth): harden Windows auth store privacy
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
//go:build !windows
|
||||
|
||||
package safeio
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// ProtectPrivateDirectory sets the private directory mode used for local authentication state.
|
||||
func ProtectPrivateDirectory(path string) error {
|
||||
if err := ValidateCanonicalPath(path); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Chmod(path, 0o700); err != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
return ValidatePrivateDirectory(path)
|
||||
}
|
||||
|
||||
// ValidatePrivateDirectory requires a canonical, non-symlinked directory with no group or world access.
|
||||
func ValidatePrivateDirectory(path string) error {
|
||||
if err := requireCanonicalDirectory(path); err != nil {
|
||||
return err
|
||||
}
|
||||
info, err := os.Lstat(path)
|
||||
if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 || !isExactPrivateMode(info.Mode(), 0o700) {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ProtectPrivateRegular sets the private file mode used for local authentication files.
|
||||
func ProtectPrivateRegular(path string) error {
|
||||
if err := ValidateCanonicalPath(path); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Chmod(path, 0o600); err != nil {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
return ValidatePrivateRegular(path)
|
||||
}
|
||||
|
||||
// ValidatePrivateRegular requires a canonical, single-link private regular file.
|
||||
func ValidatePrivateRegular(path string) error {
|
||||
if err := ValidateCanonicalPath(path); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := requireCanonicalDirectory(filepath.Dir(path)); err != nil {
|
||||
return err
|
||||
}
|
||||
info, err := os.Lstat(path)
|
||||
if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 || !hasSingleLink(info) || !isExactPrivateMode(info.Mode(), 0o600) {
|
||||
return ErrUnsafeFile
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isExactPrivateMode(mode os.FileMode, permissions os.FileMode) bool {
|
||||
return mode.Perm() == permissions && mode&(os.ModeSetuid|os.ModeSetgid|os.ModeSticky) == 0
|
||||
}
|
||||
Reference in New Issue
Block a user