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