#!/usr/local/bin/perl
# save_user.cgi
# Modify or create a webmin user

$| = 1;
require './acl-lib.pl';
&ReadParse();
@ulist = &list_users();
if ($in{'old'}) {
	$in{'name'} = $in{'old'} if (!$access{'rename'});
	&can_edit_user($in{'old'}) || &error($text{'save_euser'});
	foreach $u (@ulist) {
		$old = $u if ($u->{'name'} eq $in{'old'});
		}
	}
else {
	$access{'create'} || &error($text{'save_ecreate'});
	}
&error_setup($text{'save_err'});

$in{'name'} =~ /^[A-z0-9\-\_\.]+$/ ||
	&error(&text('save_ename', $in{'name'}));
$in{'name'} eq 'webmin' && &error($text{'save_enamewebmin'});
if (!$in{'old'} || $in{'old'} ne $in{'name'}) {
	foreach $u (@ulist, &list_groups()) {
		if ($u->{'name'} eq $in{'name'}) {
			&error(&text('save_edup', $in{'name'}));
			}
		}
	}

foreach $u (@ulist) {
	if ($u->{'name'} eq $base_remote_user) {
		$me = $u;
		}
	}

# Find the current group
if ($in{'old'}) {
	foreach $g (&list_groups()) {
		if (&indexof($in{'old'}, @{$g->{'members'}}) >= 0) {
			$oldgroup = $g;
			}
		}
	}

if ($in{'risk'}) {
	# Just store the skill and risk levels
	$user{'skill'} = $in{'skill'};
	$user{'risk'} = $in{'risk'};
	delete($user{'modules'});
	}
else {
	if (defined($in{'group'})) {
		# Check if group is allowed
		if ($access{'gassign'} ne '*') {
			local @gcan = split(/\s+/, $access{'gassign'});
			$in{'group'} && &indexof($in{'group'}, @gcan) >= 0 ||
			  !$in{'group'} && &indexof('_none', @gcan) >= 0 ||
			  $oldgroup && $oldgroup->{'name'} eq $in{'group'} ||
				&error($text{'save_egroup'});
			}

		# Store group membership
		@glist = &list_groups();
		($group) = grep { $_->{'name'} eq $in{'group'} } @glist;
		if ($in{'group'} ne ($oldgroup ? $oldgroup->{'name'} : '')) {
			# Group has changed - update the member lists
			if ($oldgroup) {
				$oldgroup->{'members'} =
					[ grep { $_ ne $in{'old'} }
					  @{$oldgroup->{'members'}} ];
				&modify_group($oldgroup->{'name'}, $oldgroup);
				}
			if ($group) {
				push(@{$group->{'members'}}, $in{'name'});
				&modify_group($in{'group'}, $group);
				}
			}
		}

	# Store manually selected modules
	@mcan = $access{'mode'} == 1 ? @{$me->{'modules'}} :
		$access{'mode'} == 2 ? split(/\s+/, $access{'mods'}) :
				       &list_modules();
	map { $mcan{$_}++ } @mcan;

	@mods = split(/\0/, $in{'mod'});
	foreach $m (@mods) {
		$mcan{$m} || &error(&text('save_emod', $m));
		}
	if ($in{'old'}) {
		# Add modules that this user already has, but were not
		# allowed to be changed or are not available for this OS
		foreach $m (@{$old->{'modules'}}) {
			push(@mods, $m) if (!$mcan{$m});
			}
		}
	if ($base_remote_user eq $in{'old'} &&
	    &indexof("acl", @mods) == -1 &&
	    (!$group || &indexof("acl", @{$group->{'modules'}}) == -1)) {
		&error($text{'save_edeny'});
		}

	if ($oldgroup) {
		# Remove modules from the old group
		@mods = grep { &indexof($_, @{$oldgroup->{'modules'}}) < 0 }
			     @mods;
		}

	if (!$in{'old'} && $access{'perms'}) {
		# Copy .acl files from creator to new user
		&copy_acl_files($me->{'name'}, $in{'name'}, $me->{'modules'});
		}

	if ($group) {
		# Add modules from group to list
		local @ownmods;
		foreach $m (@mods) {
			push(@ownmods, $m)
				if (&indexof($m, @{$group->{'modules'}}) < 0);
			}
		@mods = &unique(@mods, @{$group->{'modules'}});
		$user{'ownmods'} = \@ownmods;

		# Copy ACL files for group
		local $name = $in{'old'} ? $in{'old'} : $in{'name'};
		&copy_acl_files($in{'group'}, $name,
				[ @{$group->{'modules'}}, "" ]);
		}
	$user{'modules'} = \@mods;
	delete($user{'skill'});
	delete($user{'risk'});
	}

$salt = chr(int(rand(26))+65).chr(int(rand(26))+65);
$user{'name'} = $in{'name'};
$user{'lang'} = !$access{'lang'} ? $old->{'lang'} :
		$in{'lang_def'} ? undef : $in{'lang'};
$user{'theme'} = !$access{'theme'} ? $old->{'theme'} :
		 $in{'theme_def'} ? undef : $in{'theme'};
$user{'cert'} = !$access{'chcert'} ? $old->{'cert'} :
		$in{'cert_def'} ? undef : $in{'cert'};
