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