From 5614eca26b104b3e3ea680e4fbd2e4b631aa482a Mon Sep 17 00:00:00 2001 From: Daniel J Walsh Date: Mon, 26 Sep 2022 06:50:59 -0400 Subject: [PATCH] If chcon fails, check if label is already correct Currently if a user attempts to chcon a file or directory and fails for any reason check if the file already has the right label, and continue. Signed-off-by: Daniel J Walsh --- go-selinux/rchcon.go | 13 +++++++++++++ go-selinux/selinux_linux.go | 13 ++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/go-selinux/rchcon.go b/go-selinux/rchcon.go index fa1440d..8a726f0 100644 --- a/go-selinux/rchcon.go +++ b/go-selinux/rchcon.go @@ -12,7 +12,20 @@ import ( ) func rchcon(fpath, label string) error { + slowMode := false + // If the current label matches the new label, assume + // other labels are correct. + if currentLabel, err := lFileLabel(fpath); err == nil && + label == currentLabel { + slowMode = true + } return pwalkdir.Walk(fpath, func(p string, _ fs.DirEntry, _ error) error { + if slowMode { + if currentLabel, err := lFileLabel(p); err == nil && + label == currentLabel { + return nil + } + } e := lSetFileLabel(p, label) // Walk a file tree can race with removal, so ignore ENOENT. if errors.Is(e, os.ErrNotExist) { diff --git a/go-selinux/selinux_linux.go b/go-selinux/selinux_linux.go index bedc89f..526a2fc 100644 --- a/go-selinux/selinux_linux.go +++ b/go-selinux/selinux_linux.go @@ -1084,7 +1084,18 @@ func chcon(fpath string, label string, recurse bool) error { } if !recurse { - return setFileLabel(fpath, label) + err := lSetFileLabel(fpath, label) + if err == nil { + return nil + } + if errors.Is(err, os.ErrNotExist) { + return err + } + flabel, _ := lFileLabel(fpath) + if flabel == label { + return nil + } + return err } return rchcon(fpath, label)