xref: /freebsd/crypto/openssh/regress/test-exec.sh (revision bb5c77e9d281d6def6835d48249898764bc6a5fe)
1#	$OpenBSD: test-exec.sh,v 1.139 2025/12/22 01:31:07 djm Exp $
2#	Placed in the Public Domain.
3
4#SUDO=sudo
5
6if [ ! -z "$TEST_SSH_ELAPSED_TIMES" ]; then
7	STARTTIME=`date '+%s'`
8fi
9
10if [ ! -z "$TEST_SSH_PORT" ]; then
11	PORT="$TEST_SSH_PORT"
12else
13	PORT=4242
14fi
15
16OBJ=$1
17if [ "x$OBJ" = "x" ]; then
18	echo '$OBJ not defined'
19	exit 2
20fi
21if [ ! -d $OBJ ]; then
22	echo "not a directory: $OBJ"
23	exit 2
24fi
25SCRIPT=$2
26if [ "x$SCRIPT" = "x" ]; then
27	echo '$SCRIPT not defined'
28	exit 2
29fi
30if [ ! -f $SCRIPT ]; then
31	echo "not a file: $SCRIPT"
32	exit 2
33fi
34if $TEST_SHELL -n $SCRIPT; then
35	true
36else
37	echo "syntax error in $SCRIPT"
38	exit 2
39fi
40unset SSH_AUTH_SOCK
41
42# Portable-specific settings.
43
44if [ -x /usr/ucb/whoami ]; then
45	USER=`/usr/ucb/whoami`
46elif whoami >/dev/null 2>&1; then
47	USER=`whoami`
48elif logname >/dev/null 2>&1; then
49	USER=`logname`
50else
51	USER=`id -un`
52fi
53if test -z "$LOGNAME"; then
54	LOGNAME="${USER}"
55	export LOGNAME
56fi
57
58# Unbreak GNU head(1)
59_POSIX2_VERSION=199209
60export _POSIX2_VERSION
61
62case `uname -s 2>/dev/null` in
63OSF1*)
64	BIN_SH=xpg4
65	export BIN_SH
66	;;
67CYGWIN*)
68	os=cygwin
69	;;
70esac
71
72# If configure tells us to use a different egrep, create a wrapper function
73# to call it.  This means we don't need to change all the tests that depend
74# on a good implementation.
75if test "x${EGREP}" != "x"; then
76	egrep ()
77{
78	 ${EGREP} "$@"
79}
80fi
81
82# Likewise with awk.
83if test "x${AWK}" != "x" && test "x${AWK}" != "xawk"; then
84	awk ()
85{
86	${AWK} "$@"
87}
88fi
89
90SRC=`dirname ${SCRIPT}`
91
92# defaults
93SSH=ssh
94SSHD=sshd
95SSHAGENT=ssh-agent
96SSHADD=ssh-add
97SSHKEYGEN=ssh-keygen
98SSHKEYSCAN=ssh-keyscan
99SFTP=sftp
100SFTPSERVER=/usr/libexec/openssh/sftp-server
101SSHD_SESSION=/usr/libexec/sshd-session
102SSHD_AUTH=/usr/libexec/sshd-auth
103SCP=scp
104
105# Set by make_tmpdir() on demand (below).
106SSH_REGRESS_TMP=
107
108# Interop testing
109PLINK=/usr/local/bin/plink
110PUTTYGEN=/usr/local/bin/puttygen
111CONCH=/usr/local/bin/conch
112DROPBEAR=/usr/local/sbin/dropbear
113DBCLIENT=/usr/local/bin/dbclient
114DROPBEARKEY=/usr/local/bin/dropbearkey
115DROPBEARCONVERT=/usr/local/bin/dropbearconvert
116
117# So we can override this in Portable.
118TEST_SHELL="${TEST_SHELL:-/bin/sh}"
119
120# Tools used by multiple tests
121NC=$OBJ/netcat
122# Always use the one configure tells us to, even if that's empty.
123#OPENSSL_BIN="${OPENSSL_BIN:-openssl}"
124
125if [ "x$TEST_SSH_SSH" != "x" ]; then
126	SSH="${TEST_SSH_SSH}"
127fi
128if [ "x$TEST_SSH_SSHD_SESSION" != "x" ]; then
129	SSHD_SESSION="${TEST_SSH_SSHD_SESSION}"
130fi
131if [ "x$TEST_SSH_SSHD_AUTH" != "x" ]; then
132	SSHD_AUTH="${TEST_SSH_SSHD_AUTH}"
133fi
134if [ "x$TEST_SSH_SSHD" != "x" ]; then
135	SSHD="${TEST_SSH_SSHD}"
136fi
137if [ "x$TEST_SSH_SSHAGENT" != "x" ]; then
138	SSHAGENT="${TEST_SSH_SSHAGENT}"
139fi
140if [ "x$TEST_SSH_SSHADD" != "x" ]; then
141	SSHADD="${TEST_SSH_SSHADD}"
142fi
143if [ "x$TEST_SSH_SSHKEYGEN" != "x" ]; then
144	SSHKEYGEN="${TEST_SSH_SSHKEYGEN}"
145fi
146if [ "x$TEST_SSH_SSHKEYSCAN" != "x" ]; then
147	SSHKEYSCAN="${TEST_SSH_SSHKEYSCAN}"
148fi
149if [ "x$TEST_SSH_SFTP" != "x" ]; then
150	SFTP="${TEST_SSH_SFTP}"
151fi
152if [ "x$TEST_SSH_SFTPSERVER" != "x" ]; then
153	SFTPSERVER="${TEST_SSH_SFTPSERVER}"
154fi
155if [ "x$TEST_SSH_SCP" != "x" ]; then
156	SCP="${TEST_SSH_SCP}"
157fi
158if [ "x$TEST_SSH_PLINK" != "x" ]; then
159	PLINK="${TEST_SSH_PLINK}"
160fi
161if [ "x$TEST_SSH_PUTTYGEN" != "x" ]; then
162	PUTTYGEN="${TEST_SSH_PUTTYGEN}"
163fi
164if [ "x$TEST_SSH_CONCH" != "x" ]; then
165	CONCH="${TEST_SSH_CONCH}"
166fi
167if [ "x$TEST_SSH_DROPBEAR" != "x" ]; then
168	DROPBEAR="${TEST_SSH_DROPBEAR}"
169fi
170if [ "x$TEST_SSH_DBCLIENT" != "x" ]; then
171	DBCLIENT="${TEST_SSH_DBCLIENT}"
172fi
173if [ "x$TEST_SSH_DROPBEARKEY" != "x" ]; then
174	DROPBEARKEY="${TEST_SSH_DROPBEARKEY}"
175fi
176if [ "x$TEST_SSH_DROPBEARCONVERT" != "x" ]; then
177	DROPBEARCONVERT="${TEST_SSH_DROPBEARCONVERT}"
178fi
179if [ "x$TEST_SSH_TMUX" != "x" ]; then
180	TMUX="${TEST_SSH_TMUX}"
181fi
182if [ "x$TEST_SSH_PKCS11_HELPER" != "x" ]; then
183	SSH_PKCS11_HELPER="${TEST_SSH_PKCS11_HELPER}"
184fi
185if [ "x$TEST_SSH_SK_HELPER" != "x" ]; then
186	SSH_SK_HELPER="${TEST_SSH_SK_HELPER}"
187fi
188if [ "x$TEST_SSH_OPENSSL" != "x" ]; then
189	OPENSSL_BIN="${TEST_SSH_OPENSSL}"
190fi
191
192# Path to sshd must be absolute for rexec
193case "$SSHD" in
194/*) ;;
195*) SSHD=`which $SSHD` ;;
196esac
197
198case "$SSH" in
199/*) ;;
200*) SSH=`which $SSH` ;;
201esac
202
203case "$SSHAGENT" in
204/*) ;;
205*) SSHAGENT=`which $SSHAGENT` ;;
206esac
207
208# Record the actual binaries used.
209SSH_BIN=${SSH}
210SSHD_BIN=${SSHD}
211SSHAGENT_BIN=${SSHAGENT}
212SSHADD_BIN=${SSHADD}
213SSHKEYGEN_BIN=${SSHKEYGEN}
214SSHKEYSCAN_BIN=${SSHKEYSCAN}
215SFTP_BIN=${SFTP}
216SFTPSERVER_BIN=${SFTPSERVER}
217SCP_BIN=${SCP}
218
219if [ "x$USE_VALGRIND" != "x" ]; then
220	rm -rf $OBJ/valgrind-out $OBJ/valgrind-vgdb
221	mkdir -p $OBJ/valgrind-out $OBJ/valgrind-vgdb
222	# When using sudo ensure low-priv tests can write pipes and logs.
223	if [ "x$SUDO" != "x" ]; then
224		chmod 777 $OBJ/valgrind-out $OBJ/valgrind-vgdb
225	fi
226	VG_TEST=`basename $SCRIPT .sh`
227
228	# Some tests are difficult to fix.
229	case "$VG_TEST" in
230	reexec)
231		VG_SKIP=1 ;;
232	sftp-chroot)
233		if [ "x${SUDO}" != "x" ]; then
234			VG_SKIP=1
235		fi ;;
236	esac
237
238	if [ x"$VG_SKIP" = "x" ]; then
239		VG_LEAK="--leak-check=no"
240		if [ x"$VALGRIND_CHECK_LEAKS" != "x" ]; then
241			VG_LEAK="--leak-check=full"
242		fi
243		VG_IGNORE="/bin/*,/sbin/*,/usr/*,/var/*"
244		VG_LOG="$OBJ/valgrind-out/${VG_TEST}."
245		VG_OPTS="--track-origins=yes $VG_LEAK"
246		VG_OPTS="$VG_OPTS --trace-children=yes"
247		VG_OPTS="$VG_OPTS --trace-children-skip=${VG_IGNORE}"
248		VG_OPTS="$VG_OPTS --vgdb-prefix=$OBJ/valgrind-vgdb/"
249		VG_PATH="valgrind"
250		if [ "x$VALGRIND_PATH" != "x" ]; then
251			VG_PATH="$VALGRIND_PATH"
252		fi
253		VG="$VG_PATH $VG_OPTS"
254		SSH="$VG --log-file=${VG_LOG}ssh.%p $SSH"
255		SSHD="$VG --log-file=${VG_LOG}sshd.%p $SSHD"
256		SSHAGENT="$VG --log-file=${VG_LOG}ssh-agent.%p $SSHAGENT"
257		SSHADD="$VG --log-file=${VG_LOG}ssh-add.%p $SSHADD"
258		SSHKEYGEN="$VG --log-file=${VG_LOG}ssh-keygen.%p $SSHKEYGEN"
259		SSHKEYSCAN="$VG --log-file=${VG_LOG}ssh-keyscan.%p $SSHKEYSCAN"
260		SFTP="$VG --log-file=${VG_LOG}sftp.%p ${SFTP}"
261		SCP="$VG --log-file=${VG_LOG}scp.%p $SCP"
262		cat > $OBJ/valgrind-sftp-server.sh << EOF
263#!/bin/sh
264exec $VG --log-file=${VG_LOG}sftp-server.%p $SFTPSERVER "\$@"
265EOF
266		chmod a+rx $OBJ/valgrind-sftp-server.sh
267		SFTPSERVER="$OBJ/valgrind-sftp-server.sh"
268	fi
269fi
270
271# Logfiles.
272# SSH_LOGFILE should be the debug output of ssh(1) only
273# SSHD_LOGFILE should be the debug output of sshd(8) only
274# REGRESS_LOGFILE is the log of progress of the regress test itself.
275# TEST_SSH_LOGDIR will contain datestamped logs of all binaries run in
276# chronological order.
277if [ "x$TEST_SSH_LOGDIR" = "x" ]; then
278	TEST_SSH_LOGDIR=$OBJ/log
279	mkdir -p $TEST_SSH_LOGDIR
280fi
281if [ "x$TEST_SSH_LOGFILE" = "x" ]; then
282	TEST_SSH_LOGFILE=$OBJ/ssh.log
283fi
284if [ "x$TEST_SSHD_LOGFILE" = "x" ]; then
285	TEST_SSHD_LOGFILE=$OBJ/sshd.log
286fi
287if [ "x$TEST_REGRESS_LOGFILE" = "x" ]; then
288	TEST_REGRESS_LOGFILE=$OBJ/regress.log
289fi
290
291# If set, keep track of successful tests and skip them them if we've
292# previously completed that test.
293if [ "x$TEST_REGRESS_CACHE_DIR" != "x" ]; then
294	if [ ! -d "$TEST_REGRESS_CACHE_DIR" ]; then
295		mkdir -p "$TEST_REGRESS_CACHE_DIR"
296	fi
297	TEST="`basename $SCRIPT .sh`"
298	CACHE="${TEST_REGRESS_CACHE_DIR}/${TEST}.cache"
299	for i in ${SSH} ${SSHD} ${SSHAGENT} ${SSHADD} ${SSHKEYGEN} ${SCP} \
300	    ${SFTP} ${SFTPSERVER} ${SSHKEYSCAN}; do
301		case $i in
302		/*)	bin="$i" ;;
303		*)	bin="`which $i`" ;;
304		esac
305		if [ "$bin" -nt "$CACHE" ]; then
306			rm -f "$CACHE"
307		fi
308	done
309	if [ -f "$CACHE" ]; then
310		echo ok cached $CACHE
311		exit 0
312	fi
313fi
314
315# truncate logfiles
316>$TEST_REGRESS_LOGFILE
317
318# Create ssh and sshd wrappers with logging.  These create a datestamped
319# unique file for every invocation so that we can retain all logs from a
320# given test no matter how many times it's invoked.  It also leaves a
321# symlink with the original name for tests (and people) who look for that.
322
323# For ssh, e can't just specify "SSH=ssh -E..." because sftp and scp don't
324# handle spaces in arguments.  scp and sftp like to use -q so we remove those
325# to preserve our debug logging.  In the rare instance where -q is desirable
326# -qq is equivalent and is not removed.
327SSHLOGWRAP=$OBJ/ssh-log-wrapper.sh
328rm -f ${SSHLOGWRAP}
329cat >$SSHLOGWRAP <<EOD
330#!/bin/sh
331timestamp="\`$OBJ/timestamp\`"
332logfile="${TEST_SSH_LOGDIR}/\${timestamp}.ssh.\$\$.log"
333echo "Executing: ${SSH} \$@" log \${logfile} >>$TEST_REGRESS_LOGFILE
334echo "Executing: ${SSH} \$@" >>\${logfile}
335for i in "\$@";do shift;case "\$i" in -q):;; *) set -- "\$@" "\$i";;esac;done
336rm -f $TEST_SSH_LOGFILE
337ln -f -s \${logfile} $TEST_SSH_LOGFILE
338exec ${SSH} -E\${logfile} "\$@"
339EOD
340
341chmod a+rx $OBJ/ssh-log-wrapper.sh
342REAL_SSH="$SSH"
343REAL_SSHD="$SSHD"
344SSH="$SSHLOGWRAP"
345
346SSHDLOGWRAP=$OBJ/sshd-log-wrapper.sh
347rm -f ${SSHDLOGWRAP}
348cat >$SSHDLOGWRAP <<EOD
349#!/bin/sh
350timestamp="\`$OBJ/timestamp\`"
351logfile="${TEST_SSH_LOGDIR}/\${timestamp}.sshd.\$\$.log"
352rm -f $TEST_SSHD_LOGFILE
353touch \$logfile
354test -z "$SUDO" || chown $USER \$logfile
355ln -f -s \${logfile} $TEST_SSHD_LOGFILE
356echo "Executing: ${SSHD} \$@" log \${logfile} >>$TEST_REGRESS_LOGFILE
357echo "Executing: ${SSHD} \$@" >>\${logfile}
358exec ${SSHD} -E\${logfile} "\$@"
359EOD
360chmod a+rx $OBJ/sshd-log-wrapper.sh
361
362ssh_logfile ()
363{
364	tool="$1"
365	timestamp="`$OBJ/timestamp`"
366	logfile="${TEST_SSH_LOGDIR}/${timestamp}.$tool.$$.log"
367	echo "Logging $tool to log \${logfile}" >>$TEST_REGRESS_LOGFILE
368	echo $logfile
369}
370
371# Some test data.  We make a copy because some tests will overwrite it.
372# The tests may assume that $DATA exists and is writable and $COPY does
373# not exist.  Tests requiring larger data files can call increase_datafile_size
374# [kbytes] to ensure the file is at least that large.
375DATANAME=data
376DATA=$OBJ/${DATANAME}
377cat ${SSH_BIN} >${DATA}
378chmod u+w ${DATA}
379COPY=$OBJ/copy
380rm -f ${COPY}
381
382increase_datafile_size()
383{
384	while [ `du -k ${DATA} | cut -f1` -lt $1 ]; do
385		cat ${SSH_BIN} >>${DATA}
386	done
387}
388
389# these should be used in tests
390export SSH SSHD SSHAGENT SSHADD SSHKEYGEN SSHKEYSCAN SFTP SFTPSERVER SCP
391export SSH_PKCS11_HELPER SSH_SK_HELPER
392#echo $SSH $SSHD $SSHAGENT $SSHADD $SSHKEYGEN $SSHKEYSCAN $SFTP $SFTPSERVER $SCP
393
394# Portable specific functions
395which()
396{
397	saved_IFS="$IFS"
398	IFS=":"
399	for i in $PATH
400	do
401		if [ -x $i/$1 ]; then
402			IFS="$saved_IFS"
403			echo "$i/$1"
404			return 0
405		fi
406	done
407	IFS="$saved_IFS"
408	echo "$i/$1"
409	return 1
410}
411
412have_prog()
413{
414	which "$1" >/dev/null 2>&1
415	return $?
416}
417
418jot() {
419	awk "BEGIN { for (i = $2; i < $2 + $1; i++) { printf \"%d\n\", i } exit }"
420}
421
422if [ ! -x "`which rev`" ]; then
423rev()
424{
425	awk '{for (i=length; i>0; i--) printf "%s", substr($0, i, 1); print ""}'
426}
427fi
428
429if [ -x "/usr/xpg4/bin/id" ]; then
430id()
431{
432	/usr/xpg4/bin/id $@
433}
434fi
435
436# Check whether preprocessor symbols are defined in config.h.
437config_defined ()
438{
439	str=$1
440	while test "x$2" != "x" ; do
441		str="$str|$2"
442		shift
443	done
444	egrep "^#define.*($str)" ${BUILDDIR}/config.h >/dev/null 2>&1
445}
446
447md5 () {
448	if have_prog md5sum; then
449		md5sum
450	elif have_prog openssl; then
451		openssl md5
452	elif have_prog cksum; then
453		cksum
454	elif have_prog sum; then
455		sum
456	elif [ -x ${OPENSSL_BIN} ]; then
457		${OPENSSL_BIN} md5
458	else
459		wc -c
460	fi
461}
462
463# Some platforms don't have hostname at all, but on others uname -n doesn't
464# provide the fully qualified name we need, so in the former case we create
465# our own hostname function.
466if ! have_prog hostname; then
467	hostname() {
468		uname -n
469	}
470fi
471
472make_tmpdir ()
473{
474	SSH_REGRESS_TMP="$($OBJ/mkdtemp openssh-XXXXXXXX)" || \
475	    fatal "failed to create temporary directory"
476}
477# End of portable specific functions
478
479stop_sshd ()
480{
481	[ -z $PIDFILE ] && return
482	[ -f $PIDFILE ] || return
483	pid=`$SUDO cat $PIDFILE`
484	if [ "X$pid" = "X" ]; then
485		echo "no sshd running" 1>&2
486		return
487	elif [ $pid -lt 2 ]; then
488		echo "bad pid for sshd: $pid" 1>&2
489		return
490	fi
491	$SUDO kill $pid
492	trace "wait for sshd to exit"
493	i=0;
494	while [ -f $PIDFILE -a $i -lt 5 ]; do
495		i=`expr $i + 1`
496		sleep $i
497	done
498	if test -f $PIDFILE; then
499		if $SUDO kill -0 $pid; then
500			echo "sshd didn't exit port $PORT pid $pid" 1>&2
501		else
502			echo "sshd died without cleanup" 1>&2
503		fi
504		exit 1
505	fi
506	PIDFILE=""
507}
508
509# helper
510cleanup ()
511{
512	if [ "x$SSH_PID" != "x" ]; then
513		if [ $SSH_PID -lt 2 ]; then
514			echo bad pid for ssh: $SSH_PID
515		else
516			kill $SSH_PID
517		fi
518	fi
519	if [ "x$SSH_REGRESS_TMP" != "x" ]; then
520		rm -rf "$SSH_REGRESS_TMP"
521	fi
522	stop_sshd
523	if [ ! -z "$TEST_SSH_ELAPSED_TIMES" ]; then
524		now=`date '+%s'`
525		elapsed=$(($now - $STARTTIME))
526		echo elapsed $elapsed `basename $SCRIPT .sh`
527	fi
528}
529
530start_debug_log ()
531{
532	echo "trace: $@" >>$TEST_REGRESS_LOGFILE
533	if [ -d "$TEST_SSH_LOGDIR" ]; then
534		rm -f $TEST_SSH_LOGDIR/*
535	fi
536}
537
538save_debug_log ()
539{
540	testname=`echo $tid | tr ' ' _`
541	tarname="$OBJ/failed-$testname-logs.tar"
542
543	for logfile in $TEST_SSH_LOGDIR $TEST_REGRESS_LOGFILE \
544	    $TEST_SSH_LOGFILE $TEST_SSHD_LOGFILE; do
545		if [ ! -z "$SUDO" ]; then
546			touch $logfile
547			$SUDO chown -R $USER $logfile
548			$SUDO chmod ug+rw $logfile
549		fi
550	done
551	echo $@ >>$TEST_REGRESS_LOGFILE
552	echo $@ >>$TEST_SSH_LOGFILE
553	echo $@ >>$TEST_SSHD_LOGFILE
554	echo "Saving debug logs to $tarname" >>$TEST_REGRESS_LOGFILE
555	(cat $TEST_REGRESS_LOGFILE; echo) >>$OBJ/failed-regress.log
556	(cat $TEST_SSH_LOGFILE; echo) >>$OBJ/failed-ssh.log
557	(cat $TEST_SSHD_LOGFILE; echo) >>$OBJ/failed-sshd.log
558}
559
560trace ()
561{
562	start_debug_log $@
563	if [ "X$TEST_SSH_TRACE" = "Xyes" ]; then
564		echo "$@"
565	fi
566}
567
568verbose ()
569{
570	start_debug_log $@
571	if [ "X$TEST_SSH_QUIET" != "Xyes" ]; then
572		echo "$@"
573	fi
574}
575
576fail ()
577{
578	save_debug_log "FAIL: $@"
579	RESULT=1
580	echo "$@"
581	if test "x$TEST_SSH_FAIL_FATAL" != "x" ; then
582		cleanup
583		exit $RESULT
584	fi
585}
586
587fatal ()
588{
589	save_debug_log "FATAL: $@"
590	printf "FATAL: "
591	fail "$@"
592	cleanup
593	exit $RESULT
594}
595
596# Skip remaining tests in script.
597skip ()
598{
599	echo "SKIPPED: $@"
600	cleanup
601	exit $RESULT
602}
603
604maybe_add_scp_path_to_sshd ()
605{
606	# If we're testing a non-installed scp, add its directory to sshd's
607	# PATH so we can test it.  We don't do this for all tests as it
608	# breaks the SetEnv tests.
609	case "$SCP" in
610	/*)	PATH_WITH_SCP="`dirname $SCP`:$PATH"
611		echo "	SetEnv PATH='$PATH_WITH_SCP'" >>$OBJ/sshd_config
612		echo "	SetEnv PATH='$PATH_WITH_SCP'" >>$OBJ/sshd_proxy ;;
613	esac
614}
615
616RESULT=0
617PIDFILE=$OBJ/pidfile
618
619trap fatal 3 2
620
621# create server config
622cat << EOF > $OBJ/sshd_config
623	StrictModes		no
624	Port			$PORT
625	AddressFamily		inet
626	ListenAddress		127.0.0.1
627	#ListenAddress		::1
628	PidFile			$PIDFILE
629	AuthorizedKeysFile	$OBJ/authorized_keys_%u
630	LogLevel		DEBUG3
631	AcceptEnv		_XXX_TEST_*
632	AcceptEnv		_XXX_TEST
633	Subsystem	sftp	$SFTPSERVER
634	SshdSessionPath		$SSHD_SESSION
635	SshdAuthPath		$SSHD_AUTH
636	PerSourcePenalties	no
637EOF
638
639# This may be necessary if /usr/src and/or /usr/obj are group-writable,
640# but if you aren't careful with permissions then the unit tests could
641# be abused to locally escalate privileges.
642if [ ! -z "$TEST_SSH_UNSAFE_PERMISSIONS" ]; then
643	echo "	StrictModes no" >> $OBJ/sshd_config
644else
645	# check and warn if excessive permissions are likely to cause failures.
646	unsafe=""
647	dir="${OBJ}"
648	while test ${dir} != "/"; do
649		if test -d "${dir}" && ! test -h "${dir}"; then
650			perms=`ls -ld ${dir}`
651			case "${perms}" in
652			?????w????*|????????w?*) unsafe="${unsafe} ${dir}" ;;
653			esac
654		fi
655		dir=`dirname ${dir}`
656	done
657	if ! test  -z "${unsafe}"; then
658		cat <<EOD
659
660WARNING: Unsafe (group or world writable) directory permissions found:
661${unsafe}
662
663These could be abused to locally escalate privileges.  If you are
664sure that this is not a risk (eg there are no other users), you can
665bypass this check by setting TEST_SSH_UNSAFE_PERMISSIONS=1
666
667EOD
668	fi
669fi
670
671if [ ! -z "$TEST_SSH_MODULI_FILE" ]; then
672	trace "adding modulifile='$TEST_SSH_MODULI_FILE' to sshd_config"
673	echo "	ModuliFile '$TEST_SSH_MODULI_FILE'" >> $OBJ/sshd_config
674fi
675
676if [ ! -z "$TEST_SSH_SSHD_CONFOPTS" ]; then
677	trace "adding sshd_config option $TEST_SSH_SSHD_CONFOPTS"
678	echo "$TEST_SSH_SSHD_CONFOPTS" >> $OBJ/sshd_config
679fi
680
681# server config for proxy connects
682cp $OBJ/sshd_config $OBJ/sshd_proxy
683
684# allow group-writable directories in proxy-mode
685echo 'StrictModes no' >> $OBJ/sshd_proxy
686
687# create client config
688cat << EOF > $OBJ/ssh_config
689Host *
690	Hostname		127.0.0.1
691	HostKeyAlias		localhost-with-alias
692	Port			$PORT
693	User			$USER
694	GlobalKnownHostsFile	$OBJ/known_hosts
695	UserKnownHostsFile	$OBJ/known_hosts
696	PubkeyAuthentication	yes
697	ChallengeResponseAuthentication	no
698	PasswordAuthentication	no
699	BatchMode		yes
700	StrictHostKeyChecking	yes
701	LogLevel		DEBUG3
702EOF
703
704if [ ! -z "$TEST_SSH_SSH_CONFOPTS" ]; then
705	trace "adding ssh_config option $TEST_SSH_SSH_CONFOPTS"
706	echo "$TEST_SSH_SSH_CONFOPTS" >> $OBJ/ssh_config
707fi
708
709rm -f $OBJ/known_hosts $OBJ/authorized_keys_$USER
710
711SSH_SK_PROVIDER=
712if ! config_defined ENABLE_SK; then
713	trace skipping sk-dummy
714elif [ -f "${SRC}/misc/sk-dummy/obj/sk-dummy.so" ] ; then
715	SSH_SK_PROVIDER="${SRC}/misc/sk-dummy/obj/sk-dummy.so"
716elif [ -f "${OBJ}/misc/sk-dummy/sk-dummy.so" ] ; then
717	SSH_SK_PROVIDER="${OBJ}/misc/sk-dummy/sk-dummy.so"
718elif [ -f "${SRC}/misc/sk-dummy/sk-dummy.so" ] ; then
719	SSH_SK_PROVIDER="${SRC}/misc/sk-dummy/sk-dummy.so"
720fi
721export SSH_SK_PROVIDER
722
723if ! test -z "$SSH_SK_PROVIDER"; then
724	EXTRA_AGENT_ARGS='-P/*' # XXX want realpath(1)...
725	echo "SecurityKeyProvider $SSH_SK_PROVIDER" >> $OBJ/ssh_config
726	echo "SecurityKeyProvider $SSH_SK_PROVIDER" >> $OBJ/sshd_config
727	echo "SecurityKeyProvider $SSH_SK_PROVIDER" >> $OBJ/sshd_proxy
728fi
729export EXTRA_AGENT_ARGS
730
731maybe_filter_sk() {
732	if test -z "$SSH_SK_PROVIDER" ; then
733		grep -v ^sk | grep -v ^webauthn
734	else
735		grep -v ^webauthn
736	fi
737}
738
739SSH_KEYTYPES=`$SSH -Q key-plain | maybe_filter_sk`
740SSH_HOSTKEY_TYPES=`$SSH -Q key-plain | maybe_filter_sk`
741
742for t in ${SSH_KEYTYPES}; do
743	# generate user key
744	if [ ! -f $OBJ/$t ] || [ ${SSHKEYGEN_BIN} -nt $OBJ/$t ]; then
745		trace "generating key type $t"
746		rm -f $OBJ/$t
747		${SSHKEYGEN} -q -N '' -t $t  -f $OBJ/$t ||\
748			fail "ssh-keygen for $t failed"
749	else
750		trace "using cached key type $t"
751	fi
752
753	# setup authorized keys
754	cat $OBJ/$t.pub >> $OBJ/authorized_keys_$USER
755	echo IdentityFile $OBJ/$t >> $OBJ/ssh_config
756done
757
758for t in ${SSH_HOSTKEY_TYPES}; do
759	# known hosts file for client
760	(
761		printf 'localhost-with-alias,127.0.0.1,::1 '
762		cat $OBJ/$t.pub
763	) >> $OBJ/known_hosts
764
765	# use key as host key, too
766	(umask 077; $SUDO cp $OBJ/$t $OBJ/host.$t)
767	echo HostKey $OBJ/host.$t >> $OBJ/sshd_config
768
769	# don't use SUDO for proxy connect
770	echo HostKey $OBJ/$t >> $OBJ/sshd_proxy
771done
772chmod 644 $OBJ/authorized_keys_$USER
773
774# Activate Twisted Conch tests if the binary is present
775REGRESS_INTEROP_CONCH=no
776if test -x "$CONCH" ; then
777	REGRESS_INTEROP_CONCH=yes
778fi
779
780# If PuTTY is present, new enough and we are running a PuTTY test, prepare
781# keys and configuration.
782REGRESS_INTEROP_PUTTY=no
783if test -x "$PUTTYGEN" -a -x "$PLINK" &&
784    "$PUTTYGEN" --help 2>&1 | grep -- --new-passphrase >/dev/null; then
785	REGRESS_INTEROP_PUTTY=yes
786fi
787case "$SCRIPT" in
788*putty*)	;;
789*)		REGRESS_INTEROP_PUTTY=no ;;
790esac
791
792puttysetup() {
793	if test "x$REGRESS_INTEROP_PUTTY" != "xyes" ; then
794		skip "putty interop tests not enabled"
795	fi
796
797	mkdir -p ${OBJ}/.putty
798
799	# Add a PuTTY key to authorized_keys
800	rm -f ${OBJ}/putty.rsa2
801	if ! "$PUTTYGEN" -t rsa -o ${OBJ}/putty.rsa2 \
802	    --random-device=/dev/urandom \
803	    --new-passphrase /dev/null < /dev/null > /dev/null; then
804		echo "Your installed version of PuTTY is too old to support --new-passphrase, skipping test" >&2
805		exit 1
806	fi
807	"$PUTTYGEN" -O public-openssh ${OBJ}/putty.rsa2 \
808	    >> $OBJ/authorized_keys_$USER
809
810	# Convert rsa2 host key to PuTTY format
811	cp $OBJ/ssh-rsa $OBJ/ssh-rsa_oldfmt
812	${SSHKEYGEN} -p -N '' -m PEM -f $OBJ/ssh-rsa_oldfmt >/dev/null
813	${SRC}/ssh2putty.sh 127.0.0.1 $PORT $OBJ/ssh-rsa_oldfmt > \
814	    ${OBJ}/.putty/sshhostkeys
815	${SRC}/ssh2putty.sh 127.0.0.1 22 $OBJ/ssh-rsa_oldfmt >> \
816	    ${OBJ}/.putty/sshhostkeys
817	rm -f $OBJ/ssh-rsa_oldfmt
818
819	# Setup proxied session
820	mkdir -p ${OBJ}/.putty/sessions
821	rm -f ${OBJ}/.putty/sessions/localhost_proxy
822	echo "Protocol=ssh" >> ${OBJ}/.putty/sessions/localhost_proxy
823	echo "HostName=127.0.0.1" >> ${OBJ}/.putty/sessions/localhost_proxy
824	echo "PortNumber=$PORT" >> ${OBJ}/.putty/sessions/localhost_proxy
825	echo "ProxyMethod=5" >> ${OBJ}/.putty/sessions/localhost_proxy
826	echo "ProxyTelnetCommand=${OBJ}/sshd-log-wrapper.sh -i -f $OBJ/sshd_proxy" >> ${OBJ}/.putty/sessions/localhost_proxy
827	echo "ProxyLocalhost=1" >> ${OBJ}/.putty/sessions/localhost_proxy
828
829	PUTTYVER="`${PLINK} --version | awk '/plink: Release/{print $3}'`"
830	PUTTYMAJORVER="`echo ${PUTTYVER} | cut -f1 -d.`"
831	PUTTYMINORVER="`echo ${PUTTYVER} | cut -f2 -d.`"
832	verbose "plink version ${PUTTYVER} major ${PUTTYMAJORVER} minor ${PUTTYMINORVER}"
833
834	# Re-enable ssh-rsa on older PuTTY versions since they don't do newer
835	# key types.
836	if [ "$PUTTYMAJORVER" -eq "0" ] && [ "$PUTTYMINORVER" -lt "76" ]; then
837		echo "HostKeyAlgorithms +ssh-rsa" >> ${OBJ}/sshd_proxy
838		echo "PubkeyAcceptedKeyTypes +ssh-rsa" >> ${OBJ}/sshd_proxy
839	fi
840
841	if [ "$PUTTYMAJORVER" -eq "0" ] && [ "$PUTTYMINORVER" -le "64" ]; then
842		echo "KexAlgorithms +diffie-hellman-group14-sha1" \
843		    >>${OBJ}/sshd_proxy
844	fi
845	PUTTYDIR=${OBJ}/.putty
846	export PUTTYDIR
847}
848
849REGRESS_INTEROP_DROPBEAR=no
850if test -x "$DROPBEARKEY" -a -x "$DBCLIENT" -a -x "$DROPBEARCONVERT"; then
851	REGRESS_INTEROP_DROPBEAR=yes
852fi
853case "$SCRIPT" in
854*dropbear*)	;;
855*)		REGRESS_INTEROP_DROPBEAR=no ;;
856esac
857
858if test "$REGRESS_INTEROP_DROPBEAR" = "yes" ; then
859	trace Create dropbear keys and add to authorized_keys
860	mkdir -p $OBJ/.dropbear $OBJ/.ssh
861	awk '{print "somehost "$2" "$3}' $OBJ/known_hosts >$OBJ/.ssh/known_hosts
862	kt="ed25519"
863	for i in dss rsa ecdsa; do
864		if $SSH -Q key-plain | grep "$i" >/dev/null; then
865			kt="$kt $i"
866		else
867			rm -f "$OBJ/.dropbear/id_$i"
868		fi
869	done
870	for i in $kt; do
871		if [ ! -f "$OBJ/.dropbear/id_$i" ]; then
872			verbose Create dropbear key type $i
873			$DROPBEARKEY -t $i -f $OBJ/.dropbear/id_$i \
874			    >/dev/null 2>&1
875		fi
876		$DROPBEARCONVERT dropbear openssh $OBJ/.dropbear/id_$i \
877		    $OBJ/.dropbear/ossh.id_$i >/dev/null 2>&1
878		$SSHKEYGEN -y -f $OBJ/.dropbear/ossh.id_$i \
879		   >>$OBJ/authorized_keys_$USER
880		rm -f $OBJ/.dropbear/id_$i.pub $OBJ/.dropbear/ossh.id_$i
881	done
882fi
883
884# create a proxy version of the client config
885(
886	cat $OBJ/ssh_config
887	echo proxycommand ${SUDO} env SSH_SK_HELPER=\"$SSH_SK_HELPER\" ${TEST_SSH_SSHD_ENV} ${OBJ}/sshd-log-wrapper.sh -i -f $OBJ/sshd_proxy
888) > $OBJ/ssh_proxy
889
890# check proxy config
891${SSHD} -t -f $OBJ/sshd_proxy	|| fatal "sshd_proxy broken"
892
893# extract proxycommand into separate shell script for use by Dropbear.
894echo '#!/bin/sh' >$OBJ/ssh_proxy.sh
895awk '/^proxycommand/' $OBJ/ssh_proxy | sed 's/^proxycommand//' \
896   >>$OBJ/ssh_proxy.sh
897chmod a+x $OBJ/ssh_proxy.sh
898
899start_sshd ()
900{
901	PIDFILE=$OBJ/pidfile
902	# start sshd
903	logfile="${TEST_SSH_LOGDIR}/sshd.`$OBJ/timestamp`.$$.log"
904	$SUDO env SSH_SK_HELPER="$SSH_SK_HELPER" ${TEST_SSH_SSHD_ENV} \
905	    ${SSHD} -f $OBJ/sshd_config "$@" -t || fatal "sshd_config broken"
906	$SUDO env SSH_SK_HELPER="$SSH_SK_HELPER" ${TEST_SSH_SSHD_ENV} \
907	    ${SSHD} -f $OBJ/sshd_config "$@" -E$TEST_SSHD_LOGFILE
908
909	trace "wait for sshd"
910	i=0;
911	while [ ! -f $PIDFILE -a $i -lt 10 ]; do
912		i=`expr $i + 1`
913		sleep $i
914	done
915	rm -f ${TEST_SSHD_LOGFILE}
916	ln -f -s ${logfile} $TEST_SSHD_LOGFILE
917
918	test -f $PIDFILE || fatal "no sshd running on port $PORT"
919}
920
921enable_all_kexes_in_sshd ()
922{
923	kexs=`$SSH -Q KexAlgorithms | (tr '\n' ,; echo) | sed 's/,$//'`
924	echo KexAlgorithms $kexs >>$OBJ/sshd_config
925}
926
927# Find a PKCS#11 library.
928p11_find_lib() {
929	TEST_SSH_PKCS11=""
930	for _lib in "$@" ; do
931		if test -f "$_lib" ; then
932			TEST_SSH_PKCS11="$_lib"
933			return
934		fi
935	done
936}
937
938# Perform PKCS#11 setup: prepares a softhsm2 token configuration, generated
939# keys and loads them into the virtual token.
940PKCS11_OK=
941export PKCS11_OK
942p11_setup() {
943	# XXX we could potentially test ed25519 only in the absence of
944	# RSA and ECDSA support.
945	$SSH -Q key | grep ssh-rsa >/dev/null || return 1
946	p11_find_lib \
947		/usr/local/lib/softhsm/libsofthsm2.so \
948		/usr/lib64/pkcs11/libsofthsm2.so \
949		/usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so
950	test -z "$TEST_SSH_PKCS11" && return 1
951	trace "using token library $TEST_SSH_PKCS11"
952	TEST_SSH_PIN=1234
953	TEST_SSH_SOPIN=12345678
954	if [ "x$TEST_SSH_SSHPKCS11HELPER" != "x" ]; then
955		SSH_PKCS11_HELPER="${TEST_SSH_SSHPKCS11HELPER}"
956		export SSH_PKCS11_HELPER
957	fi
958
959	# setup environment for softhsm2 token
960	SSH_SOFTHSM_DIR=$OBJ/SOFTHSM
961	export SSH_SOFTHSM_DIR
962	rm -rf $SSH_SOFTHSM_DIR
963	TOKEN=$SSH_SOFTHSM_DIR/tokendir
964	mkdir -p $TOKEN
965	SOFTHSM2_CONF=$SSH_SOFTHSM_DIR/softhsm2.conf
966	export SOFTHSM2_CONF
967	cat > $SOFTHSM2_CONF << EOF
968# SoftHSM v2 configuration file
969directories.tokendir = ${TOKEN}
970objectstore.backend = file
971# ERROR, WARNING, INFO, DEBUG
972log.level = DEBUG
973# If CKF_REMOVABLE_DEVICE flag should be set
974slots.removable = false
975EOF
976	out=$(softhsm2-util --init-token --free --label token-slot-0 --pin "$TEST_SSH_PIN" --so-pin "$TEST_SSH_SOPIN")
977	slot=$(echo -- $out | sed 's/.* //')
978	trace "generating keys"
979	# RSA key
980	RSA=${SSH_SOFTHSM_DIR}/RSA
981	RSAP8=${SSH_SOFTHSM_DIR}/RSAP8
982	$OPENSSL_BIN genpkey -algorithm rsa > $RSA 2>/dev/null || \
983	    fatal "genpkey RSA fail"
984	$OPENSSL_BIN pkcs8 -nocrypt -in $RSA > $RSAP8 || fatal "pkcs8 RSA fail"
985	softhsm2-util --slot "$slot" --label 01 --id 01 --pin "$TEST_SSH_PIN" \
986	    --import $RSAP8 >/dev/null || fatal "softhsm import RSA fail"
987	chmod 600 $RSA
988	${SSHKEYGEN} -y -f $RSA > ${RSA}.pub
989	# ECDSA key
990	ECPARAM=${SSH_SOFTHSM_DIR}/ECPARAM
991	EC=${SSH_SOFTHSM_DIR}/EC
992	ECP8=${SSH_SOFTHSM_DIR}/ECP8
993	$OPENSSL_BIN genpkey -genparam -algorithm ec \
994	    -pkeyopt ec_paramgen_curve:prime256v1 > $ECPARAM || \
995	    fatal "param EC fail"
996	$OPENSSL_BIN genpkey -paramfile $ECPARAM > $EC || \
997	    fatal "genpkey EC fail"
998	$OPENSSL_BIN pkcs8 -nocrypt -in $EC > $ECP8 || fatal "pkcs8 EC fail"
999	softhsm2-util --slot "$slot" --label 02 --id 02 --pin "$TEST_SSH_PIN" \
1000	    --import $ECP8 >/dev/null || fatal "softhsm import EC fail"
1001	chmod 600 $EC
1002	${SSHKEYGEN} -y -f $EC > ${EC}.pub
1003	# Ed25519 key
1004	ED25519=${SSH_SOFTHSM_DIR}/ED25519
1005	ED25519P8=${SSH_SOFTHSM_DIR}/ED25519P8
1006	$OPENSSL_BIN genpkey -algorithm ed25519 > $ED25519 || \
1007	    fatal "genpkey Ed25519 fail"
1008	$OPENSSL_BIN pkcs8 -nocrypt -in $ED25519 > $ED25519P8 || \
1009		fatal "pkcs8 Ed25519 fail"
1010	softhsm2-util --slot "$slot" --label 03 --id 03 --pin "$TEST_SSH_PIN" \
1011	    --import $ED25519P8 >/dev/null || \
1012		fatal "softhsm import ed25519 fail"
1013	chmod 600 $ED25519
1014	${SSHKEYGEN} -y -f $ED25519 > ${ED25519}.pub
1015	# Prepare some askpass scripts to load PINs.
1016	PIN_SH=$SSH_SOFTHSM_DIR/pin.sh
1017	cat > $PIN_SH << EOF
1018#!/bin/sh
1019echo "${TEST_SSH_PIN}"
1020EOF
1021	chmod 0700 "$PIN_SH"
1022	WRONGPIN_SH=$SSH_SOFTHSM_DIR/wrongpin.sh
1023	cat > $WRONGPIN_SH << EOF
1024#!/bin/sh
1025echo "0000"
1026EOF
1027	chmod 0700 "$WRONGPIN_SH"
1028	PKCS11_OK=yes
1029	if env SSH_ASKPASS="$PIN_SH" SSH_ASKPASS_REQUIRE=force \
1030	    ${SSHKEYGEN} -D ${TEST_SSH_PKCS11} >/dev/null 2>&1 ; then
1031		return 0
1032	fi
1033	return 1
1034}
1035
1036# Peforms ssh-add with the right token PIN.
1037p11_ssh_add() {
1038	env SSH_ASKPASS="$PIN_SH" SSH_ASKPASS_REQUIRE=force ${SSHADD} "$@"
1039}
1040
1041start_ssh_agent() {
1042	EXTRA_AGENT_ARGS="$1"
1043	if [ "$PKCS11_OK" = "yes" ]; then
1044		EXTRA_AGENT_ARGS="${EXTRA_AGENT_ARGS} -P${TEST_SSH_PKCS11}"
1045	fi
1046	SSH_AUTH_SOCK="$OBJ/agent.sock"
1047	export SSH_AUTH_SOCK
1048	rm -f $SSH_AUTH_SOCK $OBJ/agent.log
1049	trace "start agent"
1050	${SSHAGENT} ${EXTRA_AGENT_ARGS} -d -a $SSH_AUTH_SOCK \
1051	    > $OBJ/agent.log 2>&1 &
1052	AGENT_PID=$!
1053	trap "kill $AGENT_PID" EXIT
1054	for x in 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ; do
1055		# Give it a chance to start
1056		${SSHADD} -l > /dev/null 2>&1
1057		r=$?
1058		test $r -eq 1 && break
1059		sleep 1
1060	done
1061	if [ $r -ne 1 ]; then
1062		fatal "ssh-add -l did not fail with exit code 1 (got $r)"
1063	fi
1064}
1065
1066# source test body
1067. $SCRIPT
1068
1069# kill sshd
1070cleanup
1071
1072if [ "x$USE_VALGRIND" != "x" ]; then
1073	# If there is an EXIT trap handler, invoke it now.
1074	# Some tests set these to clean up processes such as ssh-agent.  We
1075	# need to wait for all valgrind processes to complete so we can check
1076	# their logs, but since the EXIT traps are not invoked until
1077	# test-exec.sh exits, waiting here will deadlock.
1078	# This is not very portable but then neither is valgrind itself.
1079	# As a bonus, dash (as used on the runners) has a "trap" that doesn't
1080	# work in a pipeline (hence the temp file) or a subshell.
1081	exithandler=""
1082	trap >/tmp/trap.$$ && exithandler=$(cat /tmp/trap.$$ | \
1083	    awk -F "'" '/EXIT$/{print $2}')
1084	rm -f /tmp/trap.$$
1085	if [ "x${exithandler}" != "x" ]; then
1086		verbose invoking EXIT trap handler early: ${exithandler}
1087		eval "${exithandler}"
1088		trap '' EXIT
1089	fi
1090
1091	# wait for any running process to complete
1092	wait; sleep 1
1093	VG_RESULTS=$(find $OBJ/valgrind-out -type f -print)
1094	VG_RESULT_COUNT=0
1095	VG_FAIL_COUNT=0
1096	for i in $VG_RESULTS; do
1097		if grep "ERROR SUMMARY" $i >/dev/null; then
1098			VG_RESULT_COUNT=$(($VG_RESULT_COUNT + 1))
1099			if ! grep "ERROR SUMMARY: 0 errors" $i >/dev/null; then
1100				VG_FAIL_COUNT=$(($VG_FAIL_COUNT + 1))
1101				RESULT=1
1102				verbose valgrind failure $i
1103				cat $i
1104			fi
1105		fi
1106	done
1107	if [ x"$VG_SKIP" != "x" ]; then
1108		verbose valgrind skipped
1109	else
1110		verbose valgrind results $VG_RESULT_COUNT failures $VG_FAIL_COUNT
1111	fi
1112fi
1113
1114if [ $RESULT -eq 0 ]; then
1115	verbose ok $tid
1116	if [ "x$CACHE" != "x" ]; then
1117		touch "$CACHE"
1118	fi
1119else
1120	echo failed $tid
1121fi
1122exit $RESULT
1123