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