From aee58d52ce616fc1d74c15fec01e751e9c2c1dd5 Mon Sep 17 00:00:00 2001
From: Thomas Petazzoni <thomas.petazzoni@bootlin.com>
Date: Sat, 18 Jul 2020 08:01:54 -0500
Subject: [PATCH] build: add support for SELinux to include/image.mk

This allows the build process to prepare a squashfs filesystem for use
with SELinux.

Signed-off-by: Thomas Petazzoni <thomas.petazzoni@bootlin.com>
[rebase, add commit message]
Signed-off-by: W. Michael Petullo <mike@flyn.org>
---
 config/Config-build.in | 10 ++++++++++
 include/image.mk       | 19 ++++++++++++++++++-
 2 files changed, 28 insertions(+), 1 deletion(-)

diff --git a/config/Config-build.in b/config/Config-build.in
index 499f84690f5..fc94f4d45e0 100644
--- a/config/Config-build.in
+++ b/config/Config-build.in
@@ -328,4 +328,14 @@ menu "Global build settings"
 			bool "Full"
 	endchoice
 
+	config TARGET_ROOTFS_SECURITY_LABELS
+		bool "Enable rootfs security labels"
+		select KERNEL_SQUASHFS_XATTR
+		select KERNEL_EXT4_FS_SECURITY
+		select KERNEL_F2FS_FS_SECURITY
+		select KERNEL_UBIFS_FS_SECURITY
+		select KERNEL_JFFS2_FS_SECURITY
+		select PACKAGE_refpolicy
+		help
+		  This option enables the usage of SELinux labels
 endmenu
diff --git a/include/image.mk b/include/image.mk
index e8c2cf7100d..3a12db36765 100644
--- a/include/image.mk
+++ b/include/image.mk
@@ -234,13 +234,30 @@ endef
 $(eval $(foreach S,$(JFFS2_BLOCKSIZE),$(call Image/mkfs/jffs2/template,$(S))))
 $(eval $(foreach S,$(NAND_BLOCKSIZE),$(call Image/mkfs/jffs2-nand/template,$(S))))
 
-define Image/mkfs/squashfs
+define Image/mkfs/squashfs-common
 	$(STAGING_DIR_HOST)/bin/mksquashfs4 $(call mkfs_target_dir,$(1)) $@ \
 		-nopad -noappend -root-owned \
 		-comp $(SQUASHFSCOMP) $(SQUASHFSOPT) \
 		-processors 1
 endef
 
+ifeq ($(CONFIG_TARGET_ROOTFS_SECURITY_LABELS),y)
+define Image/mkfs/squashfs
+	echo "LD_LIBRARY_PATH=\$$LD_LIBRARY_PATH:$(STAGING_DIR_HOSTPKG)/lib" \
+	     "$(STAGING_DIR_HOSTPKG)/sbin/setfiles -r" \
+	     "$(call mkfs_target_dir,$(1))" \
+	     "$(call mkfs_target_dir,$(1))/etc/selinux/targeted/contexts/files/file_contexts " \
+	     "$(call mkfs_target_dir,$(1))" > $@.fakeroot-script
+	echo "$(Image/mkfs/squashfs-common)" >> $@.fakeroot-script
+	chmod +x $@.fakeroot-script
+	$(STAGING_DIR_HOST)/bin/fakeroot $@.fakeroot-script
+endef
+else
+define Image/mkfs/squashfs
+	$(call Image/mkfs/squashfs-common,$(1))
+endef
+endif
+
 # $(1): board name
 # $(2): rootfs type
 # $(3): kernel image
-- 
GitLab