1#!/bin/sh -
2#
3#	$NetBSD: security,v 1.109 2010/12/27 03:38:52 christos Exp $
4#	from: @(#)security	8.1 (Berkeley) 6/9/93
5#
6
7PATH=/sbin:/usr/sbin:/bin:/usr/bin
8
9rcvar_manpage='security.conf(5)'
10
11if [ -f /etc/rc.subr ]; then
12	. /etc/rc.subr
13else
14	echo "Can't read /etc/rc.subr; aborting."
15	exit 1;
16fi
17
18umask 077
19TZ=UTC; export TZ
20
21if [ -s /etc/security.conf ]; then
22	. /etc/security.conf
23fi
24
25# Set reasonable defaults (if they're not set in security.conf)
26#
27backup_dir=${backup_dir:-/var/backups}
28max_loginlen=${max_loginlen:-8}
29max_grouplen=${max_grouplen:-8}
30pkg_info=${pkg_info:-/usr/sbin/pkg_info}
31
32# Other configurable variables
33#
34special_files="/etc/mtree/special /etc/mtree/special.local"
35MP=/etc/master.passwd
36CHANGELIST=""
37work_dir=$backup_dir/work
38
39if [ ! -d "$work_dir" ]; then
40	mkdir -p "$work_dir"
41fi
42
43SECUREDIR=$(mktemp -d -t _securedir) || exit 1
44
45trap "/bin/rm -rf $SECUREDIR ; exit 0" EXIT INT QUIT PIPE
46
47if ! cd "$SECUREDIR"; then
48	echo "Can not cd to $SECUREDIR".
49	exit 1
50fi
51
52ERR=err.$$
53TMP1=tmp1.$$
54TMP2=tmp2.$$
55MPBYUID=mpbyuid.$$
56MPBYPATH=mpbypath.$$
57LIST=list.$$
58OUTPUT=output.$$
59LABELS=labels.$$
60LVM_LABELS=lvm.$$
61PKGS=pkgs.$$
62CHANGEFILES=changefiles.$$
63SPECIALSPEC=specialspec.$$
64
65if [ -n "${pkgdb_dir}" ]; then
66    echo "WARNING: Setting pkgdb_dir in security.conf(5) is deprecated"
67    echo "WARNING: Please define PKG_DBDIR in pkg_install.conf(5) instead"
68    _compat_K_flag="-K ${pkgdb_dir}"
69fi
70
71have_pkgs() {
72	$pkg_info ${_compat_K_flag} -q -E '*'
73}
74
75# migrate_file old new
76#	Determine if the "${old}" path name needs to be migrated to the
77#	"${new}" path. Also checks if "${old}.current" needs migrating,
78#	and if so, migrate it and possibly "${old}.current,v" and
79#	"${old}.backup".
80#
81migrate_file()
82{
83	_old=$1
84	_new=$2
85	if [ -z "$_old" -o -z "$_new" ]; then
86		err 3 "USAGE: migrate_file old new"
87	fi
88	if [ ! -d "${_new%/*}" ]; then
89		mkdir -p "${_new%/*}"
90	fi
91	if [ -f "${_old}" -a ! -f "${_new}" ]; then
92		echo "==> migrating ${_old}"
93		echo "           to ${_new}"
94		mv "${_old}" "${_new}"
95	fi
96	if [ -f "${_old}.current" -a ! -f "${_new}.current" ]; then
97		echo "==> migrating ${_old}.current"
98		echo "           to ${_new}.current"
99		mv "${_old}.current" "${_new}.current"
100		if [ -f "${_old}.current,v" -a ! -f "${_new}.current,v" ]; then
101			echo "==> migrating ${_old}.current,v"
102			echo "           to ${_new}.current,v"
103			mv "${_old}.current,v" "${_new}.current,v"
104		fi
105		if [ -f "${_old}.backup" -a ! -f "${_new}.backup" ]; then
106			echo "==> migrating ${_old}.backup"
107			echo "           to ${_new}.backup"
108			mv "${_old}.backup" "${_new}.backup"
109		fi
110	fi
111}
112
113
114# backup_and_diff file printdiff
115#	Determine if file needs backing up, and if so, do it.
116#	If printdiff is yes, display the diffs, otherwise 
117#	just print a message saying "[changes omitted]".
118#
119backup_and_diff()
120{
121	_file=$1
122	_printdiff=$2
123	if [ -z "$_file" -o -z "$_printdiff" ]; then
124		err 3 "USAGE: backup_and_diff file printdiff"
125	fi
126	! checkyesno _printdiff
127	_printdiff=$?
128
129	_old=$backup_dir/${_file##*/}
130	case "$_file" in
131	$work_dir/*)
132		_new=$_file
133		migrate_file "$backup_dir/$_old" "$_new"
134		migrate_file "$_old" "$_new"
135		;;
136	*)
137		_new=$backup_dir/$_file
138		migrate_file "$_old" "$_new"
139		;;
140	esac
141	CUR=${_new}.current
142	BACK=${_new}.backup
143	if [ -f $_file ]; then
144		if [ -f $CUR ] ; then
145			if [ "$_printdiff" -ne 0 ]; then
146				diff ${diff_options} $CUR $_file > $OUTPUT
147			else
148				if ! cmp -s $CUR $_file; then
149					echo "[changes omitted]"
150				fi > $OUTPUT
151			fi
152			if [ -s $OUTPUT ] ; then
153				printf \
154			"\n======\n%s diffs (OLD < > NEW)\n======\n" $_file
155				cat $OUTPUT
156				backup_file update $_file $CUR $BACK
157			fi
158		else
159			printf "\n======\n%s added\n======\n" $_file
160			if [ "$_printdiff" -ne 0 ]; then
161				diff ${diff_options} /dev/null $_file
162			else
163				echo "[changes omitted]"
164			fi
165			backup_file add $_file $CUR $BACK
166		fi
167	else
168		if [ -f $CUR ]; then
169			printf "\n======\n%s removed\n======\n" $_file
170			if [ "$_printdiff" -ne 0 ]; then
171				diff ${diff_options} $CUR /dev/null
172			else
173				echo "[changes omitted]"
174			fi
175			backup_file remove $_file $CUR $BACK
176		fi
177	fi
178}
179
180
181# These are used several times.
182#
183awk -F: '!/^\+/ { print $1 " " $3 }' $MP | sort -k2n > $MPBYUID
184awk -F: '{ print $1 " " $9 }' $MP | sort -k2 > $MPBYPATH
185for file in $special_files; do
186	[ -s $file ] && cat $file
187done | mtree -CM -k all > $SPECIALSPEC || exit 1
188
189
190# Check the master password file syntax.
191#
192if checkyesno check_passwd; then
193        # XXX: the sense of permit_star is reversed; the code works as
194        # implemented, but usage needs to be negated.
195	checkyesno check_passwd_permit_star && permit_star=0 || permit_star=1
196	checkyesno check_passwd_permit_nonalpha \
197		 && permit_nonalpha=1 || permit_nonalpha=0
198
199	awk -v "len=$max_loginlen" \
200	    -v "nowarn_shells_list=$check_passwd_nowarn_shells" \
201	    -v "nowarn_users_list=$check_passwd_nowarn_users" \
202	    -v "permit_star=$permit_star" \
203	    -v "permit_nonalpha=$permit_nonalpha" \
204	'
205	BEGIN {
206		while ( getline < "/etc/shells" > 0 ) {
207			if ($0 ~ /^\#/ || $0 ~ /^$/ )
208				continue;
209			shells[$1]++;
210		}
211		split(nowarn_shells_list, a);
212		for (i in a) nowarn_shells[a[i]]++;
213		split(nowarn_users_list, a);
214		for (i in a) nowarn_users[a[i]]++;
215		uid0_users_list="root toor"
216		split(uid0_users_list, a);
217		for (i in a) uid0_users[a[i]]++;
218		FS=":";
219	}
220
221	{
222		if ($0 ~ /^[	 ]*$/) {
223			printf "Line %d is a blank line.\n", NR;
224			next;
225		}
226
227		# NIS compat entry?
228		compatline = $1 ~ "^[\\+-]";
229		if (compatline) {
230			if ($1 == "+" && NF == 1) {
231				next;
232			}
233			sub("^.", "", $1);
234		}
235		if (NF != 10)
236			printf "Line %d has the wrong number of fields.\n", NR;
237		if (compatline)  {
238			if ($3 == 0)
239			    printf "Line %d includes entries with uid 0.\n",
240			        NR;
241			if ($1 == "")
242			    next;
243		}
244		if (!permit_nonalpha &&
245		    $1 !~ /^[_A-Za-z0-9]([-A-Za-z0-9_.]*[A-Za-z0-9])*$/)
246			printf "Login %s has non-alphanumeric characters.\n",
247			    $1;
248		if (length($1) > len)
249			printf "Login %s has more than "len" characters.\n",
250			    $1;
251		if ($2 == "" && !compatline && !nowarn_users[$1])
252			    printf "Login %s has no password.\n", $1;
253		if (!nowarn_shells[$10] && !nowarn_users[$1]) {
254		    if (length($2) != 13 &&
255		    	length($2) != 20 &&
256		    	$2 !~ /^\$1/ &&
257		    	$2 !~ /^\$2/ &&
258			$2 !~ /^\$sha1/ &&
259		    	$2 != "" &&
260			(permit_star || $2 != "*") &&
261		    	$2 !~ /^\*[A-z-]+$/ &&
262			$1 != "toor") {
263		    	    if ($10 == "" || shells[$10])
264				printf "Login %s is off but still has "\
265				  "a valid shell (%s)\n", $1, $10;
266		    } else if (compatline && $10 == "") {
267			    # nothing
268		    } else if (! shells[$10])
269		    	    printf "Login %s does not have a valid "\
270			    "shell (%s)\n", $1, $10;
271		}
272		if ($3 == 0 && !uid0_users[$1] && !nowarn_users[$1])
273			printf "Login %s has a user id of 0.\n", $1;
274		if ($3 != "" && $3 < 0)
275			printf "Login %s has a negative user id.\n", $1;
276		if ($4 != "" && $4 < 0)
277			printf "Login %s has a negative group id.\n", $1;
278	}' < $MP > $OUTPUT
279	if [ -s $OUTPUT ] ; then
280		printf "\nChecking the $MP file:\n"
281		cat $OUTPUT
282	fi
283
284	awk -F: '{ print $1 }' $MP | sort | uniq -d > $OUTPUT
285	if [ -s $OUTPUT ] ; then
286		printf "\n$MP has duplicate user names.\n"
287		column $OUTPUT
288	fi
289
290# To not exclude 'toor', a standard duplicate root account, from the duplicate
291# account test, uncomment the line below (without egrep in it)and comment
292# out the line (with egrep in it) below it.
293#
294#	< $MPBYUID uniq -d -f 1 | awk '{ print $2 }' > $TMP2
295	< $MPBYUID egrep -v '^toor ' | uniq -d -f 1 | awk '{ print $2 }' > $TMP2
296	if [ -s $TMP2 ] ; then
297		printf "\n$MP has duplicate user id's.\n"
298		while read uid; do
299			grep -w $uid $MPBYUID
300		done < $TMP2 | column
301	fi
302fi
303
304# Check the group file syntax.
305#
306if checkyesno check_group; then
307	GRP=/etc/group
308	awk -F: -v "len=$max_grouplen" '{
309		if ($0 ~ /^[	 ]*$/) {
310			printf "Line %d is a blank line.\n", NR;
311			next;
312		}
313		if (NF != 4 && ($1 != "+" || NF != 1))
314			printf "Line %d has the wrong number of fields.\n", NR;
315		if ($1 == "+" )  {
316			next;
317		}
318		if ($1 !~ /^[_A-Za-z0-9]([-A-Za-z0-9_.]*[A-Za-z0-9])*$/)
319			printf "Group %s has non-alphanumeric characters.\n",
320			    $1;
321		if (length($1) > len)
322			printf "Group %s has more than "len" characters.\n", $1;
323		if ($3 !~ /[0-9]*/)
324			printf "Login %s has a negative group id.\n", $1;
325	}' < $GRP > $OUTPUT
326	if [ -s $OUTPUT ] ; then
327		printf "\nChecking the $GRP file:\n"
328		cat $OUTPUT
329	fi
330
331	awk -F: '{ print $1 }' $GRP | sort | uniq -d > $OUTPUT
332	if [ -s $OUTPUT ] ; then
333		printf "\n$GRP has duplicate group names.\n"
334		column $OUTPUT
335	fi
336fi
337
338# Check for root paths, umask values in startup files.
339# The check for the root paths is problematical -- it's likely to fail
340# in other environments.  Once the shells have been modified to warn
341# of '.' in the path, the path tests should go away.
342#
343if checkyesno check_rootdotfiles; then
344	rhome=~root
345	umaskset=no
346	list="/etc/csh.cshrc /etc/csh.login ${rhome}/.cshrc ${rhome}/.login"
347	for i in $list ; do
348		if [ -f $i ] ; then
349			if egrep '^[ \t]*umask[ \t]+[0-7]+' $i > /dev/null ;
350			then
351				umaskset=yes
352			fi
353			# Double check the umask value itself; ensure that
354			# both the group and other write bits are set.
355			#
356			egrep '^[ \t]*umask[ \t]+[0-7]+' $i |
357			awk '{
358				if ($2 ~ /^.$/ || $2 ~! /[^2367].$/) {
359					print "\tRoot umask is group writable"
360				}
361				if ($2 ~ /[^2367]$/) {
362					print "\tRoot umask is other writable"
363			    	}
364			    }' | sort -u
365			SAVE_PATH=$PATH
366			unset PATH
367			/bin/csh -f -s << end-of-csh > /dev/null 2>&1
368				source $i
369				/bin/ls -ldgT \$path > $TMP1
370end-of-csh
371			export PATH=$SAVE_PATH
372			awk '{
373				if ($10 ~ /^\.$/) {
374					print "\tThe root path includes .";
375					next;
376				}
377			     }
378			     $1 ~ /^d....w/ \
379		{ print "\tRoot path directory " $10 " is group writable." } \
380			     $1 ~ /^d.......w/ \
381		{ print "\tRoot path directory " $10 " is other writable." }' \
382			< $TMP1
383		fi
384	done > $OUTPUT
385	if [ $umaskset = "no" -o -s $OUTPUT ] ; then
386		printf "\nChecking root csh paths, umask values:\n$list\n\n"
387		if [ -s $OUTPUT ]; then
388			cat $OUTPUT
389		fi
390		if [ $umaskset = "no" ] ; then
391		    printf "\tRoot csh startup files do not set the umask.\n"
392		fi
393	fi
394
395	umaskset=no
396	list="/etc/profile ${rhome}/.profile"
397	for i in $list; do
398		if [ -f $i ] ; then
399			if egrep umask $i > /dev/null ; then
400				umaskset=yes
401			fi
402			egrep umask $i |
403			awk '$2 ~ /^.$/ || $2 ~ /[^2367].$/ \
404				{ print "\tRoot umask is group writable" } \
405			     $2 ~ /[^2367]$/ \
406				{ print "\tRoot umask is other writable" }'
407			SAVE_PATH=$PATH
408			unset PATH
409			/bin/sh << end-of-sh > /dev/null 2>&1
410				. $i
411				list=\$(echo \$PATH | /usr/bin/sed -e \
412				    's/^:/.:/;s/:$/:./;s/::/:.:/g;s/:/ /g')
413				/bin/ls -ldgT \$list > $TMP1
414end-of-sh
415			export PATH=$SAVE_PATH
416			awk '{
417				if ($10 ~ /^\.$/) {
418					print "\tThe root path includes .";
419					next;
420				}
421			     }
422			     $1 ~ /^d....w/ \
423		{ print "\tRoot path directory " $10 " is group writable." } \
424			     $1 ~ /^d.......w/ \
425		{ print "\tRoot path directory " $10 " is other writable." }' \
426			< $TMP1
427
428		fi
429	done > $OUTPUT
430	if [ $umaskset = "no" -o -s $OUTPUT ] ; then
431		printf "\nChecking root sh paths, umask values:\n$list\n"
432		if [ -s $OUTPUT ]; then
433			cat $OUTPUT
434		fi
435		if [ $umaskset = "no" ] ; then
436			printf "\tRoot sh startup files do not set the umask.\n"
437		fi
438	fi
439fi
440
441# Root and uucp should both be in /etc/ftpusers.
442#
443if checkyesno check_ftpusers; then
444	list="uucp "$(awk '$2 == 0 { print $1 }' $MPBYUID)
445	for i in $list; do
446		if /usr/libexec/ftpd -C $i ; then
447			printf "\t$i is not denied\n"
448		fi
449	done > $OUTPUT
450	if [ -s $OUTPUT ]; then
451		printf "\nChecking the /etc/ftpusers configuration:\n"
452		cat $OUTPUT
453	fi
454fi
455
456# Uudecode should not be in the /etc/mail/aliases file.
457#
458if checkyesno check_aliases; then
459	for f in /etc/mail/aliases /etc/aliases; do
460		if [ -f $f ] && egrep '^[^#]*(uudecode|decode).*\|' $f; then
461			printf "\nEntry for uudecode in $f file.\n"
462		fi
463	done
464fi
465
466# Files that should not have + signs.
467#
468if checkyesno check_rhosts; then
469	list="/etc/hosts.equiv /etc/hosts.lpd"
470	for f in $list ; do
471		if [ -f $f ] && egrep '\+' $f > /dev/null ; then
472			printf "\nPlus sign in $f file.\n"
473		fi
474	done
475
476	# Check for special users with .rhosts files.  Only root and toor should
477	# have .rhosts files.  Also, .rhosts files should not have plus signs.
478	awk -F: '$1 != "root" && $1 != "toor" && \
479		($3 < 100 || $1 == "ftp" || $1 == "uucp") \
480			{ print $1 " " $9 }' $MP |
481	sort -k2 |
482	while read uid homedir; do
483		if [ -f ${homedir}/.rhosts ] ; then
484			rhost=$(ls -ldgT ${homedir}/.rhosts)
485			printf -- "$uid: $rhost\n"
486		fi
487	done > $OUTPUT
488	if [ -s $OUTPUT ] ; then
489		printf "\nChecking for special users with .rhosts files.\n"
490		cat $OUTPUT
491	fi
492
493	while read uid homedir; do
494		if [ -f ${homedir}/.rhosts -a -r ${homedir}/.rhosts ] && \
495		    cat -f ${homedir}/.rhosts | egrep '\+' > /dev/null ; then
496			printf -- "$uid: + in .rhosts file.\n"
497		fi
498	done < $MPBYPATH > $OUTPUT
499	if [ -s $OUTPUT ] ; then
500		printf "\nChecking .rhosts files syntax.\n"
501		cat $OUTPUT
502	fi
503fi
504
505# Check home directories.  Directories should not be owned by someone else
506# or writable.
507#
508if checkyesno check_homes; then
509	checkyesno check_homes_permit_usergroups && \
510		permit_usergroups=1 || permit_usergroups=0
511	while read uid homedir; do
512		if [ -d ${homedir}/ ] ; then
513			file=$(ls -ldgT ${homedir})
514			printf -- "$uid $file\n"
515		fi
516	done < $MPBYPATH |
517	awk -v "usergroups=$permit_usergroups" '
518	     $1 != $4 && $4 != "root" \
519		{ print "user " $1 " home directory is owned by " $4 }
520	     $2 ~ /^d....w/ && (!usergroups || $5 != $1) \
521		{ print "user " $1 " home directory is group writable" }
522	     $2 ~ /^d.......w/ \
523		{ print "user " $1 " home directory is other writable" }' \
524	    > $OUTPUT
525	if [ -s $OUTPUT ] ; then
526		printf "\nChecking home directories.\n"
527		cat $OUTPUT
528	fi
529
530	# Files that should not be owned by someone else or readable.
531	list=".Xauthority .netrc .ssh/id_dsa .ssh/id_rsa .ssh/identity"
532	while read uid homedir; do
533		for f in $list ; do
534			file=${homedir}/${f}
535			if [ -f $file ] ; then
536				printf -- "$uid $f $(ls -ldgT $file)\n"
537			fi
538		done
539	done < $MPBYPATH |
540	awk  -v "usergroups=$permit_usergroups" '
541	     $1 != $5 && $5 != "root" \
542		{ print "user " $1 " " $2 " file is owned by " $5 }
543	     $3 ~ /^-...r/ && (!usergroups || $6 != $1) \
544		{ print "user " $1 " " $2 " file is group readable" }
545	     $3 ~ /^-......r/ \
546		{ print "user " $1 " " $2 " file is other readable" }
547	     $3 ~ /^-....w/ && (!usergroups || $6 != $1) \
548		{ print "user " $1 " " $2 " file is group writable" }
549	     $3 ~ /^-.......w/ \
550		{ print "user " $1 " " $2 " file is other writable" }' \
551	    > $OUTPUT
552
553	# Files that should not be owned by someone else or writable.
554	list=".bash_history .bash_login .bash_logout .bash_profile .bashrc \
555	      .cshrc .emacs .exrc .forward .history .k5login .klogin .login \
556	      .logout .profile .qmail .rc_history .rhosts .shosts ssh .tcshrc \
557	      .twmrc .xinitrc .xsession .ssh/authorized_keys \
558	      .ssh/authorized_keys2 .ssh/config .ssh/id_dsa.pub \
559	      .ssh/id_rsa.pub .ssh/identity.pub .ssh/known_hosts \
560	      .ssh/known_hosts2"
561	while read uid homedir; do
562		for f in $list ; do
563			file=${homedir}/${f}
564			if [ -f $file ] ; then
565				printf -- "$uid $f $(ls -ldgT $file)\n"
566			fi
567		done
568	done < $MPBYPATH |
569	awk -v "usergroups=$permit_usergroups" '
570	     $1 != $5 && $5 != "root" \
571		{ print "user " $1 " " $2 " file is owned by " $5 }
572	     $3 ~ /^-....w/ && (!usergroups || $6 != $1) \
573		{ print "user " $1 " " $2 " file is group writable" }
574	     $3 ~ /^-.......w/ \
575		{ print "user " $1 " " $2 " file is other writable" }' \
576	    >> $OUTPUT
577	if [ -s $OUTPUT ] ; then
578		printf "\nChecking dot files.\n"
579		cat $OUTPUT
580	fi
581fi
582
583# Mailboxes should be owned by user and unreadable.
584#
585if checkyesno check_varmail; then
586	ls -lA /var/mail | \
587	awk '	NR == 1 { next; }
588		$9 ~ /^\./ {next; }
589	    	$3 != $9 {
590			print "user " $9 " mailbox is owned by " $3
591		}
592		$1 != "-rw-------" {
593			print "user " $9 " mailbox is " $1 ", group " $4
594		}' > $OUTPUT
595	if [ -s $OUTPUT ] ; then
596		printf "\nChecking mailbox ownership.\n"
597		cat $OUTPUT
598	fi
599fi
600
601# NFS exports shouldn't be globally exported
602#
603if checkyesno check_nfs && [ -f /etc/exports ]; then
604	awk '{
605		# ignore comments and blank lines
606		if ($0 ~ /^\#/ || $0 ~ /^$/ )
607			next;
608		# manage line continuation
609		while ($NF ~ /^\\$/) {
610			$NF = "";
611			line = $0 "";
612			getline;
613			$0 = line $0 "";
614		}
615
616		delete dir;
617		readonly = ndir = 0;
618		for (i = 1; i <= NF; ++i) {
619			if ($i ~ /^\//) dir[ndir++] = $i;
620			else if ($i ~ /^-/) {
621				if ($i ~ /^-(ro|o)$/) readonly = 1;
622				if ($i ~ /^-network/) next;
623			}
624			else next;
625		}
626		if (readonly)
627			for (item in dir)
628				rodir[nrodir++] = dir[item];
629		else
630			for (item in dir)
631				rwdir[nrwdir++] = dir[item];
632
633	}
634
635	END {
636		if (nrodir) {
637			printf("Globally exported file system%s, read-only:\n",
638				nrodir > 1 ? "s" : "");
639			for (item in rodir)
640				printf("\t%s\n", rodir[item]);
641		}
642		if (nrwdir) {
643			printf("Globally exported file system%s, read-write:\n",
644				nrwdir > 1 ? "s" : "");
645			for (item in rwdir)
646				printf("\t%s\n", rwdir[item]);
647		}
648	}' < /etc/exports > $OUTPUT
649	if [ -s $OUTPUT ] ; then
650		printf "\nChecking for globally exported file systems.\n"
651		cat $OUTPUT
652	fi
653fi
654
655# Display any changes in setuid files and devices.
656#
657if checkyesno check_devices; then
658	> $ERR
659	(
660
661	# Convert check_devices_ignore_fstypes="foo !bar bax"
662	#    into "-fstype foo -o ! -fstype bar -o -fstype bax"
663	# and check_devices_ignore_paths="/foo !/bar /bax"
664	#    into " -path /foo -o ! -path /bar -o -path /bax"
665	#
666	ignexpr=$(\
667	    echo $check_devices_ignore_fstypes | \
668		sed -e's/\(!*\)\([^[:space:]]\{1,\}\)/-o \1 -fstype \2/g' ; \
669	    echo $check_devices_ignore_paths | \
670		sed -e's/\(!*\)\([^[:space:]]\{1,\}\)/-o \1 -path \2/g' \
671	)
672
673	# Massage the expression into ( $ignexpr ) -a -prune -o
674	if [ -n "${ignexpr}" ]; then
675		ignexpr=$(\
676			echo $ignexpr | \
677			    sed -e 's/^-o /( /' \
678				-e 's/$/ ) -a -prune -o/' \
679		)
680	fi
681
682	find / $ignexpr \
683	    \( \( -perm -u+s -a ! -type d \) -o \
684	       \( -perm -g+s -a ! -type d \) -o \
685	       -type b -o -type c \) -print0 | \
686	xargs -0 ls -ldgTq | sort +9 > $LIST
687
688	) 2> $OUTPUT
689
690	# Display any errors that occurred during system file walk.
691	if [ -s $OUTPUT ] ; then
692		printf "Setuid/device find errors:\n" >> $ERR
693		cat $OUTPUT >> $ERR
694		printf "\n" >> $ERR
695	fi
696
697	# Display any changes in the setuid file list.
698	egrep -v '^[bc]' $LIST > $TMP1
699	if [ -s $TMP1 ] ; then
700		# Check to make sure uudecode isn't setuid.
701		if grep -w uudecode $TMP1 > /dev/null ; then
702			printf "\nUudecode is setuid.\n" >> $ERR
703		fi
704
705		file=$work_dir/setuid
706		migrate_file "$backup_dir/setuid" "$file"
707		CUR=${file}.current
708		BACK=${file}.backup
709		if [ -s $CUR ] ; then
710			if cmp -s $CUR $TMP1 ; then
711				:
712			else
713				> $TMP2
714				join -110 -210 -v2 $CUR $TMP1 > $OUTPUT
715				if [ -s $OUTPUT ] ; then
716					printf "Setuid additions:\n" >> $ERR
717					tee -a $TMP2 < $OUTPUT >> $ERR
718					printf "\n" >> $ERR
719				fi
720
721				join -110 -210 -v1 $CUR $TMP1 > $OUTPUT
722				if [ -s $OUTPUT ] ; then
723					printf "Setuid deletions:\n" >> $ERR
724					tee -a $TMP2 < $OUTPUT >> $ERR
725					printf "\n" >> $ERR
726				fi
727
728				sort -k10 $TMP2 $CUR $TMP1 | \
729				    sed -e 's/[	 ][	 ]*/ /g' | \
730				    uniq -u > $OUTPUT
731				if [ -s $OUTPUT ] ; then
732					printf "Setuid changes:\n" >> $ERR
733					column -t $OUTPUT >> $ERR
734					printf "\n" >> $ERR
735				fi
736
737				backup_file update $TMP1 $CUR $BACK
738			fi
739		else
740			printf "Setuid additions:\n" >> $ERR
741			column -t $TMP1 >> $ERR
742			printf "\n" >> $ERR
743			backup_file add $TMP1 $CUR $BACK
744		fi
745	fi
746
747	# Check for block and character disk devices that are readable or
748	# writable or not owned by root.operator.
749	>$TMP1
750	DISKLIST="ccd ch hk hp ld md ra raid rb rd rl rx \
751	    sd se ss uk up vnd wd xd xy"
752#	DISKLIST="$DISKLIST ct mt st wt"
753	for i in $DISKLIST; do
754		egrep "^b.*/${i}[0-9][0-9]*[a-p]$"  $LIST >> $TMP1
755		egrep "^c.*/r${i}[0-9][0-9]*[a-p]$"  $LIST >> $TMP1
756	done
757
758	awk '$3 != "root" || $4 != "operator" || $1 !~ /.rw-r-----/ \
759		{ printf "Disk %s is user %s, group %s, permissions %s.\n", \
760		    $11, $3, $4, $1; }' < $TMP1 > $OUTPUT
761	if [ -s $OUTPUT ] ; then
762		printf "\nChecking disk ownership and permissions.\n" >> $ERR
763		cat $OUTPUT >> $ERR
764		printf "\n" >> $ERR
765	fi
766
767	# Display any changes in the device file list.
768	egrep '^[bc]' $LIST | sort -k11 > $TMP1
769	if [ -s $TMP1 ] ; then
770		file=$work_dir/device
771		migrate_file "$backup_dir/device" "$file"
772		CUR=${file}.current
773		BACK=${file}.backup
774
775		if [ -s $CUR ] ; then
776			if cmp -s $CUR $TMP1 ; then
777				:
778			else
779				> $TMP2
780				join -111 -211 -v2 $CUR $TMP1 > $OUTPUT
781				if [ -s $OUTPUT ] ; then
782					printf "Device additions:\n" >> $ERR
783					tee -a $TMP2 < $OUTPUT >> $ERR
784					printf "\n" >> $ERR
785				fi
786
787				join -111 -211 -v1 $CUR $TMP1 > $OUTPUT
788				if [ -s $OUTPUT ] ; then
789					printf "Device deletions:\n" >> $ERR
790					tee -a $TMP2 < $OUTPUT >> $ERR
791					printf "\n" >> $ERR
792				fi
793
794				# Report any block device change. Ignore
795				# character devices, only the name is
796				# significant.
797				cat $TMP2 $CUR $TMP1 | \
798				    sed -e '/^c/d' | \
799				    sort -k11 | \
800				    sed -e 's/[	 ][	 ]*/ /g' | \
801				    uniq -u > $OUTPUT
802				if [ -s $OUTPUT ] ; then
803					printf "Block device changes:\n" >> $ERR
804					column -t $OUTPUT >> $ERR
805					printf "\n" >> $ERR
806				fi
807
808				backup_file update $TMP1 $CUR $BACK
809			fi
810		else
811			printf "Device additions:\n" >> $ERR
812			column -t $TMP1 >> $ERR
813			printf "\n" >> $ERR
814			backup_file add $TMP1 $CUR $BACK >> $ERR
815		fi
816	fi
817	if [ -s $ERR ] ; then
818		printf "\nChecking setuid files and devices:\n"
819		cat $ERR
820		printf "\n"
821	fi
822fi
823
824# Check special files.
825# Check system binaries.
826#
827# Create the mtree tree specifications using:
828#	mtree -cx -pDIR -kmd5,uid,gid,mode,nlink,size,link,time > DIR.secure
829#	chown root:wheel DIR.secure
830#	chmod u+r,go= DIR.secure
831#
832# Note, this is not complete protection against Trojan horsed binaries, as
833# the hacker can modify the tree specification to match the replaced binary.
834# For details on really protecting yourself against modified binaries, see
835# the mtree(8) manual page.
836#
837if checkyesno check_mtree; then
838	if checkyesno check_mtree_follow_symlinks; then
839		check_mtree_flags="-L"
840	else
841		check_mtree_flags=""
842	fi
843	mtree -e -l -p / $check_mtree_flags -f $SPECIALSPEC 3>&1 >$OUTPUT 2>&3 |
844		grep -v '^mtree: dev/tty: Device not configured$' >&2
845	if [ -s $OUTPUT ]; then
846		printf "\nChecking special files and directories.\n"
847		cat $OUTPUT
848	fi
849
850	for file in /etc/mtree/*.secure; do
851		[ $file = '/etc/mtree/*.secure' ] && continue
852		tree=$(sed -n -e '3s/.* //p' -e 3q $file)
853		mtree $check_mtree_flags -f $file -p $tree > $TMP1
854		if [ -s $TMP1 ]; then
855			printf "\nChecking $tree:\n"
856			cat $TMP1
857		fi
858	done > $OUTPUT
859	if [ -s $OUTPUT ]; then
860		printf "\nChecking system binaries:\n"
861		cat $OUTPUT
862	fi
863fi
864
865# Backup disklabels of available disks
866#
867if checkyesno check_disklabels; then
868		# migrate old disklabels
869	for file in $(ls -1d $backup_dir/$backup_dir/disklabel.* \
870	    $backup_dir/disklabel.* 2>/dev/null); do
871		migrate_file "$file" "$work_dir/${file##*/}"
872	done
873
874		# generate list of old disklabels, fdisks & wedges and remove them
875	ls -1d $work_dir/disklabel.* $work_dir/fdisk.* $work_dir/wedges.* 2>/dev/null |
876	    egrep -v '\.(backup|current)(,v)?$' > $LABELS
877	xargs rm < $LABELS
878
879		# generate disklabels of all disks excluding:	cd dk fd md st
880	disks=$(iostat -x | awk 'NR > 1 && $1 !~ /^[cfm]d|dk|st|nfs/ { print $1; }')
881	for i in $disks; do
882		disklabel $i > "$work_dir/disklabel.$i" 2>/dev/null
883	done
884
885		# if fdisk is available, generate fdisks for:	ed ld sd wd
886	if [ -x /sbin/fdisk ]; then
887		disks=$(iostat -x | awk 'NR > 1 && $1 ~ /^[elsw]d/ { print $1; }')
888		for i in $disks; do
889			/sbin/fdisk $i > "$work_dir/fdisk.$i" 2>/dev/null
890		done
891	fi
892
893		# if dkctl is available, generate dkctl listwedges for:	ed ld sd wd cgd ofdisk ra rl raid
894	if [ -x /sbin/dkctl ]; then
895		disks=$(iostat -x | awk 'NR > 1 && $1 ~ /^[elsw]d|cgd|ofdisk|r[al]|raid/ { print $1; }')
896		for i in $disks; do
897			/sbin/dkctl $i listwedges > "$work_dir/wedges.$i" 2>/dev/null
898		done
899	fi
900
901		# append list of new disklabels, fdisks and wedges
902	ls -1d $work_dir/disklabel.* $work_dir/fdisk.* $work_dir/wedges.* 2>/dev/null |
903	    egrep -v '\.(backup|current)(,v)?$' >> $LABELS
904	CHANGELIST="$LABELS $CHANGELIST"
905fi
906
907if checkyesno check_lvm; then
908    
909    # generate list of existing LVM elements Physical Volumes, Volume Groups and Logical Volumes.
910if [ -x /sbin/lvm ]; then
911    lvm pvdisplay -m >"$work_dir/lvm.pv" 2>/dev/null
912    lvm vgdisplay -m >"$work_dir/lvm.vg" 2>/dev/null
913    lvm lvdisplay -m >"$work_dir/lvm.lv" 2>/dev/null
914fi
915    ls -1d $work_dir/lvm.* 2>/dev/null |
916        egrep -v '\.(backup|current)(,v)?$'>> $LVM_LABELS 
917    CHANGELIST="$CHANGELIST $LVM_LABELS"
918fi
919
920# Check for changes in the list of installed pkgs
921#
922if checkyesno check_pkgs && have_pkgs; then
923	pkgs=$work_dir/pkgs
924	migrate_file "$backup_dir/pkgs" "$pkgs"
925	pkg_dbdir=$(pkg_admin config-var PKG_DBDIR)
926	: ${pkg_dbdir:=/var/db/pkg}
927	(	cd $pkg_dbdir
928		$pkg_info | sort
929		echo ""
930		find . \( -name +REQUIRED_BY -o -name +CONTENTS \) -print0 |
931			xargs -0 ls -ldgTq | sort -t. +1 | sed -e 's, \./, ,'
932	 ) > $pkgs
933	echo "$pkgs" > $PKGS
934	CHANGELIST="$PKGS $CHANGELIST"
935fi
936
937# List of files that get backed up and checked for any modifications.
938# Any changes cause the files to rotate.
939#
940if checkyesno check_changelist ; then
941	mtree -D -k type -f $SPECIALSPEC -E exclude |
942	    sed '/^type=file/!d ; s/type=file \.//' | unvis > $CHANGEFILES
943
944	(
945		# Add other files which might dynamically exist:
946		#	/etc/ifconfig.*
947		#	/etc/raid*.conf
948		#	/etc/rc.d/*
949		#	/etc/rc.conf.d/*
950		#
951		echo "/etc/ifconfig.*"
952		echo "/etc/raid*.conf"
953		echo "/etc/rc.d/*"
954		echo "/etc/rc.conf.d/*"
955		echo "/etc/lvm/backup/*"
956		echo "/etc/lvm/archive/*"
957
958		# Add /etc/changelist
959		#
960		if [ -s /etc/changelist ]; then
961			grep -v '^#' /etc/changelist
962		fi
963	) | while read file; do
964		case "$file" in
965		*[\*\?\[]*)	# If changelist line is a glob ...
966				# ... expand possible backup files
967				#
968			ls -1d $(echo $backup_dir/${file}.current) 2>/dev/null \
969			    | sed "s,^$backup_dir/,, ; s,\.current$,,"
970				
971				# ... expand possible files
972				#
973			ls -1d $(echo $file) 2>/dev/null
974			;;
975		*)
976				# Otherwise, just print the filename
977			echo $file
978			;;
979		esac
980	done >> $CHANGEFILES
981	CHANGELIST="$CHANGEFILES $CHANGELIST"
982fi
983
984# Special case backups, including the master password file and
985# ssh private host keys. The normal backup mechanisms for
986# $check_changelist (see below) also print out the actual file
987# differences and we don't want to do that for these files
988#
989echo $MP > $TMP1			# always add /etc/master.passwd
990mtree -D -k type -f $SPECIALSPEC -I nodiff |
991    sed '/^type=file/!d ; s/type=file \.//' | unvis >> $TMP1
992grep -v '^$' $TMP1 | sort -u > $TMP2
993
994while read file; do
995	backup_and_diff "$file" no
996done < $TMP2
997
998
999if [ -n "$CHANGELIST" ]; then
1000	grep -h -v '^$' $CHANGELIST | sort -u > $TMP1
1001	comm -23 $TMP1 $TMP2 | while read file; do
1002		backup_and_diff "$file" yes
1003	done
1004fi
1005
1006if have_pkgs; then
1007	if checkyesno check_pkg_vulnerabilities; then
1008		pkg_admin ${_compat_K_flag} audit >${OUTPUT} 2>&1
1009		if [ -s ${OUTPUT} ]; then
1010			printf "\nInstalled vulnerable packages:\n"
1011			cat ${OUTPUT}
1012		fi
1013	fi
1014
1015	if checkyesno check_pkg_signatures; then
1016		pkg_admin ${_compat_K_flag} check >${OUTPUT} 2>&1
1017		if [ $? -ne 0 ]; then
1018			printf "\nFiles with invalid signatures:\n"
1019			cat ${OUTPUT}
1020		fi
1021	fi
1022fi
1023
1024if [ -f /etc/security.local ]; then
1025	. /etc/security.local > $OUTPUT 2>&1
1026	if [ -s $OUTPUT ] ; then
1027		printf "\nRunning /etc/security.local:\n"
1028		cat $OUTPUT
1029	fi
1030fi
1031