1#!/bin/bash
2# SPDX-License-Identifier: GPL-2.0
3
4set -e
5set -u
6set -o pipefail
7
8IMA_POLICY_FILE="/sys/kernel/security/ima/policy"
9TEST_BINARY="/bin/true"
10VERBOSE="${SELFTESTS_VERBOSE:=0}"
11LOG_FILE="$(mktemp /tmp/ima_setup.XXXX.log)"
12
13usage()
14{
15	echo "Usage: $0 <setup|cleanup|run> <existing_tmp_dir>"
16	exit 1
17}
18
19ensure_mount_securityfs()
20{
21	local securityfs_dir=$(grep "securityfs" /proc/mounts | awk '{print $2}')
22
23	if [ -z "${securityfs_dir}" ]; then
24		securityfs_dir=/sys/kernel/security
25		mount -t securityfs security "${securityfs_dir}"
26	fi
27
28	if [ ! -d "${securityfs_dir}" ]; then
29		echo "${securityfs_dir}: securityfs is not mounted" && exit 1
30	fi
31}
32
33setup()
34{
35	local tmp_dir="$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})"
39	mkdir -p ${mount_dir}
40
41	dd if=/dev/zero of="${mount_img}" bs=1M count=10
42
43	losetup -f "${mount_img}"
44	local loop_device=$(losetup -a | grep ${mount_img:?} | cut -d ":" -f1)
45
46	mkfs.ext2 "${loop_device:?}"
47	mount "${loop_device}" "${mount_dir}"
48
49	cp "${TEST_BINARY}" "${mount_dir}"
50	local mount_uuid="$(blkid ${loop_device} | sed 's/.*UUID="\([^"]*\)".*/\1/')"
51
52	ensure_mount_securityfs
53	echo "measure func=BPRM_CHECK fsuuid=${mount_uuid}" > ${IMA_POLICY_FILE}
54}
55
56cleanup() {
57	local tmp_dir="$1"
58	local mount_img="${tmp_dir}/test.img"
59	local mount_dir="${tmp_dir}/mnt"
60
61	local loop_devices=$(losetup -a | grep ${mount_img:?} | cut -d ":" -f1)
62
63	for loop_dev in "${loop_devices}"; do
64		losetup -d $loop_dev
65	done
66
67	umount ${mount_dir}
68	rm -rf ${tmp_dir}
69}
70
71run()
72{
73	local tmp_dir="$1"
74	local mount_dir="${tmp_dir}/mnt"
75	local copied_bin_path="${mount_dir}/$(basename ${TEST_BINARY})"
76
77	exec "${copied_bin_path}"
78}
79
80catch()
81{
82	local exit_code="$1"
83	local log_file="$2"
84
85	if [[ "${exit_code}" -ne 0 ]]; then
86		cat "${log_file}" >&3
87	fi
88
89	rm -f "${log_file}"
90	exit ${exit_code}
91}
92
93main()
94{
95	[[ $# -ne 2 ]] && usage
96
97	local action="$1"
98	local tmp_dir="$2"
99
100	[[ ! -d "${tmp_dir}" ]] && echo "Directory ${tmp_dir} doesn't exist" && exit 1
101
102	if [[ "${action}" == "setup" ]]; then
103		setup "${tmp_dir}"
104	elif [[ "${action}" == "cleanup" ]]; then
105		cleanup "${tmp_dir}"
106	elif [[ "${action}" == "run" ]]; then
107		run "${tmp_dir}"
108	else
109		echo "Unknown action: ${action}"
110		exit 1
111	fi
112}
113
114trap 'catch "$?" "${LOG_FILE}"' EXIT
115
116if [[ "${VERBOSE}" -eq 0 ]]; then
117	# Save the stderr to 3 so that we can output back to
118	# it incase of an error.
119	exec 3>&2 1>"${LOG_FILE}" 2>&1
120fi
121
122main "$@"
123rm -f "${LOG_FILE}"
124