Prelabel the init binary with SELinux context.

This change uses the setfiles tool to set an SELinux
context on the init binary when the OS image is built.

BUG=b:25408463
TEST=I built the OS, installed it, and ran ls -Z /sbin/init
CQ-DEPEND=CL:*249719,CL:329413

Change-Id: I9e0748f2e2292c1b91c15a2929f5eb482dc18e9f
Reviewed-on: https://chromium-review.googlesource.com/329184
Commit-Ready: Ricky Zhou <rickyz@chromium.org>
Tested-by: Greg Kerr <kerrnel@chromium.org>
Reviewed-by: Ricky Zhou <rickyz@chromium.org>
Reviewed-by: Mike Frysinger <vapier@chromium.org>
diff --git a/build_library/base_image_util.sh b/build_library/base_image_util.sh
index 79f4b63..42a773f 100755
--- a/build_library/base_image_util.sh
+++ b/build_library/base_image_util.sh
@@ -312,6 +312,20 @@
     create_dev_install_lists "${root_fs_dir}"
   fi
 
+  # Restore the extended attributes of necessary files.
+  local selinux_config="${BOARD_ROOT}/etc/selinux/config"
+  if [[ -e "${selinux_config}" ]]; then
+    local selinux_type="$(source "${selinux_config}" && echo "${SELINUXTYPE}")"
+    local file_contexts="${BOARD_ROOT}/etc/selinux/${selinux_type}/contexts/files/file_contexts"
+    # If the selinux_config file exists, file_contexts must also.
+    if ! [[ -e "${file_contexts}" ]]; then
+      local err_msg="The SELinux config file exists at ${selinux_config}, "
+      err_msg+="but an SELinux context file not found at ${file_contexts}."
+      die_notrace "${err_msg}"
+    fi
+    sudo /sbin/setfiles -r "${root_fs_dir}" "${file_contexts}" "${root_fs_dir}"
+  fi
+
   # Zero rootfs free space to make it more compressible so auto-update
   # payloads become smaller
   zero_free_space "${root_fs_dir}"