xref: /openbsd/libexec/security/security (revision c5d0954b)
1#!/usr/bin/perl -T
2
3# $OpenBSD: security,v 1.43 2024/06/09 18:31:17 afresh1 Exp $
4#
5# Copyright (c) 2011, 2012, 2014, 2015 Ingo Schwarze <schwarze@openbsd.org>
6# Copyright (c) 2011 Andrew Fresh <andrew@afresh1.com>
7#
8# Permission to use, copy, modify, and distribute this software for any
9# purpose with or without fee is hereby granted, provided that the above
10# copyright notice and this permission notice appear in all copies.
11#
12# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19
20use warnings;
21use strict;
22
23use Digest::SHA qw(sha256_hex);
24use Errno qw(ENOENT);
25use Fcntl qw(O_RDONLY O_NONBLOCK :mode);
26use File::Basename qw(basename);
27use File::Compare qw(compare);
28use File::Copy qw(copy);
29require File::Find;
30
31use constant {
32	BACKUP_DIR => '/var/backups/',
33	RELINK_DIR => '/usr/share/relink/',
34};
35
36$ENV{PATH} = '/bin:/usr/bin:/sbin:/usr/sbin';
37delete $ENV{ENV};
38umask 077;
39
40my $check_title;
41my $return_code = 0;
42
43sub nag ($$) {
44	my ($cond, $msg) = @_;
45	if ($cond) {
46		if ($check_title) {
47			print "\n$check_title\n";
48			undef $check_title;
49		}
50		print "$msg\n";
51		$return_code = 1;
52	}
53	return $cond;
54}
55
56sub close_or_nag {
57	my ($fh, $cmd) = @_;
58	my $res = close $fh;
59	nag !$res, "$cmd: " .
60	    ($! ? "error closing pipe: $!" : "exit code " . ($? >> 8));
61	return $res;
62}
63
64sub check_access_file {
65	my ($filename, $login) = @_;
66	return unless -e $filename;
67	my $mode = (stat(_))[2];
68	nag $mode & (S_IRUSR | S_IRGRP | S_IROTH) && ! -O $filename,
69	    "Login $login is off but still has a valid shell " .
70	    "and alternate access files in\n" .
71	    "\t home directory are still readable.";
72}
73
74sub check_passwd {
75	my $filename = '/etc/master.passwd';
76	$check_title = "Checking the $filename file:";
77	nag !(open my $fh, '<', $filename), "open: $filename: $!" and return;
78	my (%logins, %uids);
79	while (my $line = <$fh>) {
80		chomp $line;
81		nag $line !~ /\S/,
82		    "Line $. is a blank line."
83		    and next;
84		my @f = split /:/, $line, -1;
85		nag @f != 10,
86		    "Line $. has the wrong number of fields:\n$line";
87		my ($name, $pwd, $uid, $gid, $class, $chg, $exp, $gecos,
88		    $home, $shell) = @f;
89		next if $name =~ /^[+-]/;  # skip YP lines
90		unless (nag $name eq '',
91		    "Line $. has an empty login field:\n$line") {
92			nag $name !~ /^[A-Za-z0-9_][-.A-Za-z0-9_]*\$?$/,
93			    "Login $name has non-alphanumeric characters.";
94			nag $logins{$name}++,
95			    "Duplicate user name $name.";
96		}
97		nag length $name > 31,
98		    "Login $name has more than 31 characters.";
99		nag $pwd eq '' && !($name eq 'anoncvs' &&
100				    $shell =~ /\/anoncvssh$/),
101		    "Login $name has no password.";
102		if ($pwd ne '' &&
103		    $pwd ne 'skey' &&
104		    length $pwd != 13 &&
105		    $pwd !~ /^\$[0-9a-f]+\$/ &&
106		    ($shell eq '' || $shell =~ /sh$/)) {
107			nag -s "/etc/skey/$name",
108			    "Login $name is off but still has a valid " .
109			    "shell and an entry in /etc/skey.";
110			nag -d $home && ! -r $home,
111			    "Login $name is off but still has valid " .
112			    "shell and home directory is unreadable\n" .
113			    "\t by root; cannot check for existence " .
114			    "of alternate access files."
115			or check_access_file "$home/.$_", $name
116			    foreach qw(ssh rhosts shosts);
117		}
118		nag $uid == 0 && $name ne 'root',
119		    "Login $name has a user ID of 0.";
120		nag $uid < 0,
121		    "Login $name has a negative user ID.";
122		nag $uids{$uid}++,
123		    "Login $name has duplicate user ID $uid.";
124		nag $gid < 0,
125		    "Login $name has a negative group ID.";
126		nag $exp != 0 && $exp < time,
127		    "Login $name has expired.";
128	}
129	close $fh;
130}
131
132# Backup the master password file; a special case, the normal backup
133# mechanisms also print out file differences and we don't want to do
134# that because this file has encrypted passwords in it.
135sub backup_passwd {
136	my $base = 'master.passwd';
137	my $orig = "/etc/$base";
138	my $curr = BACKUP_DIR . "$base.current";
139	if (!-s $curr) {
140		# nothing
141	} elsif (compare $curr, $orig) {
142		copy $curr, BACKUP_DIR . "$base.backup";
143	} else {
144		return;
145	}
146	copy $orig, $curr;
147	chown 0, 0, $curr;
148}
149
150# Check the group file syntax.
151sub check_group {
152	my $filename = '/etc/group';
153	$check_title = "Checking the $filename file:";
154	nag !(open my $fh, '<', $filename), "open: $filename: $!" and return;
155	my (%names, $global_yp);
156	while (my $line = <$fh>) {
157		chomp $line;
158		nag $global_yp,
159		    'Global YP inclusion ("+") is not the last line.'
160		    and undef $global_yp;
161		if ($line eq '+') {
162			$global_yp = 1;
163			next;
164		}
165		nag $line !~ /\S/,
166		    "Line $. is a blank line."
167		    and next;
168		my @f = split /:/, $line, -1;
169		nag @f != 4,
170		    "Line $. has the wrong number of fields:\n$line";
171		my ($name, $pwd, $gid, $members) = @f;
172		next if $name =~ /^[+-]/;  # skip YP lines
173		unless (nag $name eq '',
174		    "Line $. has an empty group name field:\n$line") {
175			nag $name !~ /^[A-Za-z0-9_][-.A-Za-z0-9_]*$/,
176			    "Group $name has non-alphanumeric characters.";
177			nag $names{$name}++,
178			    "Duplicate group name $name.";
179		}
180		nag length $name > 31,
181		    "Group $name has more than 31 characters.";
182		nag $gid =~ /[^\d]/,
183		    "Group $name has an invalid group ID.";
184	}
185	close $fh;
186}
187
188sub check_umask {
189	my ($filename) = @_;
190	nag !(open my $fh, '<', $filename), "open: $filename: $!" and return;
191	my $umaskset;
192	while (<$fh>) {
193		next unless /^\s*umask\s+([0-7]+)/;
194		my $umask = "0$1";
195		$umaskset = 1;
196		my ($other, $group) = reverse split '', $umask;
197		nag $group =~ /^[0145]$/,
198		    "Root umask is group writable";
199		nag $other =~ /^[0145]$/,
200		    "Root umask is other writable";
201	}
202	close $fh;
203	return $umaskset;
204}
205
206# This type of test by spawning a shell is messy and fragile.
207# Instead, consider modifying the shells to warn about '.' in the PATH.
208sub check_root_path {
209	my ($path, $filename) = @_;
210	nag !(defined $path && $path =~ s/^PATH=[:\s]*//),
211	    "Failed to find PATH in $filename."
212	    and return;
213	foreach my $dir (split /[:\s]+/, $path) {
214		nag $dir eq '.', "The root path includes ." and next;
215		next unless -d $dir;
216		my $mode = (stat(_))[2];
217		nag $mode & S_IWGRP,
218		    "Root path directory $dir is group writable.";
219		nag $mode & S_IWOTH,
220		    "Root path directory $dir is other writable.";
221	}
222}
223
224# Check for umask values and root paths in startup files.
225sub check_csh {
226	my @list = qw(/etc/csh.cshrc /etc/csh.login /root/.cshrc /root/.login);
227	$check_title = "Checking root csh paths, umask values:\n@list";
228
229	my $umaskset = 0;
230	foreach my $filename (@list) {
231		next unless -s $filename;
232		$umaskset = 1 if check_umask $filename;
233
234		nag !(open my $fh, '-|', qw(/bin/csh -f -c),
235			"eval 'source $filename' >& /dev/null; " .
236			"echo PATH=\$path"),
237		    "cannot spawn /bin/csh: $!"
238		    and next;
239		my @output = <$fh>;
240		close_or_nag $fh, "csh $filename" or next;
241		chomp @output;
242		check_root_path pop @output, $filename;
243	}
244	nag !$umaskset,
245	    "\nRoot csh startup files do not set the umask.";
246}
247
248sub check_sh {
249	my @list = qw(/etc/profile /root/.profile);
250	$check_title = "Checking root sh paths, umask values:\n@list";
251
252	my @env_path;
253	my $umaskset = 0;
254	foreach my $filename (@list) {
255		next unless -s $filename;
256		$umaskset ||= check_umask($filename);
257
258		nag !(open my $fh, '-|', qw(/bin/sh -c),
259			". $filename; echo ENV=\$ENV; echo PATH=\$PATH"),
260		    "cannot spawn /bin/sh: $!"
261		    and next;
262		my @output = <$fh>;
263		close_or_nag $fh, "sh $filename" or next;
264		chomp @output;
265		check_root_path pop @output, $filename;
266
267		my $env = pop @output;
268		nag !(defined $env && $env =~ /^ENV=\s*(\S*)/),
269		    "Failed to find ENV in $filename."
270		    and next;
271		push @env_path, $1 if $1 ne '';
272	}
273	nag !$umaskset,
274	    "\nRoot sh startup files do not set the umask.";
275	return @env_path;
276}
277
278sub check_ksh {
279	my @list = ('/etc/ksh.kshrc', @_);
280	$check_title = "Checking root ksh paths, umask values:\n@list";
281
282	# Usually, we are at HOME anyway, but for the ENV check, this
283	# is particularly important, so make sure we are really there.
284	chdir '/root';
285
286	# A good .kshrc will not have a umask or path,
287	# that being set in .profile; check anyway.
288	foreach my $filename (@list) {
289		next unless -s $filename;
290		check_umask($filename);
291
292		nag !(open my $fh, '-|', qw(/bin/ksh -c),
293			". $filename; echo PATH=\$PATH"),
294		    "cannot spawn /bin/ksh: $!"
295		    and next;
296		my @output = <$fh>;
297		close_or_nag $fh, "ksh $filename" or next;
298		chomp @output;
299		check_root_path pop @output, $filename;
300	}
301}
302
303# Uudecode should not be in the /etc/mail/aliases file.
304sub check_mail_aliases {
305	my $filename = '/etc/mail/aliases';
306	nag !(open my $fh, '<', $filename), "open: $filename: $!" and return;
307	no warnings 'uninitialized';
308	nag /^((?:uu)?decode)/,
309	    "There is an entry for $1 in the $filename file."
310	    while <$fh>;
311	close $fh;
312}
313
314# hostname.if files may contain secrets and should not be world-readable.
315sub check_hostname_if {
316	while (my $filename = glob '/etc/hostname.*') {
317		next unless -e $filename;
318		my $mode = (stat(_))[2];
319		nag $mode & S_IRWXO,
320		    "$filename is world readable.";
321	}
322}
323
324# hosts.lpd should not have + signs.
325sub check_hosts_lpd {
326	my $filename = '/etc/hosts.lpd';
327	-s $filename or return;
328	nag !(open my $fh, '<', $filename), "open: $filename: $!" and return;
329	nag /^\+/ && !/^\+@/,
330	    "Plus sign in $filename file."
331	    while <$fh>;
332	close $fh;
333}
334
335sub find_homes {
336	my $filename = '/etc/passwd';
337	nag !(open my $fh, '<', $filename),
338	    "open: $filename: $!"
339	    and return [];
340	my $homes = [];
341	while (<$fh>) {
342		my $entry = [ @{[split /:/]}[0,2,5] ];
343		chomp;
344		nag !defined $entry->[2],
345		    "Incomplete line \"$_\" in $filename."
346		    and next;
347		chomp $entry->[2];
348		push @$homes, $entry;
349	}
350	close $fh;
351	return $homes;
352}
353
354# Check for special users with .rhosts/.shosts files.
355# Only root should have .rhosts/.shosts files.
356sub check_rhosts_owner {
357	my ($name, $uid, $home) = @_;
358	return if $name =~ /^[+-]/;  # skip YP lines
359	foreach my $base (qw(rhosts shosts)) {
360		my $filename = "$home/.$base";
361		next unless -s $filename;
362		nag ! -O $filename &&
363		    ($name eq 'ftp' || ($uid < 100 && $name ne 'root')),
364		    "$filename is not owned by root.";
365	}
366}
367
368# Also, .rhosts/.shosts files should not have plus signs.
369sub check_rhosts_content {
370	my ($name, $uid, $home) = @_;
371	foreach my $base (qw(rhosts shosts)) {
372		my $filename = "$home/.$base";
373		next unless -s $filename;
374		nag !sysopen(my $fh, $filename, O_RDONLY | O_NONBLOCK),
375		    "open: $filename: $!"
376		    and next;
377		nag !(-f $fh),
378		    "$filename is not a regular file"
379		    and next;
380		local $_;
381		nag /^\+\s*$/,
382		    "$filename has + sign in it."
383		    while <$fh>;
384		close $fh;
385	}
386}
387
388# Home directories should not be owned by someone else or writeable.
389sub check_homedir {
390	my ($name, $uid, $home) = @_;
391	return if $name =~ /^[+-]/;  # skip YP lines
392	return unless -d $home;
393	my ($mode, $fuid) = (stat(_))[2,4];
394	nag $fuid && $fuid != $uid,
395	    "user $name home directory is owned by " .
396	    ((getpwuid $fuid)[0] // $fuid);
397	nag $mode & S_IWGRP,
398	    "user $name home directory is group writable";
399	nag $mode & S_IWOTH,
400	    "user $name home directory is other writable";
401}
402
403# Files that should not be owned by someone else or readable.
404sub check_dot_readable {
405	my ($name, $uid, $home) = @_;
406	return if $name =~ /^[+-]/;  # skip YP lines
407	foreach my $f (qw(
408	    .netrc .rhosts .gnupg/secring.gpg .gnupg/random_seed
409	    .pgp/secring.pgp .shosts .ssh/identity .ssh/id_dsa .ssh/id_ecdsa
410	    .ssh/id_rsa .ssh/id_ed25519
411	)) {
412		next unless -e "$home/$f";
413		my ($mode, $fuid) = (stat(_))[2,4];
414		nag $fuid && $fuid != $uid,
415		    "user $name $f file is owned by " .
416		    ((getpwuid $fuid)[0] // $fuid);
417		nag $mode & S_IRGRP,
418		    "user $name $f file is group readable";
419		nag $mode & S_IROTH,
420		    "user $name $f file is other readable";
421		nag $mode & S_IWGRP,
422		    "user $name $f file is group writable";
423		nag $mode & S_IWOTH,
424		    "user $name $f file is other writable";
425	}
426}
427
428# Files that should not be owned by someone else or writeable.
429sub check_dot_writeable {
430	my ($name, $uid, $home) = @_;
431	return if $name =~ /^[+-]/;  # skip YP lines
432	foreach my $f (qw(
433	    .bashrc .bash_profile .bash_login .bash_logout .cshrc
434	    .emacs .exrc .forward .fvwmrc .inputrc .kshrc .login
435	    .logout .nexrc .profile .screenrc .ssh .ssh/config
436	    .ssh/authorized_keys .ssh/authorized_keys2 .ssh/environment
437	    .ssh/known_hosts .ssh/rc .tcshrc .twmrc .xsession .xinitrc
438	    .Xdefaults .Xauthority
439        )) {
440		next unless -e "$home/$f";
441		my ($mode, $fuid) = (stat(_))[2,4];
442		nag $fuid && $fuid != $uid,
443		    "user $name $f file is owned by " .
444		    ((getpwuid $fuid)[0] // $fuid);
445		nag $mode & S_IWGRP,
446		    "user $name $f file is group writable";
447		nag $mode & S_IWOTH,
448		    "user $name $f file is other writable";
449	}
450}
451
452# Mailboxes should be owned by the user and unreadable.
453sub check_mailboxes {
454	my $dir = '/var/mail';
455	nag !(opendir my $dh, $dir), "opendir: $dir: $!" and return;
456	foreach my $name (readdir $dh) {
457		next if $name =~ /^\.\.?$/;
458		next if $name =~ /.\.lock$/;
459		my ($mode, $fuid, $fgid) = (stat "$dir/$name")[2,4,5];
460		unless (defined $mode) {
461			nag !$!{ENOENT}, "stat: $dir/$name: $!";
462			next;
463		}
464		my $fname = (getpwuid $fuid)[0] // $fuid;
465		my $gname = (getgrgid $fgid)[0] // $fgid;
466		nag $fname ne $name,
467		    "user $name mailbox is owned by $fname";
468		nag S_IMODE($mode) != (S_IRUSR | S_IWUSR),
469		    sprintf 'user %s mailbox is %s, group %s',
470		        $name, strmode($mode), $gname;
471	}
472	closedir $dh;
473}
474
475# File systems should not be globally exported.
476sub check_exports {
477	my $filename = '/etc/exports';
478	return unless -e $filename;
479	nag !(open my $fh, '<', $filename), "open: $filename: $!" and return;
480
481	LINE: while (<$fh>) {
482		chomp;
483		next if /^(?:#|$)/;
484
485		my @fs;
486		my $readonly = 0;
487		foreach (split) {
488			if (/^\//)                   { push @fs, $_; }
489			elsif ($_ eq '-ro')          { $readonly = 1; }
490			elsif (/^(?:[^-]|-network)/) { next LINE; }
491		}
492
493		nag 1, "File system @fs globally exported, "
494		    . ($readonly ? 'read-only.' : 'read-write.');
495	}
496	close $fh;
497}
498
499sub strmode_x {
500	my ($mode, $x, $s) = @_;
501	$x &= $mode;
502	$s &= $mode;
503	return ($x && $s) ? 's' : $x ? 'x' : $s ? 'S' : '-';
504}
505
506sub strmode {
507	my ($mode) = @_;
508
509	my %types = (
510		S_IFDIR,  'd',    # directory
511		S_IFCHR,  'c',    # character special
512		S_IFBLK,  'b',    # block special
513		S_IFREG,  '-',    # regular
514		S_IFLNK,  'l',    # symbolic link
515		S_IFSOCK, 's',    # socket
516		S_IFIFO,  'p',    # fifo
517	);
518
519	return
520	      ($types{ $mode & S_IFMT } || '?')
521	    . (($mode & S_IRUSR) ? 'r' : '-')
522	    . (($mode & S_IWUSR) ? 'w' : '-')
523	    . (strmode_x $mode, S_IXUSR, S_ISUID)
524	    . (($mode & S_IRGRP) ? 'r' : '-')
525	    . (($mode & S_IWGRP) ? 'w' : '-')
526	    . (strmode_x $mode, S_IXGRP, S_ISGID)
527	    . (($mode & S_IROTH) ? 'r' : '-')
528	    . (($mode & S_IWOTH) ? 'w' : '-')
529	    . (strmode_x $mode, S_IXOTH, S_ISVTX);
530}
531
532sub find_special_files {
533	my (%skip, @fs);
534
535	%skip = map { $_ => 1 } split ' ', $ENV{SUIDSKIP}
536	    if $ENV{SUIDSKIP};
537
538	# Add mount points of non-local file systems
539	# to the list of directories to skip.
540	nag !(open my $fh, '-|', 'mount'),
541	    "cannot spawn mount: $!"
542	    and return;
543	while (<$fh>) {
544		my ($path, $opt) = /\son\s+(.*?)\s+type\s+\w+(.*)/;
545		push @fs, $path if $path && $opt =~ /local/ &&
546		    !($opt =~ /nodev/ && $opt =~ /nosuid/);
547	}
548	close_or_nag $fh, "mount" or return;
549	return unless @fs;
550
551	my $setuid_files = {};
552	my $device_files = {};
553	my $uudecode_is_setuid = 0;
554
555	File::Find::find({no_chdir => 1, wanted => sub {
556
557		if ($skip{$_}) {
558			$File::Find::prune = 1;
559			return;
560		}
561
562		my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size,
563		    $atime, $mtime, $ctime, $blksize, $blocks) = lstat;
564		if (defined $dev) {
565			no warnings 'once';
566			if ($dev != $File::Find::topdev) {
567				$File::Find::prune = 1;
568				return;
569			}
570		} else {
571			nag !$!{ENOENT}, "stat: $_: $!";
572			return;
573		}
574
575		# SUID/SGID files
576		my $file = {};
577		if (-f _ && $mode & (S_ISUID | S_ISGID)) {
578			return if -e RELINK_DIR . $_;
579			$setuid_files->{$File::Find::name} = $file;
580			$uudecode_is_setuid = 1
581			    if basename($_) eq 'uudecode';
582		}
583
584		# Special Files
585		elsif (!-d _ && !-f _ && !-l _ && !-S _ && !-p _ ) {
586			$device_files->{$File::Find::name} = $file;
587			$file->{major} = (($rdev >> 8) & 0xff) . ',';
588			$file->{minor} = (($rdev >> 8) & 0xffff00) |
589			    ($rdev & 0xff);
590		} else {
591			return;
592		}
593
594		$file->{mode}    = $mode;
595		$file->{strmode} = strmode $mode;
596		$file->{nlink}   = $nlink;
597		$file->{user}    = (getpwuid $uid)[0] // $uid;
598		$file->{group}   = (getgrgid $gid)[0] // $gid;
599		$file->{size}    = $size;
600		@$file{qw(wday mon day time year)} =
601		    split ' ', localtime $mtime;
602	}}, @fs);
603
604	nag $uudecode_is_setuid, 'Uudecode is setuid.';
605	return $setuid_files, $device_files;
606}
607
608sub adjust_columns {
609	my (@table) = @_;
610
611	my @s;
612	foreach my $row (@table) {
613		for (0 .. $#$row) {
614			$s[$_] = length $row->[$_]
615			    if (!$s[$_] || length $row->[$_] > $s[$_]);
616		}
617	}
618	$s[-1] = '0';
619	my $fmt = join ' ', map { m/(\d+)/ && "%-$1s"} @s;
620
621	return map { sprintf $fmt, @$_ } @table;
622}
623
624# Display any changes in setuid/setgid files and devices.
625sub check_filelist {
626	my ($files, $mode) = @_;
627	my $current = BACKUP_DIR . "$mode.current";
628	my $backup  = BACKUP_DIR . "$mode.backup";
629	my @fields  = (
630	    qw(strmode nlink user group),
631	    $mode eq 'device' ?  qw(major minor) : 'size',
632	    qw(mon day time year)
633	);
634
635	my %current;
636	if (-s $current) {
637		nag !(open my $fh, '<', $current), "open: $current: $!"
638		    and return;
639		while (<$fh>) {
640			chomp;
641			my (%f, $file);
642			(@f{@fields}, $file) = split ' ', $_, @fields + 1;
643			$current{$file} = \%f;
644		}
645		close $fh;
646	}
647
648	my %changed;
649	foreach my $f (sort keys %$files) {
650		if (my $old = delete $current{$f}) {
651			next if $mode eq 'device' &&
652			    !S_ISBLK($files->{$f}{mode});
653			foreach my $k (@fields) {
654				next if $old->{$k} eq $files->{$f}{$k};
655				push @{$changed{changes}},
656				    [ @$old{@fields}, $f ],
657				    [ @{$files->{$f}}{@fields}, $f ];
658				last;
659			}
660			next;
661		}
662		push @{$changed{additions}}, [ @{$files->{$f}}{@fields}, $f ];
663	}
664	foreach my $f (sort keys %current) {
665		next if $mode eq 'setuid' && -e RELINK_DIR . $f;
666		push @{$changed{deletions}}, [ @{$current{$f}}{@fields}, $f ];
667	};
668
669	foreach my $k (qw( additions deletions changes )) {
670		next unless exists $changed{$k};
671		$mode = 'block device' if $mode eq 'device' && $k eq 'changes';
672		$check_title = (ucfirst $mode) . " $k:";
673		nag 1, $_ for adjust_columns @{$changed{$k}};
674	}
675
676	return if !%changed;
677	copy $current, $backup;
678
679	nag !(open my $fh, '>', $current), "open: $current: $!" and return;
680	print $fh "@{$files->{$_}}{@fields} $_\n" foreach sort keys %$files;
681	close $fh;
682}
683
684# Check for block and character disk devices that are readable or writeable
685# or not owned by root.operator.
686sub check_disks {
687	my ($files) = @_;
688
689	my $disk_re = qr/
690	    \/
691	    (?:ccd|dk|fd|hd|hk|hp|jb|kra|ra|rb|rd|rl|rx|rz|sd|up|vnd|wd|xd)
692	    \d+ [B-H]? [a-p]
693	    $
694	/x;
695
696	foreach my $file (sort keys %$files) {
697		next if $file !~ /$disk_re/;
698		my $f = $files->{$file};
699		nag $f->{user} ne 'root' || $f->{group} ne 'operator' ||
700			S_IMODE($f->{mode}) != (S_IRUSR | S_IWUSR | S_IRGRP),
701		    sprintf("Disk %s is user %s, group %s, permissions %s.",
702			$file, $f->{user}, $f->{group}, $f->{strmode});
703	}
704}
705
706# Check special files and system binaries.
707#
708# Create the mtree tree specifications using:
709#
710#       mtree -cx -p DIR -K sha256digest,type > /etc/mtree/DIR.secure
711#       chown root:wheel /etc/mtree/DIR.secure
712#       chmod 600 /etc/mtree/DIR.secure
713#
714# Note, this is not complete protection against Trojan horsed binaries, as
715# the hacker can modify the tree specification to match the replaced binary.
716# For details on really protecting yourself against modified binaries, see
717# the mtree(8) manual page.
718sub check_mtree {
719	nag !-d '/etc/mtree', '/etc/mtree is missing' and return;
720
721	if (open my $fh, '-|', qw(mtree -e -l -p / -f /etc/mtree/special)) {
722		nag 1, $_ for map { chomp; $_ } <$fh>;
723		close_or_nag $fh, "mtree special";
724	} else { nag 1, "cannot spawn mtree: $!"; }
725
726	while (my $filename = glob '/etc/mtree/*.secure') {
727		nag !(open my $fh, '<', $filename),
728		    "open: $filename: $!"
729		    and next;
730
731		my $tree;
732		while (<$fh>) {
733			last unless /^#/;
734			($tree) = /^#\s+tree:\s+(.*)/ and last;
735		}
736		next unless $tree;
737
738		$check_title = "Checking system binaries in $tree:";
739		nag !(open $fh, '-|', 'mtree', '-f', $filename, '-p', $tree),
740		    "cannot spawn mtree: $!"
741		    and next;
742		nag 1, $_ for map { chomp; $_ } <$fh>;
743		close_or_nag $fh, "mtree $filename";
744	}
745}
746
747sub diff {
748	nag !(open my $fh, '-|', qw(diff -ua), @_),
749	    "cannot spawn diff: $!"
750	    and return;
751	local $/;
752	my $diff = <$fh>;
753	{
754		close $fh and last;
755		nag $!, "diff: error closing pipe: $!" and last;
756		nag $? >> 8 > 1, "diff: exit code " . ($? >> 8);
757	}
758	return nag !!$diff, $diff;
759}
760
761sub backup_if_changed {
762	my ($orig) = @_;
763
764	my ($backup) = $orig =~ /(.*)/;
765	if (index $backup, BACKUP_DIR) {
766		$backup =~ s{^/}{};
767		$backup =~ s{/}{_}g;
768		$backup = BACKUP_DIR . $backup;
769	}
770	my $current = "$backup.current";
771	$backup .= '.backup';
772	my $last = -s $current ? $current : '/dev/null';
773	$orig    = '/dev/null' unless -s $orig;
774
775	diff $last, $orig or return;
776
777	if (-s $current) {
778		copy $current, $backup;
779		chown 0, 0, $backup;
780	}
781	if ($orig eq '/dev/null') {
782		unlink $current;
783	} else {
784		copy $orig, $current;
785		chown 0, 0, $current;
786	}
787}
788
789sub backup_digest {
790	my ($orig) = @_;
791
792	my ($backup) = $orig =~ m{^/?(.*)};
793	$backup =~ s{/}{_}g;
794	my $current = BACKUP_DIR . "$backup.current.sha256";
795	$backup = BACKUP_DIR . "$backup.backup.sha256";
796
797	my $digest_new = 0;
798	if (-s $orig) {
799		if (open my $fh, '<', $orig) {
800			binmode $fh;
801			local $/;
802			$digest_new = sha256_hex(<$fh>);
803			close $fh;
804		} else { nag 1, "open: $orig: $!"; }
805	}
806
807	my $digest_old = 0;
808	if (-s $current) {
809		if (open my $fh, '<', $current) {
810			$digest_old = <$fh>;
811			close $fh;
812			chomp $digest_old;
813		} else { nag 1, "open: $current: $!"; }
814	}
815
816	return if $digest_old eq $digest_new;
817
818	if ($digest_old && $digest_new) {
819		copy $current, $backup;
820		chown 0, 0, $backup;
821		chmod 0600, $backup;
822	} elsif ($digest_old) {
823		$check_title = "======\n$orig removed SHA-256 checksum\n======";
824		unlink $current;
825	} elsif ($digest_new) {
826		$check_title = "======\n$orig new SHA-256 checksum\n======";
827	}
828
829	if ($digest_new) {
830		if (open my $fh, '>', $current) {
831			print $fh "$digest_new\n";
832			close $fh;
833		} else { nag 1, "open: $current: $!\n"; }
834		chown 0, 0, $current;
835		chmod 0600, $current;
836	}
837
838	nag $digest_old, "OLD: $digest_old";
839	nag $digest_new, "NEW: $digest_new";
840}
841
842# List of files that get backed up and checked for any modifications.  Each
843# file is expected to have two backups, /var/backups/file.{current,backup}.
844# Any changes cause the files to rotate.
845sub check_changelist {
846	my $filename = '/etc/changelist';
847	-s $filename or return;
848	nag !(open my $fh, '<', $filename), "open: $filename: $!" and return;
849
850	my @relative;
851	while (<$fh>) {
852		next if /^(?:#|\s*$)/;
853		chomp;
854		my $plus = s/^\+//;
855		unless (/^\//) {
856			push @relative, $_;
857			next;
858		}
859		my $tilda = /~$/;
860
861		foreach (glob) {
862			next if $_ eq '/etc/master.passwd';
863			next if /~$/ && !$tilda;
864			next if -d $_;
865
866			if ($plus) {
867				$check_title =
868				    "======\n$_ SHA-256 checksums\n======";
869				backup_digest $_;
870			} else {
871				$check_title =
872				    "======\n$_ diffs (-OLD  +NEW)\n======";
873				backup_if_changed $_;
874			}
875		}
876	}
877	close $fh;
878
879	$check_title = "Skipped relative paths in changelist(5):";
880	nag 1, $_ foreach @relative;
881}
882
883# Make backups of the labels for any mounted disks
884# and produce diffs when they change.
885sub check_disklabels {
886	nag !(open my $fh, '-|', qw(df -ln)),
887	    "cannot spawn df: $!"
888	    and return;
889	my %disks;
890	@disks{map m{^/dev/(\w*\d*)[a-p]}, <$fh>} = ();
891	close_or_nag $fh, "df";
892
893	unless (nag !(open my $fh, '-|', qw(bioctl softraid0)),
894	    "cannot spawn bioctl: $!") {
895		@disks{map m{<(\w*\d*)[a-p]>}, <$fh>} = ();
896		close_or_nag $fh, "bioctl";
897	}
898
899	foreach my $disk (sort keys %disks) {
900		$check_title = "======\n$disk diffs (-OLD  +NEW)\n======";
901		my $filename = BACKUP_DIR . "disklabel.$disk";
902		system "disklabel $disk > $filename";
903		backup_if_changed $filename;
904		unlink $filename;
905	}
906}
907
908# Backup the list of installed packages and produce diffs when it changes.
909sub check_pkglist {
910	$check_title = "======\nPackage list changes (-OLD  +NEW)\n======";
911	my $filename = BACKUP_DIR . 'pkglist';
912	system "pkg_info > $filename 2>&1";
913	backup_if_changed $filename;
914	unlink $filename;
915}
916
917# main program
918check_passwd;
919backup_passwd;
920check_group;
921check_csh;
922check_ksh(check_sh);
923$check_title = "Checking configuration files:";
924check_mail_aliases;
925check_hostname_if;
926check_hosts_lpd;
927$check_title = "Checking for special users with .rhosts/.shosts files.";
928my $homes = find_homes;
929check_rhosts_owner @$_ foreach @$homes;
930$check_title = "Checking .rhosts/.shosts files syntax.";
931check_rhosts_content @$_ foreach @$homes;
932$check_title = "Checking home directories.";
933check_homedir @$_ foreach @$homes;
934$check_title = "Checking dot files.";
935check_dot_readable @$_ foreach @$homes;
936check_dot_writeable @$_ foreach @$homes;
937$check_title = "Checking mailbox ownership.";
938check_mailboxes;
939$check_title = "Checking for globally exported file systems.";
940check_exports;
941$check_title = "Setuid/device find errors:";
942my ($setuid_files, $device_files) = find_special_files;
943$check_title = "Checking setuid/setgid files and devices:";
944check_filelist $setuid_files, 'setuid' if $setuid_files;
945$check_title = "Checking disk ownership and permissions.";
946check_disks $device_files;
947check_filelist $device_files, 'device' if $device_files;
948$check_title = "Checking special files and directories.\n" .
949    "Output format is:\n\tfilename:\n\t\tcriteria (shouldbe, reallyis)";
950check_mtree;
951$check_title = "Backing up and comparing configuration files.";
952check_changelist;
953$check_title = "Checking disklabels of mounted disks:";
954check_disklabels;
955check_pkglist;
956exit $return_code;
957