From 25a435e90844ea98fe5eb7bef22c1aecf3a9c033 Mon Sep 17 00:00:00 2001
From: Panu Matilainen <pmatilai@redhat.com>
Date: Mon, 14 Feb 2022 14:29:33 +0200
Subject: [PATCH] Set file metadata via fd-based ops for everything but
 symlinks

Regular file ops are fd-based already, for the rest we need to open them
manually. Files with temporary suffix must never be followed, for
directories (and pre-existing FA_TOUCHed files) use the rpm symlink
"root or target owner allowed" rule wrt following.

This mostly fixes CVE-2021-35938, but as we're not yet using dirfd-based
operatiosn for everything there are corner cases left undone. And then
there's the plugin API which needs updating for all this.
---
 lib/fsm.c | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/lib/fsm.c b/lib/fsm.c
index 913e9de..6f781c6 100644
--- a/lib/fsm.c
+++ b/lib/fsm.c
@@ -1133,6 +1133,14 @@ int rpmPackageFilesInstall(rpmts ts, rpmte te, rpmfiles files,
                     rc = RPMERR_UNKNOWN_FILETYPE;
             }
 
+	    if (!rc && fd == -1 && !S_ISLNK(fp->sb.st_mode)) {
+		/* Only follow safe symlinks, and never on temporary files */
+		fd = fsmOpenat(di.dirfd, fp->fpath,
+				fp->suffix ? AT_SYMLINK_NOFOLLOW : 0);
+		if (fd < 0)
+		    rc = RPMERR_OPEN_FAILED;
+	    }
+
 	    if (fd != firstlinkfile)
 		fsmClose(&fd);
 	}
-- 
1.8.3.1

