meta-selinux/classes/selinux-image.bbclass
Sasi Kumar Maddineni 9a913243ff selinux-image: Preserve SELinux contexts in tarballs
Tarball images were created without SELinux context information,
causing loss of security labels during extraction while working with
features like:ostree. This breaks SELinux policy enforcement and requires
relabeling after deployment, adding runtime overhead.

Append "--selinux" to IMAGE_CMD_TAR to include SELinux file contexts
when generating tarball images. This ensures security labels are
preserved across image creation and deployment.

Signed-off-by: Sasi Kumar Maddineni <quic_sasikuma@quicinc.com>
Signed-off-by: Yi Zhao <yi.zhao@windriver.com>
2025-11-28 11:47:08 +08:00

32 lines
1.3 KiB
Plaintext

selinux_set_labels() {
if [ -f ${IMAGE_ROOTFS}/${sysconfdir}/selinux/config ]; then
POL_TYPE=$(sed -n -e "s&^SELINUXTYPE[[:space:]]*=[[:space:]]*\([0-9A-Za-z_]\+\)&\1&p" ${IMAGE_ROOTFS}/${sysconfdir}/selinux/config)
if ! setfiles -m -r ${IMAGE_ROOTFS} ${IMAGE_ROOTFS}/${sysconfdir}/selinux/${POL_TYPE}/contexts/files/file_contexts ${IMAGE_ROOTFS}
then
bbwarn "Failed to set security contexts. Restoring security contexts will run on first boot."
echo "# first boot relabelling" > ${IMAGE_ROOTFS}/.autorelabel
fi
fi
}
# The selinux_set_labels function should run as late as possible. Append
# it to IMAGE_PREPROCESS_COMMAND in RecipePreFinalise event handler,
# this ensures it is the last function in IMAGE_PREPROCESS_COMMAND.
python selinux_setlabels_handler() {
if not d or 'selinux' not in d.getVar('DISTRO_FEATURES').split():
return
if d.getVar('FIRST_BOOT_RELABEL') == '1':
return
d.appendVar('IMAGE_PREPROCESS_COMMAND', ' selinux_set_labels; ')
d.appendVarFlag('do_image', 'depends', ' policycoreutils-native:do_populate_sysroot')
}
addhandler selinux_setlabels_handler
selinux_setlabels_handler[eventmask] = "bb.event.RecipePreFinalise"
IMAGE_CMD_TAR:append = " --selinux"
inherit core-image