2 # SPDX-License-Identifier: GPL-2.0
8 IMA_POLICY_FILE="/sys/kernel/security/ima/policy"
9 TEST_BINARY="/bin/true"
10 VERBOSE="${SELFTESTS_VERBOSE:=0}"
11 LOG_FILE="$(mktemp /tmp/ima_setup.XXXX.log)"
15 echo "Usage: $0 <setup|cleanup|run|modify-bin|restore-bin|load-policy> <existing_tmp_dir>"
19 ensure_mount_securityfs()
21 local securityfs_dir=$(grep "securityfs" /proc/mounts | awk '{print $2}')
23 if [ -z "${securityfs_dir}" ]; then
24 securityfs_dir=/sys/kernel/security
25 mount -t securityfs security "${securityfs_dir}"
28 if [ ! -d "${securityfs_dir}" ]; then
29 echo "${securityfs_dir}: securityfs is not mounted" && exit 1
36 local mount_img="${tmp_dir}/test.img"
37 local mount_dir="${tmp_dir}/mnt"
38 local copied_bin_path="${mount_dir}/$(basename ${TEST_BINARY})"
41 dd if=/dev/zero of="${mount_img}" bs=1M count=10
43 losetup -f "${mount_img}"
44 local loop_device=$(losetup -a | grep ${mount_img:?} | cut -d ":" -f1)
46 mkfs.ext2 "${loop_device:?}"
47 mount "${loop_device}" "${mount_dir}"
49 cp "${TEST_BINARY}" "${mount_dir}"
50 local mount_uuid="$(blkid ${loop_device} | sed 's/.*UUID="\([^"]*\)".*/\1/')"
52 ensure_mount_securityfs
53 echo "measure func=BPRM_CHECK fsuuid=${mount_uuid}" > ${IMA_POLICY_FILE}
54 echo "measure func=BPRM_CHECK fsuuid=${mount_uuid}" > ${mount_dir}/policy_test
59 local mount_img="${tmp_dir}/test.img"
60 local mount_dir="${tmp_dir}/mnt"
62 local loop_devices=$(losetup -a | grep ${mount_img:?} | cut -d ":" -f1)
64 for loop_dev in "${loop_devices}"; do
75 local mount_dir="${tmp_dir}/mnt"
76 local copied_bin_path="${mount_dir}/$(basename ${TEST_BINARY})"
78 exec "${copied_bin_path}"
84 local mount_dir="${tmp_dir}/mnt"
85 local copied_bin_path="${mount_dir}/$(basename ${TEST_BINARY})"
87 echo "mod" >> "${copied_bin_path}"
93 local mount_dir="${tmp_dir}/mnt"
94 local copied_bin_path="${mount_dir}/$(basename ${TEST_BINARY})"
96 truncate -s -4 "${copied_bin_path}"
102 local mount_dir="${tmp_dir}/mnt"
104 echo ${mount_dir}/policy_test > ${IMA_POLICY_FILE} 2> /dev/null
112 if [[ "${exit_code}" -ne 0 ]]; then
113 cat "${log_file}" >&3
122 [[ $# -ne 2 ]] && usage
127 [[ ! -d "${tmp_dir}" ]] && echo "Directory ${tmp_dir} doesn't exist" && exit 1
129 if [[ "${action}" == "setup" ]]; then
131 elif [[ "${action}" == "cleanup" ]]; then
133 elif [[ "${action}" == "run" ]]; then
135 elif [[ "${action}" == "modify-bin" ]]; then
136 modify_bin "${tmp_dir}"
137 elif [[ "${action}" == "restore-bin" ]]; then
138 restore_bin "${tmp_dir}"
139 elif [[ "${action}" == "load-policy" ]]; then
140 load_policy "${tmp_dir}"
142 echo "Unknown action: ${action}"
147 trap 'catch "$?" "${LOG_FILE}"' EXIT
149 if [[ "${VERBOSE}" -eq 0 ]]; then
150 # Save the stderr to 3 so that we can output back to
151 # it incase of an error.
152 exec 3>&2 1>"${LOG_FILE}" 2>&1