auth.inc 20.6 KB
Newer Older
Ad Schellevis's avatar
Ad Schellevis committed
1 2
<?php

3 4 5
/*
	Copyright (C) 2014 Deciso B.V.
	Copyright (C) 2010 Ermal Luçi
Ad Schellevis's avatar
Ad Schellevis committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
	Copyright (C) 2007, 2008 Scott Ullrich <sullrich@gmail.com>
        Copyright (C) 2005-2006 Bill Marquette <bill.marquette@gmail.com>
        Copyright (C) 2006 Paul Taylor <paultaylor@winn-dixie.com>.
        Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>.
        All rights reserved.

        Redistribution and use in source and binary forms, with or without
        modification, are permitted provided that the following conditions are met:

        1. Redistributions of source code must retain the above copyright notice,
           this list of conditions and the following disclaimer.

        2. Redistributions in binary form must reproduce the above copyright
           notice, this list of conditions and the following disclaimer in the
           documentation and/or other materials provided with the distribution.

        THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
        INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
        AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
        AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
        OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
        SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
        INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
        CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
        ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
        POSSIBILITY OF SUCH DAMAGE.
*/

/*
 * NOTE : Portions of the mschapv2 support was based on the BSD licensed CHAP.php
 * file courtesy of Michael Retterklieber.
 */
38

39
/* include globals from notices.inc /utility/XML parser files */
40 41
require_once("interfaces.inc");
require_once("util.inc");
42

Ad Schellevis's avatar
Ad Schellevis committed
43 44 45
// Will be changed to false if security checks fail
$security_passed = true;

46
/* If this function doesn't exist, we're being called from Captive Portal or
Ad Schellevis's avatar
Ad Schellevis committed
47 48
   another internal subsystem which does not include authgui.inc */