$user{'notabs'} = !$access{'cats'} ? $old->{'notabs'} : $in{'notabs'};
$raddr = $ENV{'REMOTE_ADDR'};
if ($access{'ips'}) {
	if ($in{'ipmode'}) {
		@hosts = split(/\s+/, $in{"ips"});
		if (!@hosts) { &error($text{'save_enone'}); }
		foreach $h (@hosts) {
			if ($h =~ /^([0-9\.]+)\/([0-9\.]+)$/) {
				&check_ipaddress($1) ||
					&error(&text('save_enet', $1));
				&check_ipaddress($2) ||
					&error(&text('save_emask', $2));
				$i = $h;
				}
			elsif ($h =~ /^[0-9\.]+$/) {
				&check_ipaddress($h) ||
					&error(&text('save_eip', $h));
				$i = $h;
				}
			elsif ($h =~ /^\*\.(\S+)$/) {
				$i = $h;
				}
			elsif ($h eq 'LOCAL') {
				$i = 'LOCAL';
				}
			elsif (!($i = join('.',unpack("CCCC",inet_aton($h))))) {
				&error(&text('save_ehost', $h));
				}
			push(@ips, $i);
			}
		}
	if ($in{'ipmode'} == 1) {
		$user{'allow'} = join(" ", @ips);
		if ($old->{'name'} eq $base_remote_user &&
		    !&ip_match($raddr, @ips)) {
			&error(&text('save_eself', $raddr));
			}
		}
	elsif ($in{'ipmode'} == 2) {
		$user{'deny'} = join(" ", @ips);
		if ($old->{'name'} eq $base_remote_user &&
		    &ip_match($raddr, @ips)) {
			&error(&text('save_eself', $raddr));
			}
		}
	}
else {
	$user{'allow'} = $old->{'allow'};
	$user{'deny'} = $old->{'deny'};
	}
if ($in{'pass_def'} == 0) {
	# New password
	$in{'pass'} =~ /:/ && &error($text{'save_ecolon'});
	$salt = chr(int(rand(26))+65).chr(int(rand(26))+65);
	$user{'pass'} = crypt($in{'pass'}, $salt);
	$user{'sync'} = 0;
	}
elsif ($in{'pass_def'} == 1) {
	# No change in password
	$user{'pass'} = $in{'oldpass'};
	$user{'sync'} = 0;
	}
elsif ($in{'pass_def'} == 3) {
	# Unix authentication
	$user{'pass'} = 'x';
	$user{'sync'} = 0;
	}
elsif ($in{'pass_def'} == 4) {
	# Account is locked
	$user{'pass'} = '*LK*';
	$user{'sync'} = 0;
	}
elsif ($in{'pass_def'} == 5) {
	# External authentcation
	$user{'pass'} = 'e';
	$user{'sync'} = 0;
	}
else {
	# Password synchronization (deprecated)
	&foreign_check("useradmin") || &error($text{'save_eos'});
	&foreign_require("useradmin", "user-lib.pl");
	foreach $uu (&foreign_call("useradmin", "list_users")) {
		$user{'pass'} = $uu->{'pass'}
			if ($uu->{'user'} eq $in{'name'});
		}
	defined($user{'pass'}) ||
		&error(&text('save_eunix', $in{'name'}));
	if ($user{'pass'} =~ /^\$1\$/ && crypt("foo", "xx") !~ /^\$1\$/ &&
	    crypt('test', '$1$A9wB3O18$zaZgqrEmb9VNltWTL454R/') ne
		  '$1$A9wB3O18$zaZgqrEmb9VNltWTL454R/') {
		&error($text{'save_emd5'});
		}
	$user{'sync'} = 1;
	}

if ($in{'old'}) {
	# update user and all ACLs
	&modify_user($in{'old'}, \%user);
	foreach $u (&list_users()) {
		%uaccess = &get_module_acl($u->{'name'});
		local @au = split(/\s+/, $uaccess{'users'});
		local $idx = &indexof($in{'old'}, @au);
		if ($idx != -1) {
			$au[$idx] = $in{'name'};
			$uaccess{'users'} = join(" ", @au);
			&save_module_acl(\%uaccess, $u->{'name'});
			}
		}
	}
else {
	# create and add to access list
	&create_user(\%user, $in{'clone'});
	if ($access{'users'} ne '*') {
		$access{'users'} .= " ".$in{'name'};
		&save_module_acl(\%access);
		}
	#%aclacl = &get_module_acl();
	#&save_module_acl(\%aclacl, $in{'name'});
	}
&restart_miniserv();
delete($in{'pass'});
if ($in{'old'}) {
	&webmin_log("modify", "user", $in{'old'}, \%in);
	}
else {
	&webmin_log("create", "user", $user{'name'}, \%in);
	}
&redirect("");

# ip_match(ip, [match]+)
# Checks an IP address against a list of IPs, networks and networks/masks
sub ip_match
{
local(@io, @mo, @ms, $i, $j);
@io = split(/\./, $_[0]);
local $hn = gethostbyaddr(inet_aton($_[0]), AF_INET);
undef($hn) if ((&to_ipaddress($hn))[0] ne $_[0]);
for($i=1; $i<@_; $i++) {
	local $mismatch = 0;
	if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
		# Compare with network/mask
		@mo = split(/\./, $1); @ms = split(/\./, $2);
		for($j=0; $j<4; $j++) {
			if ((int($io[$j]) & int($ms[$j])) != int($mo[$j])) {
				$mismatch = 1;
				}
			}
		}
	elsif ($_[$i] =~ /^\*(\.\S+)$/) {
		# Compare with hostname regexp
		$mismatch = 1 if ($hn !~ /$1$/);
		}
	elsif ($_[$i] eq 'LOCAL') {
		# Just assume OK for now
		}
	else {
		# Compare with IP or network
		@mo = split(/\./, $_[$i]);
		while(@mo && !$mo[$#mo]) { pop(@mo); }
		for($j=0; $j<@mo; $j++) {
			if ($mo[$j] != $io[$j]) {
				$mismatch = 1;
				}
			}
		}
	return 1 if (!$mismatch);
	}
return 0;
}

