From a5f987841607bebcf084c1803018948b27013116 Mon Sep 17 00:00:00 2001 From: Daniel J Walsh Date: Thu, 30 Jun 2022 07:42:21 -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 | 16 ++++++++++++++++ go-selinux/selinux_linux.go | 13 ++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/go-selinux/rchcon.go b/go-selinux/rchcon.go index feb739d..4de8db7 100644 --- a/go-selinux/rchcon.go +++ b/go-selinux/rchcon.go @@ -1,3 +1,4 @@ +//go:build linux && go1.16 // +build linux,go1.16 package selinux @@ -11,7 +12,22 @@ 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 { + if label == currentLabel { + slowMode = true + } + } return pwalkdir.Walk(fpath, func(p string, _ fs.DirEntry, _ error) error { + if slowMode { + if currentLabel, err := lFileLabel(p); err == nil { + if 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 ee602ab..230dcf4 100644 --- a/go-selinux/selinux_linux.go +++ b/go-selinux/selinux_linux.go @@ -1102,7 +1102,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)