1#!/bin/sh
2# SPDX-License-Identifier: GPL-2.0-or-later
3# Copyright (c) 2017 Fujitsu Ltd.
4# Ported: Guangwen Feng <fenggw-fnst@cn.fujitsu.com>
5#
6# This is a regression test about potential uninitialized variable,
7# the test can crash the buggy kernel, and the bug has been fixed in:
8#
9#   commit 38327424b40bcebe2de92d07312c89360ac9229a
10#   Author: Dan Carpenter <dan.carpenter@oracle.com>
11#   Date:   Thu Jun 16 15:48:57 2016 +0100
12#
13#   KEYS: potential uninitialized variable
14
15TST_SETUP=setup
16TST_CLEANUP=cleanup
17TST_TESTFUNC=do_test
18TST_NEEDS_ROOT=1
19TST_NEEDS_TMPDIR=1
20TST_NEEDS_CMDS="keyctl"
21. tst_test.sh
22
23check_keyctl()
24{
25	local nosup
26	for op in $@; do
27		nosup=0
28
29		if ! keyctl 2>&1 | grep -q "keyctl $op"; then
30			nosup=1
31		fi
32
33		if [ "$op" = "request2" ]; then
34			local key=`keyctl request2 user debug:foo bar`
35			if [ $? -ne 0 ]; then
36				nosup=1
37			fi
38		fi
39
40		if [ "$op" = "unlink" ]; then
41			if ! keyctl unlink $key @s; then
42				nosup=1
43			fi
44		fi
45
46		if [ $nosup -ne 0 ]; then
47			tst_brk TCONF "keyctl operation $op not supported"
48		fi
49	done
50}
51
52setup()
53{
54	check_keyctl negate request2 show unlink
55
56	PATH_KEYSTAT="/proc/key-users"
57	PATH_KEYQUOTA="/proc/sys/kernel/keys/root_maxbytes"
58
59	if [ ! -f "$PATH_KEYSTAT" ] || [ ! -f "$PATH_KEYQUOTA" ]; then
60		tst_brk TCONF "'${PATH_KEYSTAT}' or '${PATH_KEYQUOTA}' \
61			does not exist"
62	fi
63
64	ORIG_KEYSZ=`awk -F' +|/' '/ 0:/ {print $8}' $PATH_KEYSTAT`
65	ORIG_MAXKEYSZ=`cat $PATH_KEYQUOTA`
66}
67
68cleanup()
69{
70	if [ -n "$ORIG_MAXKEYSZ" ]; then
71		echo $ORIG_MAXKEYSZ >$PATH_KEYQUOTA
72	fi
73}
74
75do_test()
76{
77	local quota_excd=0
78	local maxkeysz=$((ORIG_KEYSZ + 100))
79
80	while [ $maxkeysz -ge 0 ]
81	do
82		echo $maxkeysz >$PATH_KEYQUOTA
83
84		keyctl request2 user debug:fred negate @t >temp 2>&1
85		grep -q -E "quota exceeded" temp
86		if [ $? -eq 0 ]; then
87			quota_excd=1
88			break
89		fi
90
91		local key=`keyctl show | awk '/debug:fred/ {print $1}'`
92		if [ -z "$key" ]; then
93			key=`keyctl show | \
94				awk -F ':' '/inaccessible/ {print $1}'`
95		fi
96
97		if [ -n "$key" ]; then
98			keyctl unlink $key @s >/dev/null
99			tst_sleep 50ms
100		fi
101
102		maxkeysz=$((maxkeysz - 4))
103	done
104
105	if [ $quota_excd -eq 0 ]; then
106		tst_res TWARN "Failed to trigger the quota excess"
107	fi
108
109	tst_res TPASS "Bug not reproduced"
110}
111
112tst_run
113