xref: /freebsd/tests/sys/mac/portacl/misc.sh (revision 2008043f386721d58158e37e0d7e50df8095942d)
1#!/bin/sh
2
3sysctl security.mac.portacl >/dev/null 2>&1
4if [ $? -ne 0 ]; then
5	echo "1..0 # SKIP MAC_PORTACL is unavailable."
6	exit 0
7fi
8if [ $(id -u) -ne 0 ]; then
9	echo "1..0 # SKIP testcases must be run as root"
10	exit 0
11fi
12
13ntest=1
14
15check_bind() {
16	local host idtype name proto port udpflag
17
18	host="127.0.0.1"
19	timeout=1
20
21	idtype=${1}
22	name=${2}
23	proto=${3}
24	port=${4}
25
26	[ "${proto}" = "udp" ] && udpflag="-u"
27
28	out=$(
29		case "${idtype}" in
30		uid|gid)
31			( echo -n | su -m ${name} -c "nc ${udpflag} -l -w ${timeout} $host $port" 2>&1 ) &
32			;;
33		jail)
34			kill $$
35			;;
36		*)
37			kill $$
38		esac
39		sleep 0.3
40		echo | nc ${udpflag} -w ${timeout} $host $port >/dev/null 2>&1
41		wait
42	)
43	case "${out}" in
44	"nc: Permission denied"*|"nc: Operation not permitted"*)
45		echo fl
46		;;
47	"")
48		echo ok
49		;;
50	*)
51		echo ${out}
52		;;
53	esac
54}
55
56bind_test() {
57	local expect_without_rule expect_with_rule idtype name proto port
58
59	expect_without_rule=${1}
60	expect_with_rule=${2}
61	idtype=${3}
62	name=${4}
63	proto=${5}
64	port=${6}
65
66	sysctl security.mac.portacl.rules= >/dev/null
67	out=$(check_bind ${idtype} ${name} ${proto} ${port})
68	if [ "${out}" = "${expect_without_rule}" ]; then
69		echo "ok ${ntest}"
70	elif [ "${out}" = "ok" -o "${out}" = "fl" ]; then
71		echo "not ok ${ntest} # '${out}' != '${expect_without_rule}'"
72	else
73		echo "not ok ${ntest} # unexpected output: '${out}'"
74	fi
75	: $(( ntest += 1 ))
76
77	if [ "${idtype}" = "uid" ]; then
78		idstr=$(id -u ${name})
79	elif [ "${idtype}" = "gid" ]; then
80		idstr=$(id -g ${name})
81	else
82		idstr=${name}
83	fi
84	sysctl security.mac.portacl.rules=${idtype}:${idstr}:${proto}:${port} >/dev/null
85	out=$(check_bind ${idtype} ${name} ${proto} ${port})
86	if [ "${out}" = "${expect_with_rule}" ]; then
87		echo "ok ${ntest}"
88	elif [ "${out}" = "ok" -o "${out}" = "fl" ]; then
89		echo "not ok ${ntest} # '${out}' != '${expect_with_rule}'"
90	else
91		echo "not ok ${ntest} # unexpected output: '${out}'"
92	fi
93	: $(( ntest += 1 ))
94
95	sysctl security.mac.portacl.rules= >/dev/null
96}
97
98reserved_high=$(sysctl -n net.inet.ip.portrange.reservedhigh)
99suser_exempt=$(sysctl -n security.mac.portacl.suser_exempt)
100port_high=$(sysctl -n security.mac.portacl.port_high)
101
102restore_settings() {
103	sysctl -n net.inet.ip.portrange.reservedhigh=${reserved_high} >/dev/null
104	sysctl -n security.mac.portacl.suser_exempt=${suser_exempt} >/dev/null
105	sysctl -n security.mac.portacl.port_high=${port_high} >/dev/null
106}
107