if (function_exists("display_error_form") && !isset($config['system']['webgui']['nodnsrebindcheck'])) {
49
	/* DNS ReBinding attack prevention */
Ad Schellevis's avatar
Ad Schellevis committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
	$found_host = false;

	/* Either a IPv6 address with or without a alternate port */
	if(strstr($_SERVER['HTTP_HOST'], "]")) {
		$http_host_port = explode("]", $_SERVER['HTTP_HOST']);
		/* v6 address has more parts, drop the last part */
		if(count($http_host_port) > 1) {
			array_pop($http_host_port);
			$http_host = str_replace(array("[", "]"), "", implode(":", $http_host_port));
		} else {
			$http_host = str_replace(array("[", "]"), "", implode(":", $http_host_port));
		}
	} else {
		$http_host = explode(":", $_SERVER['HTTP_HOST']);
		$http_host = $http_host[0];
	}
	if(is_ipaddr($http_host) or $_SERVER['SERVER_ADDR'] == "127.0.0.1" or
			strcasecmp($http_host, "localhost") == 0 or $_SERVER['SERVER_ADDR'] == "::1")
		$found_host = true;
	if(strcasecmp($http_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 or
			strcasecmp($http_host, $config['system']['hostname']) == 0)
		$found_host = true;

73
	if(isset($config['dyndnses']['dyndns']) && is_array($config['dyndnses']['dyndns']) && !$found_host)
Ad Schellevis's avatar
Ad Schellevis committed
74 75 76 77 78 79
		foreach($config['dyndnses']['dyndns'] as $dyndns)
			if(strcasecmp($dyndns['host'], $http_host) == 0) {
				$found_host = true;
				break;
			}

80
	if(isset($config['dnsupdates']['dnsupdate']) && is_array($config['dnsupdates']['dnsupdate']) && !$found_host)
Ad Schellevis's avatar
Ad Schellevis committed
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
		foreach($config['dnsupdates']['dnsupdate'] as $rfc2136)
			if(strcasecmp($rfc2136['host'], $http_host) == 0) {
				$found_host = true;
				break;
			}

	if(!empty($config['system']['webgui']['althostnames']) && !$found_host) {
		$althosts = explode(" ", $config['system']['webgui']['althostnames']);
		foreach ($althosts as $ah)
			if(strcasecmp($ah, $http_host) == 0 or strcasecmp($ah, $_SERVER['SERVER_ADDR']) == 0) {
				$found_host = true;
				break;
			}
	}

	if($found_host == false) {
		if(!security_checks_disabled()) {
			display_error_form("501", gettext("Potential DNS Rebind attack detected, see http://en.wikipedia.org/wiki/DNS_rebinding<br />Try accessing the router by IP address instead of by hostname."));
			exit;
		}
		$security_passed = false;
	}
}

// If the HTTP_REFERER is something other than ourselves then disallow.
if(function_exists("display_error_form") && !isset($config['system']['webgui']['nohttpreferercheck'])) {
107
	if(isset($_SERVER['HTTP_REFERER'])) {
108 109 110
		if(file_exists('/tmp/setupwizard_lastreferrer')) {
			if($_SERVER['HTTP_REFERER'] == file_get_contents('/tmp/setupwizard_lastreferrer')) {
				unlink('/tmp/setupwizard_lastreferrer');
Ad Schellevis's avatar
Ad Schellevis committed
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
				header("Refresh: 1; url=index.php");
				echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n        \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
				echo "<html><head><title>" . gettext("Redirecting...") . "</title></head><body>" . gettext("Redirecting to the dashboard...") . "</body></html>";
				exit;
			}
		}
		$found_host = false;
		$referrer_host = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
		$referrer_host = str_replace(array("[", "]"), "", $referrer_host);
		if($referrer_host) {
			if(strcasecmp($referrer_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0
					|| strcasecmp($referrer_host, $config['system']['hostname']) == 0)
				$found_host = true;

			if(!empty($config['system']['webgui']['althostnames']) && !$found_host) {
				$althosts = explode(" ", $config['system']['webgui']['althostnames']);
				foreach ($althosts as $ah) {
					if(strcasecmp($referrer_host, $ah) == 0) {
						$found_host = true;
						break;
					}
				}
			}

135
			if(isset($config['dyndnses']['dyndns']) && is_array($config['dyndnses']['dyndns']) && !$found_host)
Ad Schellevis's avatar
Ad Schellevis committed
136 137 138 139 140 141
				foreach($config['dyndnses']['dyndns'] as $dyndns)
					if(strcasecmp($dyndns['host'], $referrer_host) == 0) {
						$found_host = true;
						break;
					}

142
			if(isset($config['dnsupdates']['dnsupdate']) && is_array($config['dnsupdates']['dnsupdate']) && !$found_host)
Ad Schellevis's avatar
Ad Schellevis committed
143 144 145 146 147 148 149
				foreach($config['dnsupdates']['dnsupdate'] as $rfc2136)
					if(strcasecmp($rfc2136['host'], $referrer_host) == 0) {
						$found_host = true;
						break;
					}

			if(!$found_host) {
150
				$found_host = isAuthLocalIP($referrer_host);
Ad Schellevis's avatar
Ad Schellevis committed
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
				if($referrer_host == "127.0.0.1" || $referrer_host == "localhost") {
					// allow SSH port forwarded connections and links from localhost
					$found_host = true;
				}
			}
		}
		if($found_host == false) {
			if(!security_checks_disabled()) {
				display_error_form("501", "An HTTP_REFERER was detected other than what is defined in System -> Advanced (" . htmlspecialchars($_SERVER['HTTP_REFERER']) . ").  You can disable this check if needed in System -> Advanced -> Admin.");
				exit;
			}
			$security_passed = false;
		}
	} else
		$security_passed = false;
}

Ad Schellevis's avatar
Ad Schellevis committed
168
if (function_exists("display_error_form") && $security_passed) {
Ad Schellevis's avatar
Ad Schellevis committed
169 170
	/* Security checks passed, so it should be OK to turn them back on */
	restore_security_checks();
Ad Schellevis's avatar
Ad Schellevis committed
171
}
Ad Schellevis's avatar
Ad Schellevis committed
172 173 174 175 176
unset($security_passed);

$groupindex = index_groups();
$userindex = index_users();

177 178 179 180 181 182 183 184 185 186

/**
 * check if $http_host is a local configured ip address
 */
function isAuthLocalIP($http_host)
{
    global $config;
    $interface_list_ips = get_configured_ip_addresses();
    foreach ($interface_list_ips as $ilips) {
        if (strcasecmp($http_host, $ilips) == 0) {
187
            return true;
188 189
        }
    }
190 191 192 193
    $interface_list_ipv6s = get_configured_ipv6_addresses();
    foreach ($interface_list_ipv6s as $ilipv6s) {
        if (strcasecmp($http_host, $ilipv6s) == 0) {
            return true;
194
        }
195 196 197 198 199
    }
    if (isset($config['virtualip']['vip'])) {
        foreach ($config['virtualip']['vip'] as $vip) {
            if ($vip['subnet'] == $http_host) {
                return true;
200 201 202
            }
        }
    }
203
		return false;
204 205
}

206 207 208
function index_groups()
{
	global $config, $groupindex;
Ad Schellevis's avatar
Ad Schellevis committed
209 210 211

	$groupindex = array();

212
	if (isset($config['system']['group'])) {
Ad Schellevis's avatar
Ad Schellevis committed
213 214
		$i = 0;
		foreach($config['system']['group'] as $groupent) {
215 216 217 218
			if (isset($groupent['name'])) {
				$groupindex[$groupent['name']] = $i;
				$i++;
			}
Ad Schellevis's avatar
Ad Schellevis committed
219 220 221 222 223 224
		}
	}

	return ($groupindex);
}

225 226 227
function index_users()
{
	global $config;
Ad Schellevis's avatar
Ad Schellevis committed
228 229 230 231 232 233 234 235 236 237 238 239

	if (is_array($config['system']['user'])) {
		$i = 0;
		foreach($config['system']['user'] as $userent) {
			$userindex[$userent['name']] = $i;
			$i++;
		}
	}

	return ($userindex);
}

240 241 242
function &getUserEntry($name)
{
	global $config, $userindex;
243 244
	$false = false;
	if (isset($userindex[$name])) {
Ad Schellevis's avatar
Ad Schellevis committed
245
		return $config['system']['user'][$userindex[$name]];
246 247 248
	} else {
		return $false;
	}
Ad Schellevis's avatar
Ad Schellevis committed
249 250
}

251 252 253
function &getUserEntryByUID($uid)
{
	global $config;
Ad Schellevis's avatar
Ad Schellevis committed
254 255 256 257 258 259 260 261 262

	if (is_array($config['system']['user']))
		foreach ($config['system']['user'] as & $user)
			if ($user['uid'] == $uid)
				return $user;

	return false;
}

263 264 265 266 267
function &getGroupEntry($name)
{
	global $config, $groupindex;

	if (isset($groupindex[$name])) {
Ad Schellevis's avatar
Ad Schellevis committed
268
		return $config['system']['group'][$groupindex[$name]];
269
	}
Ad Schellevis's avatar
Ad Schellevis committed
270 271
}

272 273 274
function &getGroupEntryByGID($gid)
{
	global $config;
Ad Schellevis's avatar
Ad Schellevis committed
275

276
	if (isset($config['system']['group'])) {
277 278
		foreach ($config['system']['group'] as & $group) {
			if ($group['gid'] == $gid) {
Ad Schellevis's avatar
Ad Schellevis committed
279
				return $group;
280 281 282
			}
		}
	}
Ad Schellevis's avatar
Ad Schellevis committed
283 284 285 286

	return false;
}

287 288
function get_user_privileges(&$user)
{
289 290 291 292
        if (!isset($user['priv']) || !is_array($user['priv'])) {
             $privs = array();
	} else {
             $privs = $user['priv'];
293
	}
Ad Schellevis's avatar
Ad Schellevis committed
294 295 296 297 298

        $names = local_user_get_groups($user, true);

        foreach ($names as $name) {
                $group = getGroupEntry($name);
299
                if (isset($group['priv']) && is_array($group['priv'])) {
300 301
                        $privs = array_merge($privs, $group['priv']);
		}
Ad Schellevis's avatar
Ad Schellevis committed
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
        }

        return $privs;
}

function userHasPrivilege($userent, $privid = false) {

        if (!$privid || !is_array($userent))
                return false;

        $privs = get_user_privileges($userent);

        if (!is_array($privs))
                return false;

        if (!in_array($privid, $privs))
                return false;

        return true;
}


324 325 326 327
function local_sync_accounts()
{
	global $config;

Ad Schellevis's avatar
Ad Schellevis committed
328
	/* remove local users to avoid uid conflicts */
329
	$fd = popen('/usr/sbin/pw usershow -a', 'r');
Ad Schellevis's avatar
Ad Schellevis committed
330 331
	if ($fd) {
		while (!feof($fd)) {
332
			$line = explode(':',fgets($fd));
333
			if ( count($line) < 3 ||  !strncmp($line[0], '_', 1) || $line[2] < 2000 || $line[2] > 65000) {
Ad Schellevis's avatar
Ad Schellevis committed
334
				continue;
335
			}
Ad Schellevis's avatar
Ad Schellevis committed
336 337 338 339
			/*
			 * If a crontab was created to user, pw userdel will be interactive and
			 * can cause issues. Just remove crontab before run it when necessary
			 */
340 341
			@unlink("/var/cron/tabs/{$line[0]}");
			mwexecf('/usr/sbin/pw userdel -n %s', $line[0]);
Ad Schellevis's avatar
Ad Schellevis committed
342 343 344 345 346 347
		}
		pclose($fd);
	}

	/* remove local groups to avoid gid conflicts */
	$gids = array();
348
	$fd = popen('/usr/sbin/pw groupshow -a', 'r');
Ad Schellevis's avatar
Ad Schellevis committed
349 350
	if ($fd) {
		while (!feof($fd)) {
351
			$line = explode(':',fgets($fd));
352
			if (count($line) < 3 || !strncmp($line[0], '_', 1) || $line[2] < 2000 || $line[2] > 65000 ) {
Ad Schellevis's avatar
Ad Schellevis committed
353
				continue;
354
			}
355
			mwexecf('/usr/sbin/pw groupdel %s', $line[2]);
Ad Schellevis's avatar
Ad Schellevis committed
356 357 358 359 360 361 362 363 364
		}
		pclose($fd);
	}

	/* make sure the all group exists */
	$allgrp = getGroupEntryByGID(1998);
	local_group_set($allgrp, true);

	/* sync all local users */
365 366
	if (is_array($config['system']['user'])) {
		foreach ($config['system']['user'] as $user) {
Ad Schellevis's avatar
Ad Schellevis committed
367
			local_user_set($user);
368 369
		}
	}
Ad Schellevis's avatar
Ad Schellevis committed
370 371

	/* sync all local groups */
372 373
	if (is_array($config['system']['group'])) {
		foreach ($config['system']['group'] as $group) {
Ad Schellevis's avatar
Ad Schellevis committed
374
			local_group_set($group);
375 376
		}
	}
Ad Schellevis's avatar
Ad Schellevis committed
377 378
}

379 380
function local_user_set(&$user)
{
Ad Schellevis's avatar
Ad Schellevis committed
381
	if (empty($user['password'])) {
382 383 384 385
		log_error(sprintf(
			gettext('There is something wrong in your config because user %s password is missing!'),
			$user['name']
		));
Ad Schellevis's avatar
Ad Schellevis committed
386 387 388 389 390
		return;
	}

	$user_uid = $user['uid'];
	$user_name = $user['name'];
391 392 393 394
	$user_home = "/home/{$user_name}";
	$user_shell = '/sbin/nologin';
	$user_group = 'nobody';
	$lock_account = 'lock';
Ad Schellevis's avatar
Ad Schellevis committed
395

396 397 398 399 400 401
	@mkdir('/home', 0755);

	/* admins access gives wheely rights */
	if (userHasPrivilege($user, 'page-all')) {
		$user_group = 'wheel';
	}
Ad Schellevis's avatar
Ad Schellevis committed
402 403

	/* configure shell type */
404 405
	if (userHasPrivilege($user, 'user-shell-access')) {
		$user_shell = '/bin/csh';
Ad Schellevis's avatar
Ad Schellevis committed
406 407
	}

408 409 410
	/* unlock valid shell users */
	if (!is_account_disabled($user_name) && !is_account_expired($user_name)) {
		$lock_account = 'unlock';
Ad Schellevis's avatar
Ad Schellevis committed
411 412 413 414
	}

	/* root user special handling */
	if ($user_uid == 0) {
415 416 417 418
		$user_group = 'wheel';
		$user_home = '/root';
		$user_shell = '/usr/local/etc/rc.initial';
		$lock_account = 'unlock';
Ad Schellevis's avatar
Ad Schellevis committed
419 420 421 422 423 424 425 426 427
	}

	/* read from pw db */
	$fd = popen("/usr/sbin/pw usershow -n {$user_name} 2>&1", "r");
	$pwread = fgets($fd);
	pclose($fd);
	$userattrs = explode(":", trim($pwread));

	/* determine add or mod */
428
	if (($userattrs[0] != $user['name']) || (!strncmp($pwread, 'pw:', 3))) {
429
		$user_op = 'useradd -m -k /usr/share/skel -o';
Ad Schellevis's avatar
Ad Schellevis committed
430
	} else {
431
		$user_op = 'usermod';
Ad Schellevis's avatar
Ad Schellevis committed
432 433
	}

434
	$comment = str_replace(array(':', '!', '@'), ' ', $user['descr']);
Ad Schellevis's avatar
Ad Schellevis committed
435 436
	/* add or mod pw db */
	$cmd = "/usr/sbin/pw {$user_op} -q -u {$user_uid} -n {$user_name}".
437 438 439
		" -g {$user_group} -s {$user_shell} -d {$user_home}".
		" -c ".escapeshellarg($comment)." -H 0 2>&1";
	$fd = popen($cmd, 'w');
Ad Schellevis's avatar
Ad Schellevis committed
440 441 442 443
	fwrite($fd, $user['password']);
	pclose($fd);

	/* create user directory if required */
444
	@mkdir($user_home, 0700);
Ad Schellevis's avatar
Ad Schellevis committed
445 446 447 448
	@chown($user_home, $user_name);
	@chgrp($user_home, $user_group);

	/* write out ssh authorized key file */
449
	if (isset($user['authorizedkeys'])) {
450 451
		@mkdir("{$user_home}/.ssh", 0700);
		@chown("{$user_home}/.ssh", $user_name);
Ad Schellevis's avatar
Ad Schellevis committed
452 453 454
		$keys = base64_decode($user['authorizedkeys']);
		@file_put_contents("{$user_home}/.ssh/authorized_keys", $keys);
		@chown("{$user_home}/.ssh/authorized_keys", $user_name);
455 456 457
	} else {
		@unlink("{$user_home}/.ssh/authorized_keys");
	}
458

459
	mwexecf('/usr/sbin/pw %s %s', array($lock_account, $user_name), true);
Ad Schellevis's avatar
Ad Schellevis committed
460 461
}

462 463
function local_user_del($user)
{
Ad Schellevis's avatar
Ad Schellevis committed
464 465 466 467
	/* remove all memberships */
	local_user_set_groups($user);

	/* delete from pw db */
468
	mwexecf('/usr/sbin/pw userdel -n %s -r', $user['name']);
Ad Schellevis's avatar
Ad Schellevis committed
469 470 471 472 473

	/* Delete user from groups needs a call to write_config() */
	local_group_del_user($user);
}

474
function local_user_set_password(&$user, $password)
475 476
{
	$user['password'] = crypt($password, '$6$');
Ad Schellevis's avatar
Ad Schellevis committed
477 478 479 480 481 482 483 484 485 486

	// Converts ascii to unicode.
	$astr = (string) $password;
	$ustr = '';
	for ($i = 0; $i < strlen($astr); $i++) {
		$a = ord($astr{$i}) << 8;
		$ustr.= sprintf("%X", $a);
	}
}

487 488 489
function local_user_get_groups($user, $all = false)
{
	global $config;
Ad Schellevis's avatar
Ad Schellevis committed
490 491

	$groups = array();
492 493

	if (!isset($config['system']['group'])) {
Ad Schellevis's avatar
Ad Schellevis committed
494
		return $groups;
495
	}
Ad Schellevis's avatar
Ad Schellevis committed
496

497
	foreach ($config['system']['group'] as $group) {
498
		if (isset($group['member'])) {
499 500 501 502
			if (in_array($user['uid'], $group['member']) || ($group['name'] == "all" && $all)) {
				$groups[] = $group['name'];
			}
		}
503
	}
Ad Schellevis's avatar
Ad Schellevis committed
504 505 506 507

	sort($groups);

	return $groups;
508

Ad Schellevis's avatar
Ad Schellevis committed
509 510
}

511 512 513
function local_user_set_groups($user, $new_groups = null)
{
	global $config, $groupindex;
Ad Schellevis's avatar
Ad Schellevis committed
514

515
	if (!isset($config['system']['group'])) {
Ad Schellevis's avatar
Ad Schellevis committed
516
		return;
517
	}
Ad Schellevis's avatar
Ad Schellevis committed
518 519 520 521

	$cur_groups = local_user_get_groups($user, true);
	$mod_groups = array();

522
	if (!is_array($new_groups)) {
Ad Schellevis's avatar
Ad Schellevis committed
523
		$new_groups = array();
524
	}
Ad Schellevis's avatar
Ad Schellevis committed
525

526
	if (!is_array($cur_groups)) {
Ad Schellevis's avatar
Ad Schellevis committed
527
		$cur_groups = array();
528
	}
Ad Schellevis's avatar
Ad Schellevis committed
529 530 531

	/* determine which memberships to add */
	foreach ($new_groups as $groupname) {
532 533
		if (in_array($groupname,$cur_groups) || !isset($groupindex[$groupname])) {
			// continue if group is already in current list or the groupname is invalid
Ad Schellevis's avatar
Ad Schellevis committed
534
			continue;
535
		}
Ad Schellevis's avatar
Ad Schellevis committed
536 537 538 539 540 541 542
		$group = & $config['system']['group'][$groupindex[$groupname]];
		$group['member'][] = $user['uid'];
		$mod_groups[] = $group;
	}

	/* determine which memberships to remove */
	foreach ($cur_groups as $groupname) {
543
		if (in_array($groupname,$new_groups)) {
Ad Schellevis's avatar
Ad Schellevis committed
544
			continue;
545 546
		}
		if (!isset($config['system']['group'][$groupindex[$groupname]])) {
Ad Schellevis's avatar
Ad Schellevis committed
547
			continue;
548
		}
Ad Schellevis's avatar
Ad Schellevis committed
549 550 551 552 553 554 555 556 557
		$group = & $config['system']['group'][$groupindex[$groupname]];
		if (is_array($group['member'])) {
			$index = array_search($user['uid'], $group['member']);
			array_splice($group['member'], $index, 1);
			$mod_groups[] = $group;
		}
	}

	/* sync all modified groups */
558
	foreach ($mod_groups as $group) {
Ad Schellevis's avatar
Ad Schellevis committed
559
		local_group_set($group);
560
	}
Ad Schellevis's avatar
Ad Schellevis committed
561 562
}

563 564
function local_group_del_user($user)
{
Ad Schellevis's avatar
Ad Schellevis committed
565 566
	global $config;

567
	if (!isset($config['system']['group'])) {
Ad Schellevis's avatar
Ad Schellevis committed
568
                return;
569
	}
Ad Schellevis's avatar
Ad Schellevis committed
570 571

        foreach ($config['system']['group'] as $group) {
572
		if (isset($group['member'])) {
Ad Schellevis's avatar
Ad Schellevis committed
573
			foreach ($group['member'] as $idx => $uid) {
574
				if ($user['uid'] == $uid) {
Ad Schellevis's avatar
Ad Schellevis committed
575
					unset($config['system']['group']['member'][$idx]);
576
				}
Ad Schellevis's avatar
Ad Schellevis committed
577 578 579 580 581
			}
		}
	}
}

582 583
function local_group_set($group, $reset = false)
{
584 585 586 587
	if (!isset($group['name']) || !isset($group['gid'])) {
		// input data invalid
		return false;
	}
Ad Schellevis's avatar
Ad Schellevis committed
588 589
	$group_name = $group['name'];
	$group_gid = $group['gid'];
590
	$group_members = '';
Ad Schellevis's avatar
Ad Schellevis committed
591

592 593 594
	if (!$reset && !empty($group['member']) && count($group['member']) > 0) {
		$group_members = implode(',', $group['member']);
	}
Ad Schellevis's avatar
Ad Schellevis committed
595

596 597 598
	$ret = mwexecf('/usr/sbin/pw groupshow %s', $group_name, true);
	if ($ret) {
		$group_op = 'groupadd';
599
	} else {
600
		$group_op = 'groupmod';
601
	}
Ad Schellevis's avatar
Ad Schellevis committed
602

603
	mwexecf('/usr/sbin/pw %s %s -g %s -M %s', array($group_op, $group_name, $group_gid, $group_members));
Ad Schellevis's avatar
Ad Schellevis committed
604 605
}

606 607
function local_group_del($group)
{
Ad Schellevis's avatar
Ad Schellevis committed
608
	/* delete from group db */
609
	mwexecf('/usr/sbin/pw groupdel %s', $group['name']);
Ad Schellevis's avatar
Ad Schellevis committed
610 611
}

612 613
function ldap_setup_caenv($authcfg)
{
Ad Schellevis's avatar
Ad Schellevis committed
614 615

	unset($caref);
616

Ad Schellevis's avatar
Ad Schellevis committed
617 618 619
	if (empty($authcfg['ldap_caref']) || !strstr($authcfg['ldap_urltype'], "SSL")) {
		putenv('LDAPTLS_REQCERT=never');
		return;
620 621 622 623 624 625
	}

	$caref = lookup_ca($authcfg['ldap_caref']);
	if (!$caref) {
		log_error(sprintf(gettext("LDAP: Could not lookup CA by reference for host %s."), $authcfg['ldap_caref']));
		/* XXX: Prevent for credential leaking since we cannot setup the CA env. Better way? */
Ad Schellevis's avatar
Ad Schellevis committed
626
		putenv('LDAPTLS_REQCERT=hard');
627
		return;
Ad Schellevis's avatar
Ad Schellevis committed
628
	}
629 630 631 632 633 634 635 636 637

	@mkdir("/var/run/certs");
	@unlink("/var/run/certs/{$caref['refid']}.ca");
	file_put_contents("/var/run/certs/{$caref['refid']}.ca", base64_decode($caref['crt']));
	@chmod("/var/run/certs/{$caref['refid']}.ca", 0600);
	putenv('LDAPTLS_REQCERT=hard');
	/* XXX: Probably even the hashed link should be created for this? */
	putenv("LDAPTLS_CACERTDIR=/var/run/certs");
	putenv("LDAPTLS_CACERT=/var/run/certs/{$caref['refid']}.ca");
Ad Schellevis's avatar
Ad Schellevis committed
638 639 640 641
}


function is_account_expired($username) {
642 643 644
	$user = getUserEntry($username);
	if (isset($user['expires']) && !empty($user['expires'])) {
		if (strtotime("-1 day") > strtotime(date("m/d/Y",strtotime($user['expires']))))
Ad Schellevis's avatar
Ad Schellevis committed
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
			return true;
	}

	return false;
}

function is_account_disabled($username) {
	$user = getUserEntry($username);
	if (isset($user['disabled']))
		return true;

	return false;
}

function auth_get_authserver($name) {
660
	global $config;
Ad Schellevis's avatar
Ad Schellevis committed
661

662 663 664
	if ($name == "Local Database") {
		return array(
			"name" => gettext("Local Database"),
665
			"type" => "local",
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
			"host" => $config['system']['hostname']
		);
	}


	if (isset($config['system']['authserver']) && is_array($config['system']['authserver'])) {
		foreach ($config['system']['authserver'] as $authcfg) {
			if ($authcfg['name'] == $name) {
				if ($authcfg['type'] == 'ldap') {
					// let's try to avoid regenerating the ldap url in every function.
					if (strstr($authcfg['ldap_urltype'], "Standard")) {
						$authcfg['ldap_full_url'] = "ldap://";
					} else {
						$authcfg['ldap_full_url'] = "ldaps://";
					}
					$authcfg['ldap_full_url'] .= is_ipaddrv6($authcfg['host']) ? "[{$authcfg['host']}]" : $authcfg['host'];
					if (!empty($authcfg['ldap_port'])) {
						$authcfg['ldap_full_url'] .= ":{$authcfg['ldap_port']}";
					}
685 686 687 688 689 690 691 692
					// make sure a user and password entry exists and are null for anonymous usage
					if (empty($authcfg['ldap_binddn'])) {
						$authcfg['ldap_binddn'] = null;
					}
					if (empty($authcfg['ldap_bindpw'])) {
						$authcfg['ldap_bindpw'] = null;
					}

693 694 695 696 697
				}
				return $authcfg;
			}
		}
	}
Ad Schellevis's avatar
Ad Schellevis committed
698 699 700 701 702 703 704
}

function auth_get_authserver_list() {
        global $config;

	$list = array();

705
        if (isset($config['system']['authserver']) && is_array($config['system']['authserver'])) {
Ad Schellevis's avatar
Ad Schellevis committed
706 707 708 709 710 711
                foreach ($config['system']['authserver'] as $authcfg) {
			/* Add support for disabled entries? */
			$list[$authcfg['name']] = $authcfg;
                }
        }

712
	$list["Local Database"] = array( "name" => gettext("Local Database"), "type" => "local", "host" => $config['system']['hostname']);
Ad Schellevis's avatar
Ad Schellevis committed
713 714 715
	return $list;
}

716
function authenticate_user($username, $password, $authcfg = NULL) {
Ad Schellevis's avatar
Ad Schellevis committed
717

718 719 720 721
	if (empty($authcfg)) {
		$authName = 'Local Database';
	} else {
		$authName = $authcfg['name'];
722 723 724 725 726 727
		if ($authcfg['type'] == 'local') {
			// avoid gettext type issues on Local Database, authenticator should always be named "Local Database"
			$authName = 'Local Database';
		} elseif ($authcfg['type'] == 'ldap') {
			// temporary fix, ldap handler doesn't do this init yet.
			ldap_setup_caenv($authcfg);
728 729 730 731 732
		}
	}

	$authFactory = new OPNsense\Auth\AuthenticationFactory;
	$authenticator = $authFactory->get($authName);
Ad Schellevis's avatar
Ad Schellevis committed
733

734 735 736 737 738 739
	if ($authenticator != null) {
		return $authenticator->authenticate($username, $password) ;
	} else {
		log_error('Unable to retrieve authenticator for '. $authName);
		return false;
	}
Ad Schellevis's avatar
Ad Schellevis committed
740
}