1#!/bin/sh
2# SPDX-License-Identifier: GPL-2.0-or-later
3# Copyright (c) 2009 IBM Corporation
4# Copyright (c) 2018 Petr Vorel <pvorel@suse.cz>
5# Author: Mimi Zohar <zohar@linux.ibm.com>
6#
7# Test replacing the default integrity measurement policy.
8
9TST_SETUP="setup"
10TST_CNT=2
11
12. ima_setup.sh
13
14check_policy_writable()
15{
16	local err="IMA policy already loaded and kernel not configured to enable multiple writes to it (need CONFIG_IMA_WRITE_POLICY=y)"
17
18	[ -f $IMA_POLICY ] || tst_brk TCONF "$err"
19	# CONFIG_IMA_READ_POLICY
20	echo "" 2> log > $IMA_POLICY
21	grep -q "Device or resource busy" log && tst_brk TCONF "$err"
22}
23
24setup()
25{
26	IMA_POLICY="$IMA_DIR/policy"
27	check_policy_writable
28
29	VALID_POLICY="$TST_DATAROOT/measure.policy"
30	[ -f $VALID_POLICY ] || tst_brk TCONF "missing $VALID_POLICY"
31
32	INVALID_POLICY="$TST_DATAROOT/measure.policy-invalid"
33	[ -f $INVALID_POLICY ] || tst_brk TCONF "missing $INVALID_POLICY"
34}
35
36load_policy()
37{
38	local ret
39
40	exec 2>/dev/null 4>$IMA_POLICY
41	[ $? -eq 0 ] || exit 1
42
43	cat $1 >&4 2> /dev/null
44	ret=$?
45	exec 4>&-
46
47	[ $ret -eq 0 ] && \
48		tst_res TINFO "IMA policy updated, please reboot after testing to restore settings"
49
50	return $ret
51}
52
53test1()
54{
55	tst_res TINFO "verify that invalid policy isn't loaded"
56
57	local p1
58
59	check_policy_writable
60	load_policy $INVALID_POLICY & p1=$!
61	wait "$p1"
62	if [ $? -ne 0 ]; then
63		tst_res TPASS "didn't load invalid policy"
64	else
65		tst_res TFAIL "loaded invalid policy"
66	fi
67}
68
69test2()
70{
71	tst_res TINFO "verify that policy file is not opened concurrently and able to loaded multiple times"
72
73	local p1 p2 rc1 rc2
74
75	check_policy_writable
76	load_policy $VALID_POLICY & p1=$!
77	load_policy $VALID_POLICY & p2=$!
78	wait "$p1"; rc1=$?
79	wait "$p2"; rc2=$?
80	if [ $rc1 -eq 0 ] && [ $rc2 -eq 0 ]; then
81		tst_res TFAIL "policy opened concurrently"
82	elif [ $rc1 -eq 0 ] || [ $rc2 -eq 0 ]; then
83		tst_res TPASS "policy was loaded just by one process and able to loaded multiple times"
84	else
85		tst_res TFAIL "problem loading or extending policy (may require policy to be signed)"
86	fi
87}
88
89tst_run
90