1#	$OpenBSD: dynamic-forward.sh,v 1.17 2024/03/08 11:34:10 dtucker Exp $
2#	Placed in the Public Domain.
3
4tid="dynamic forwarding"
5
6FWDPORT=`expr $PORT + 1`
7CTL=$OBJ/ctl-sock
8cp $OBJ/ssh_config $OBJ/ssh_config.orig
9proxycmd="nc -x 127.0.0.1:$FWDPORT -X"
10trace "will use ProxyCommand $proxycmd"
11
12start_ssh() {
13	direction="$1"
14	arg="$2"
15	n=0
16	error="1"
17	# Use a multiplexed ssh so we can control its lifecycle.
18	trace "start dynamic -$direction forwarding, fork to background"
19	(cat $OBJ/ssh_config.orig ; echo "$arg") > $OBJ/ssh_config
20	${REAL_SSH} -vvvnNfF $OBJ/ssh_config -E$TEST_SSH_LOGFILE \
21	    -$direction $FWDPORT -oExitOnForwardFailure=yes \
22	    -oControlMaster=yes -oControlPath=$CTL somehost
23	r=$?
24	test $r -eq 0 || fatal "failed to start dynamic forwarding $r"
25	if ! ${REAL_SSH} -qF$OBJ/ssh_config -O check \
26	     -oControlPath=$CTL somehost >/dev/null 2>&1 ; then
27		fatal "forwarding ssh process unresponsive"
28	fi
29}
30
31stop_ssh() {
32	test -S $CTL || return
33	if ! ${REAL_SSH} -qF$OBJ/ssh_config -O exit \
34	     -oControlPath=$CTL >/dev/null somehost >/dev/null ; then
35		fatal "forwarding ssh process did not respond to close"
36	fi
37	n=0
38	while [ "$n" -lt 20 ] ; do
39		test -S $CTL || break
40		sleep 1
41		n=`expr $n + 1`
42	done
43	if test -S $CTL ; then
44		fatal "forwarding ssh process did not exit"
45	fi
46}
47
48check_socks() {
49	direction=$1
50	expect_success=$2
51	for s in 4 5; do
52	    for h in 127.0.0.1 localhost; do
53		trace "testing ssh socks version $s host $h (-$direction)"
54		${REAL_SSH} -q -F $OBJ/ssh_config -o \
55		   "ProxyCommand ${TEST_SHELL} -c '${proxycmd}${s} $h $PORT 2>/dev/null'" \
56		   somehost cat ${DATA} > ${COPY}
57		r=$?
58		if [ "x$expect_success" = "xY" ] ; then
59			if [ $r -ne 0 ] ; then
60				fail "ssh failed with exit status $r"
61			fi
62			test -f ${COPY}	 || fail "failed copy ${DATA}"
63			cmp ${DATA} ${COPY} || fail "corrupted copy of ${DATA}"
64		elif [ $r -eq 0 ] ; then
65			fail "ssh unexpectedly succeeded"
66		fi
67	    done
68	done
69}
70
71start_sshd
72trap "stop_ssh" EXIT
73
74for d in D R; do
75	verbose "test -$d forwarding"
76	start_ssh $d
77	check_socks $d Y
78	stop_ssh
79	test "x$d" = "xR" || continue
80	
81	# Test PermitRemoteOpen
82	verbose "PermitRemoteOpen=any"
83	start_ssh $d PermitRemoteOpen=any
84	check_socks $d Y
85	stop_ssh
86
87	verbose "PermitRemoteOpen=none"
88	start_ssh $d PermitRemoteOpen=none
89	check_socks $d N
90	stop_ssh
91
92	verbose "PermitRemoteOpen=explicit"
93	start_ssh $d \
94	    PermitRemoteOpen="127.0.0.1:$PORT [::1]:$PORT localhost:$PORT"
95	check_socks $d Y
96	stop_ssh
97
98	verbose "PermitRemoteOpen=disallowed"
99	start_ssh $d \
100	    PermitRemoteOpen="127.0.0.1:1 [::1]:1 localhost:1"
101	check_socks $d N
102	stop_ssh
103done
104