1#!/bin/sh
2# $FreeBSD$
3
4sysctl security.mac.portacl >/dev/null 2>&1
5if [ $? -ne 0 ]; then
6	echo "1..1"
7	echo "not ok 1 # MAC_PORTACL is unavailable."
8	exit 0
9fi
10
11ntest=1
12
13check_bind() {
14	idtype=${1}
15	name=${2}
16	proto=${3}
17	port=${4}
18
19	[ "${proto}" = "udp" ] && udpflag="-u"
20
21	out=`(
22		case "${idtype}" in
23		uid|gid)
24			( echo -n | su -m ${name} -c "nc ${udpflag} -o -l 127.0.0.1 $port" 2>&1 ) &
25			;;
26		jail)
27			kill $$
28			;;
29		*)
30			kill $$
31		esac
32		sleep 0.3
33		echo | nc ${udpflag} -o 127.0.0.1 $port >/dev/null 2>&1
34		wait
35	)`
36	case "${out}" in
37	"nc: Permission denied"*|"nc: Operation not permitted"*)
38		echo fl
39		;;
40	"")
41		echo ok
42		;;
43	*)
44		echo ${out}
45		;;
46	esac
47}
48
49bind_test() {
50	expect_without_rule=${1}
51	expect_with_rule=${2}
52	idtype=${3}
53	name=${4}
54	proto=${5}
55	port=${6}
56
57	sysctl security.mac.portacl.rules= >/dev/null
58	out=`check_bind ${idtype} ${name} ${proto} ${port}`
59	if [ "${out}" = "${expect_without_rule}" ]; then
60		echo "ok ${ntest}"
61	elif [ "${out}" = "ok" -o "${out}" = "fl" ]; then
62		echo "not ok ${ntest}"
63	else
64		echo "not ok ${ntest} # ${out}"
65	fi
66	ntest=$((ntest+1))
67
68	if [ "${idtype}" = "uid" ]; then
69		idstr=`id -u ${name}`
70	elif [ "${idtype}" = "gid" ]; then
71		idstr=`id -g ${name}`
72	else
73		idstr=${name}
74	fi
75	sysctl security.mac.portacl.rules=${idtype}:${idstr}:${proto}:${port} >/dev/null
76	out=`check_bind ${idtype} ${name} ${proto} ${port}`
77	if [ "${out}" = "${expect_with_rule}" ]; then
78		echo "ok ${ntest}"
79	elif [ "${out}" = "ok" -o "${out}" = "fl" ]; then
80		echo "not ok ${ntest}"
81	else
82		echo "not ok ${ntest} # ${out}"
83	fi
84	ntest=$((ntest+1))
85
86	sysctl security.mac.portacl.rules= >/dev/null
87}
88
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}
98