Project

General

Profile

Download (54.5 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * auth.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2003-2006 Manuel Kasper <mk@neon1.net>
7
 * Copyright (c) 2005-2006 Bill Marquette <bill.marquette@gmail.com>
8
 * Copyright (c) 2006 Paul Taylor <paultaylor@winn-dixie.com>
9
 * Copyright (c) 2004-2018 Rubicon Communications, LLC (Netgate)
10
 * All rights reserved.
11
 *
12
 * Licensed under the Apache License, Version 2.0 (the "License");
13
 * you may not use this file except in compliance with the License.
14
 * You may obtain a copy of the License at
15
 *
16
 * http://www.apache.org/licenses/LICENSE-2.0
17
 *
18
 * Unless required by applicable law or agreed to in writing, software
19
 * distributed under the License is distributed on an "AS IS" BASIS,
20
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
 * See the License for the specific language governing permissions and
22
 * limitations under the License.
23
 */
24

    
25
/*
26
 * NOTE : Portions of the mschapv2 support was based on the BSD licensed CHAP.php
27
 * file courtesy of Michael Retterklieber.
28
 */
29
include_once('phpsessionmanager.inc');
30
if (!$do_not_include_config_gui_inc) {
31
	require_once("config.gui.inc");
32
}
33

    
34
// Will be changed to false if security checks fail
35
$security_passed = true;
36

    
37
/* If this function doesn't exist, we're being called from Captive Portal or
38
   another internal subsystem which does not include authgui.inc */
39
if (function_exists("display_error_form")) {
40
	/* Extra layer of lockout protection. Check if the user is in the GUI
41
	 * lockout table before processing a request */
42

    
43
	/* Fetch the contents of the lockout table. */
44
	exec("/sbin/pfctl -t 'webConfiguratorlockout' -T show", $entries);
45

    
46
	/* If the client is in the lockout table, print an error, kill states, and exit */
47
	if (in_array($_SERVER['REMOTE_ADDR'], array_map('trim', $entries))) {
48
		if (!security_checks_disabled()) {
49
			/* They may never see the error since the connection will be cut off, but try to be nice anyhow. */
50
			display_error_form("501", gettext("Access Denied<br/><br/>Access attempt from a temporarily locked out client address.<br /><br />Try accessing the firewall again after the lockout expires."));
51
			/* If they are locked out, they shouldn't have a state. Disconnect their connections. */
52
			$retval = pfSense_kill_states($_SERVER['REMOTE_ADDR']);
53
			if (is_ipaddrv4($_SERVER['REMOTE_ADDR'])) {
54
				$retval = pfSense_kill_states("0.0.0.0/0", $_SERVER['REMOTE_ADDR']);
55
			} elseif (is_ipaddrv6($_SERVER['REMOTE_ADDR'])) {
56
				$retval = pfSense_kill_states("::", $_SERVER['REMOTE_ADDR']);
57
			}
58
			exit;
59
		}
60
		$security_passed = false;
61
	}
62
}
63

    
64
if (function_exists("display_error_form") && !isset($config['system']['webgui']['nodnsrebindcheck'])) {
65
	/* DNS ReBinding attack prevention.  https://redmine.pfsense.org/issues/708 */
66
	$found_host = false;
67

    
68
	/* Either a IPv6 address with or without a alternate port */
69
	if (strstr($_SERVER['HTTP_HOST'], "]")) {
70
		$http_host_port = explode("]", $_SERVER['HTTP_HOST']);
71
		/* v6 address has more parts, drop the last part */
72
		if (count($http_host_port) > 1) {
73
			array_pop($http_host_port);
74
			$http_host = str_replace(array("[", "]"), "", implode(":", $http_host_port));
75
		} else {
76
			$http_host = str_replace(array("[", "]"), "", implode(":", $http_host_port));
77
		}
78
	} else {
79
		$http_host = explode(":", $_SERVER['HTTP_HOST']);
80
		$http_host = $http_host[0];
81
	}
82
	if (is_ipaddr($http_host) or $_SERVER['SERVER_ADDR'] == "127.0.0.1" or
83
		strcasecmp($http_host, "localhost") == 0 or $_SERVER['SERVER_ADDR'] == "::1") {
84
		$found_host = true;
85
	}
86
	if (strcasecmp($http_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 or
87
		strcasecmp($http_host, $config['system']['hostname']) == 0) {
88
		$found_host = true;
89
	}
90

    
91
	if (is_array($config['dyndnses']['dyndns']) && !$found_host) {
92
		foreach ($config['dyndnses']['dyndns'] as $dyndns) {
93
			if (strcasecmp($dyndns['host'], $http_host) == 0) {
94
				$found_host = true;
95
				break;
96
			}
97
		}
98
	}
99

    
100
	if (is_array($config['dnsupdates']['dnsupdate']) && !$found_host) {
101
		foreach ($config['dnsupdates']['dnsupdate'] as $rfc2136) {
102
			if (strcasecmp($rfc2136['host'], $http_host) == 0) {
103
				$found_host = true;
104
				break;
105
			}
106
		}
107
	}
108

    
109
	if (!empty($config['system']['webgui']['althostnames']) && !$found_host) {
110
		$althosts = explode(" ", $config['system']['webgui']['althostnames']);
111
		foreach ($althosts as $ah) {
112
			if (strcasecmp($ah, $http_host) == 0 or strcasecmp($ah, $_SERVER['SERVER_ADDR']) == 0) {
113
				$found_host = true;
114
				break;
115
			}
116
		}
117
	}
118

    
119
	if ($found_host == false) {
120
		if (!security_checks_disabled()) {
121
			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."));
122
			exit;
123
		}
124
		$security_passed = false;
125
	}
126
}
127

    
128
// If the HTTP_REFERER is something other than ourselves then disallow.
129
if (function_exists("display_error_form") && !isset($config['system']['webgui']['nohttpreferercheck'])) {
130
	if ($_SERVER['HTTP_REFERER']) {
131
		if (file_exists("{$g['tmp_path']}/setupwizard_lastreferrer")) {
132
			if ($_SERVER['HTTP_REFERER'] == file_get_contents("{$g['tmp_path']}/setupwizard_lastreferrer")) {
133
				unlink("{$g['tmp_path']}/setupwizard_lastreferrer");
134
				header("Refresh: 1; url=index.php");
135
?>
136
<!DOCTYPE html>
137
<html lang="en">
138
<head>
139
	<link rel="stylesheet" href="/css/pfSense.css" />
140
	<title><?=gettext("Redirecting..."); ?></title>
141
</head>
142
<body id="error" class="no-menu">
143
	<div id="jumbotron">
144
		<div class="container">
145
			<div class="col-sm-offset-3 col-sm-6 col-xs-12">
146
				<p><?=gettext("Redirecting to the dashboard...")?></p>
147
			</div>
148
		</div>
149
	</div>
150
</body>
151
</html>
152
<?php
153
				exit;
154
			}
155
		}
156
		$found_host = false;
157
		$referrer_host = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
158
		$referrer_host = str_replace(array("[", "]"), "", $referrer_host);
159
		if ($referrer_host) {
160
			if (strcasecmp($referrer_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 ||
161
			    strcasecmp($referrer_host, $config['system']['hostname']) == 0) {
162
				$found_host = true;
163
			}
164

    
165
			if (!empty($config['system']['webgui']['althostnames']) && !$found_host) {
166
				$althosts = explode(" ", $config['system']['webgui']['althostnames']);
167
				foreach ($althosts as $ah) {
168
					if (strcasecmp($referrer_host, $ah) == 0) {
169
						$found_host = true;
170
						break;
171
					}
172
				}
173
			}
174

    
175
			if (is_array($config['dyndnses']['dyndns']) && !$found_host) {
176
				foreach ($config['dyndnses']['dyndns'] as $dyndns) {
177
					if (strcasecmp($dyndns['host'], $referrer_host) == 0) {
178
						$found_host = true;
179
						break;
180
					}
181
				}
182
			}
183

    
184
			if (is_array($config['dnsupdates']['dnsupdate']) && !$found_host) {
185
				foreach ($config['dnsupdates']['dnsupdate'] as $rfc2136) {
186
					if (strcasecmp($rfc2136['host'], $referrer_host) == 0) {
187
						$found_host = true;
188
						break;
189
					}
190
				}
191
			}
192

    
193
			if (!$found_host) {
194
				$interface_list_ips = get_configured_ip_addresses();
195
				foreach ($interface_list_ips as $ilips) {
196
					if (strcasecmp($referrer_host, $ilips) == 0) {
197
						$found_host = true;
198
						break;
199
					}
200
				}
201
				$interface_list_ipv6s = get_configured_ipv6_addresses(true);
202
				foreach ($interface_list_ipv6s as $ilipv6s) {
203
					$ilipv6s = explode('%', $ilipv6s)[0];
204
					if (strcasecmp($referrer_host, $ilipv6s) == 0) {
205
						$found_host = true;
206
						break;
207
					}
208
				}
209
				if ($referrer_host == "127.0.0.1" || $referrer_host == "localhost") {
210
					// allow SSH port forwarded connections and links from localhost
211
					$found_host = true;
212
				}
213
			}
214
		}
215
		if ($found_host == false) {
216
			if (!security_checks_disabled()) {
217
				display_error_form("501", "An HTTP_REFERER was detected other than what is defined in System -> Advanced (" . htmlspecialchars($_SERVER['HTTP_REFERER']) . ").  If not needed, this check can be disabled in System -> Advanced -> Admin.");
218
				exit;
219
			}
220
			$security_passed = false;
221
		}
222
	} else {
223
		$security_passed = false;
224
	}
225
}
226

    
227
if (function_exists("display_error_form") && $security_passed) {
228
	/* Security checks passed, so it should be OK to turn them back on */
229
	restore_security_checks();
230
}
231
unset($security_passed);
232

    
233
$groupindex = index_groups();
234
$userindex = index_users();
235

    
236
function index_groups() {
237
	global $g, $debug, $config, $groupindex;
238

    
239
	$groupindex = array();
240

    
241
	if (is_array($config['system']['group'])) {
242
		$i = 0;
243
		foreach ($config['system']['group'] as $groupent) {
244
			$groupindex[$groupent['name']] = $i;
245
			$i++;
246
		}
247
	}
248

    
249
	return ($groupindex);
250
}
251

    
252
function index_users() {
253
	global $g, $debug, $config;
254

    
255
	if (is_array($config['system']['user'])) {
256
		$i = 0;
257
		foreach ($config['system']['user'] as $userent) {
258
			$userindex[$userent['name']] = $i;
259
			$i++;
260
		}
261
	}
262

    
263
	return ($userindex);
264
}
265

    
266
function & getUserEntry($name) {
267
	global $debug, $config, $userindex;
268
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
269

    
270
	if (isset($userindex[$name])) {
271
		return $config['system']['user'][$userindex[$name]];
272
	} elseif ($authcfg['type'] != "Local Database") {
273
		$user = array();
274
		$user['name'] = $name;
275
		return $user;
276
	}
277
}
278

    
279
function & getUserEntryByUID($uid) {
280
	global $debug, $config;
281

    
282
	if (is_array($config['system']['user'])) {
283
		foreach ($config['system']['user'] as & $user) {
284
			if ($user['uid'] == $uid) {
285
				return $user;
286
			}
287
		}
288
	}
289

    
290
	return false;
291
}
292

    
293
function & getGroupEntry($name) {
294
	global $debug, $config, $groupindex;
295
	if (isset($groupindex[$name])) {
296
		return $config['system']['group'][$groupindex[$name]];
297
	}
298
}
299

    
300
function & getGroupEntryByGID($gid) {
301
	global $debug, $config;
302

    
303
	if (is_array($config['system']['group'])) {
304
		foreach ($config['system']['group'] as & $group) {
305
			if ($group['gid'] == $gid) {
306
				return $group;
307
			}
308
		}
309
	}
310

    
311
	return false;
312
}
313

    
314
function get_user_privileges(& $user) {
315
	global $config, $_SESSION;
316

    
317
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
318
	$allowed_groups = array();
319

    
320
	$privs = $user['priv'];
321
	if (!is_array($privs)) {
322
		$privs = array();
323
	}
324

    
325
	// cache auth results for a short time to ease load on auth services & logs
326
	if (isset($config['system']['webgui']['auth_refresh_time'])) {
327
		$recheck_time = $config['system']['webgui']['auth_refresh_time'];
328
	} else {
329
		$recheck_time = 30;
330
	}
331

    
332
	if ($authcfg['type'] == "ldap") {
333
		if (isset($_SESSION["ldap_allowed_groups"]) &&
334
		    (time() <= $_SESSION["auth_check_time"] + $recheck_time)) {
335
			$allowed_groups = $_SESSION["ldap_allowed_groups"];
336
		} else {
337
			$allowed_groups = @ldap_get_groups($user['name'], $authcfg);
338
			$_SESSION["ldap_allowed_groups"] = $allowed_groups;
339
			$_SESSION["auth_check_time"] = time();
340
		}
341
	} elseif ($authcfg['type'] == "radius") {
342
		if (isset($_SESSION["radius_allowed_groups"]) &&
343
		    (time() <= $_SESSION["auth_check_time"] + $recheck_time)) {
344
			$allowed_groups = $_SESSION["radius_allowed_groups"];
345
		} else {
346
			$allowed_groups = @radius_get_groups($_SESSION['user_radius_attributes']);
347
			$_SESSION["radius_allowed_groups"] = $allowed_groups;
348
			$_SESSION["auth_check_time"] = time();
349
		}
350
	}
351

    
352
	if (empty($allowed_groups)) {
353
		$allowed_groups = local_user_get_groups($user, true);
354
	}
355

    
356
	if (is_array($allowed_groups)) {
357
		foreach ($allowed_groups as $name) {
358
			$group = getGroupEntry($name);
359
			if (is_array($group['priv'])) {
360
				$privs = array_merge($privs, $group['priv']);
361
			}
362
		}
363
	}
364

    
365
	return $privs;
366
}
367

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

    
370
	if (!$privid || !is_array($userent)) {
371
		return false;
372
	}
373

    
374
	$privs = get_user_privileges($userent);
375

    
376
	if (!is_array($privs)) {
377
		return false;
378
	}
379

    
380
	if (!in_array($privid, $privs)) {
381
		return false;
382
	}
383

    
384
	return true;
385
}
386

    
387
function local_backed($username, $passwd) {
388

    
389
	$user = getUserEntry($username);
390
	if (!$user) {
391
		return false;
392
	}
393

    
394
	if (is_account_disabled($username) || is_account_expired($username)) {
395
		return false;
396
	}
397

    
398
	if ($user['bcrypt-hash']) {
399
		if (password_verify($passwd, $user['bcrypt-hash'])) {
400
			return true;
401
		}
402
	}
403

    
404
	//for backwards compatibility
405
	if ($user['password']) {
406
		if (crypt($passwd, $user['password']) == $user['password']) {
407
			return true;
408
		}
409
	}
410

    
411
	if ($user['md5-hash']) {
412
		if (md5($passwd) == $user['md5-hash']) {
413
			return true;
414
		}
415
	}
416

    
417
	return false;
418
}
419

    
420
function local_sync_accounts() {
421
	global $debug, $config;
422

    
423
	/* remove local users to avoid uid conflicts */
424
	$fd = popen("/usr/sbin/pw usershow -a", "r");
425
	if ($fd) {
426
		while (!feof($fd)) {
427
			$line = explode(":", fgets($fd));
428
			if ($line[0] != "admin") {
429
				if (!strncmp($line[0], "_", 1)) {
430
					continue;
431
				}
432
				if ($line[2] < 2000) {
433
					continue;
434
				}
435
				if ($line[2] > 65000) {
436
					continue;
437
				}
438
			}
439
			/*
440
			 * If a crontab was created to user, pw userdel will be interactive and
441
			 * can cause issues. Just remove crontab before run it when necessary
442
			 */
443
			unlink_if_exists("/var/cron/tabs/{$line[0]}");
444
			$cmd = "/usr/sbin/pw userdel -n " . escapeshellarg($line[0]);
445
			if ($debug) {
446
				log_error(sprintf(gettext("Running: %s"), $cmd));
447
			}
448
			mwexec($cmd);
449
		}
450
		pclose($fd);
451
	}
452

    
453
	/* remove local groups to avoid gid conflicts */
454
	$gids = array();
455
	$fd = popen("/usr/sbin/pw groupshow -a", "r");
456
	if ($fd) {
457
		while (!feof($fd)) {
458
			$line = explode(":", fgets($fd));
459
			if (!strncmp($line[0], "_", 1)) {
460
				continue;
461
			}
462
			if ($line[2] < 2000) {
463
				continue;
464
			}
465
			if ($line[2] > 65000) {
466
				continue;
467
			}
468
			$cmd = "/usr/sbin/pw groupdel -g " . escapeshellarg($line[2]);
469
			if ($debug) {
470
				log_error(sprintf(gettext("Running: %s"), $cmd));
471
			}
472
			mwexec($cmd);
473
		}
474
		pclose($fd);
475
	}
476

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

    
481
	/* sync all local users */
482
	if (is_array($config['system']['user'])) {
483
		foreach ($config['system']['user'] as $user) {
484
			local_user_set($user);
485
		}
486
	}
487

    
488
	/* sync all local groups */
489
	if (is_array($config['system']['group'])) {
490
		foreach ($config['system']['group'] as $group) {
491
			local_group_set($group);
492
		}
493
	}
494

    
495

    
496
}
497

    
498
function local_user_set(& $user) {
499
	global $g, $debug;
500

    
501
	if (empty($user['password']) && empty($user['bcrypt-hash'])) {
502
		log_error("There is something wrong in the config because user {$user['name']} password is missing!");
503
		return;
504
	}
505

    
506

    
507
	$home_base = "/home/";
508
	$user_uid = $user['uid'];
509
	$user_name = $user['name'];
510
	$user_home = "{$home_base}{$user_name}";
511
	$user_shell = "/etc/rc.initial";
512
	$user_group = "nobody";
513

    
514
	// Ensure $home_base exists and is writable
515
	if (!is_dir($home_base)) {
516
		mkdir($home_base, 0755);
517
	}
518

    
519
	$lock_account = false;
520
	/* configure shell type */
521
	/* Cases here should be ordered by most privileged to least privileged. */
522
	if (userHasPrivilege($user, "user-shell-access") || userHasPrivilege($user, "page-all")) {
523
		$user_shell = "/bin/tcsh";
524
	} elseif (userHasPrivilege($user, "user-copy-files-chroot")) {
525
		$user_shell = "/usr/local/sbin/scponlyc";
526
	} elseif (userHasPrivilege($user, "user-copy-files")) {
527
		$user_shell = "/usr/local/bin/scponly";
528
	} elseif (userHasPrivilege($user, "user-ssh-tunnel")) {
529
		$user_shell = "/usr/local/sbin/ssh_tunnel_shell";
530
	} elseif (userHasPrivilege($user, "user-ipsec-xauth-dialin")) {
531
		$user_shell = "/sbin/nologin";
532
	} else {
533
		$user_shell = "/sbin/nologin";
534
		$lock_account = true;
535
	}
536

    
537
	/* Lock out disabled or expired users, unless it's root/admin. */
538
	if ((is_account_disabled($user_name) || is_account_expired($user_name)) && ($user_uid != 0)) {
539
		$user_shell = "/sbin/nologin";
540
		$lock_account = true;
541
	}
542

    
543
	/* root user special handling */
544
	if ($user_uid == 0) {
545
		$cmd = "/usr/sbin/pw usermod -q -n root -s /bin/sh -H 0";
546
		if ($debug) {
547
			log_error(sprintf(gettext("Running: %s"), $cmd));
548
		}
549
		$fd = popen($cmd, "w");
550
		if (empty($user['bcrypt-hash'])) {
551
			fwrite($fd, $user['password']);
552
		} else {
553
			fwrite($fd, $user['bcrypt-hash']);
554
		}
555
		pclose($fd);
556
		$user_group = "wheel";
557
		$user_home = "/root";
558
		$user_shell = "/etc/rc.initial";
559
	}
560

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

    
567
	$skel_dir = '/etc/skel';
568

    
569
	/* determine add or mod */
570
	if (($userattrs[0] != $user['name']) || (!strncmp($pwread, "pw:", 3))) {
571
		$user_op = "useradd -m -k " . escapeshellarg($skel_dir) . " -o";
572
	} else {
573
		$user_op = "usermod";
574
	}
575

    
576
	$comment = str_replace(array(":", "!", "@"), " ", $user['descr']);
577
	/* add or mod pw db */
578
	$cmd = "/usr/sbin/pw {$user_op} -q " .
579
			" -u " . escapeshellarg($user_uid) .
580
			" -n " . escapeshellarg($user_name) .
581
			" -g " . escapeshellarg($user_group) .
582
			" -s " . escapeshellarg($user_shell) .
583
			" -d " . escapeshellarg($user_home) .
584
			" -c " . escapeshellarg($comment) .
585
			" -H 0 2>&1";
586

    
587
	if ($debug) {
588
		log_error(sprintf(gettext("Running: %s"), $cmd));
589
	}
590
	$fd = popen($cmd, "w");
591
	if (empty($user['bcrypt-hash'])) {
592
		fwrite($fd, $user['password']);
593
	} else {
594
		fwrite($fd, $user['bcrypt-hash']);
595
	}
596
	pclose($fd);
597

    
598
	/* create user directory if required */
599
	if (!is_dir($user_home)) {
600
		mkdir($user_home, 0700);
601
	}
602
	@chown($user_home, $user_name);
603
	@chgrp($user_home, $user_group);
604

    
605
	/* Make sure all users have last version of config files */
606
	foreach (glob("{$skel_dir}/dot.*") as $dot_file) {
607
		$target = $user_home . '/' . substr(basename($dot_file), 3);
608
		@copy($dot_file, $target);
609
		@chown($target, $user_name);
610
		@chgrp($target, $user_group);
611
	}
612

    
613
	/* write out ssh authorized key file */
614
	if ($user['authorizedkeys']) {
615
		if (!is_dir("{$user_home}/.ssh")) {
616
			@mkdir("{$user_home}/.ssh", 0700);
617
			@chown("{$user_home}/.ssh", $user_name);
618
		}
619
		$keys = base64_decode($user['authorizedkeys']);
620
		@file_put_contents("{$user_home}/.ssh/authorized_keys", $keys);
621
		@chown("{$user_home}/.ssh/authorized_keys", $user_name);
622
	} else {
623
		unlink_if_exists("{$user_home}/.ssh/authorized_keys");
624
	}
625

    
626
	$un = $lock_account ? "" : "un";
627
	exec("/usr/sbin/pw {$un}lock " . escapeshellarg($user_name) . " -q 2>/dev/null");
628

    
629
}
630

    
631
function local_user_del($user) {
632
	global $debug;
633

    
634
	/* remove all memberships */
635
	local_user_set_groups($user);
636

    
637
	/* Don't remove /root */
638
	if ($user['uid'] != 0) {
639
		$rmhome = "-r";
640
	}
641

    
642
	/* read from pw db */
643
	$fd = popen("/usr/sbin/pw usershow -n {$user['name']} 2>&1", "r");
644
	$pwread = fgets($fd);
645
	pclose($fd);
646
	$userattrs = explode(":", trim($pwread));
647

    
648
	if ($userattrs[0] != $user['name']) {
649
		log_error("Tried to remove user {$user['name']} but got user {$userattrs[0]} instead. Bailing.");
650
		return;
651
	}
652

    
653
	/* delete from pw db */
654
	$cmd = "/usr/sbin/pw userdel -n " . escapeshellarg($user['name']) . " " . escapeshellarg($rmhome);
655

    
656
	if ($debug) {
657
		log_error(sprintf(gettext("Running: %s"), $cmd));
658
	}
659
	mwexec($cmd);
660

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

    
665
function local_user_set_password(&$user, $password) {
666

    
667
	unset($user['password']);
668
	unset($user['md5-hash']);
669
	$user['bcrypt-hash'] = password_hash($password, PASSWORD_BCRYPT);
670

    
671
	/* Maintain compatibility with FreeBSD - change $2y$ prefix to $2b$
672
	 * https://reviews.freebsd.org/D2742
673
	 * XXX: Can be removed as soon as r284483 is MFC'd.
674
	 */
675
	if ($user['bcrypt-hash'][2] == "y") {
676
		$user['bcrypt-hash'][2] = "b";
677
	}
678

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

    
687
}
688

    
689
function local_user_get_groups($user, $all = false) {
690
	global $debug, $config;
691

    
692
	$groups = array();
693
	if (!is_array($config['system']['group'])) {
694
		return $groups;
695
	}
696

    
697
	foreach ($config['system']['group'] as $group) {
698
		if ($all || (!$all && ($group['name'] != "all"))) {
699
			if (is_array($group['member'])) {
700
				if (in_array($user['uid'], $group['member'])) {
701
					$groups[] = $group['name'];
702
				}
703
			}
704
		}
705
	}
706

    
707
	if ($all) {
708
		$groups[] = "all";
709
	}
710

    
711
	sort($groups);
712

    
713
	return $groups;
714

    
715
}
716

    
717
function local_user_set_groups($user, $new_groups = NULL) {
718
	global $debug, $config, $groupindex;
719

    
720
	if (!is_array($config['system']['group'])) {
721
		return;
722
	}
723

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

    
727
	if (!is_array($new_groups)) {
728
		$new_groups = array();
729
	}
730

    
731
	if (!is_array($cur_groups)) {
732
		$cur_groups = array();
733
	}
734

    
735
	/* determine which memberships to add */
736
	foreach ($new_groups as $groupname) {
737
		if ($groupname == '' || in_array($groupname, $cur_groups)) {
738
			continue;
739
		}
740
		$group = & $config['system']['group'][$groupindex[$groupname]];
741
		$group['member'][] = $user['uid'];
742
		$mod_groups[] = $group;
743
	}
744
	unset($group);
745

    
746
	/* determine which memberships to remove */
747
	foreach ($cur_groups as $groupname) {
748
		if (in_array($groupname, $new_groups)) {
749
			continue;
750
		}
751
		if (!isset($config['system']['group'][$groupindex[$groupname]])) {
752
			continue;
753
		}
754
		$group = & $config['system']['group'][$groupindex[$groupname]];
755
		if (is_array($group['member'])) {
756
			$index = array_search($user['uid'], $group['member']);
757
			array_splice($group['member'], $index, 1);
758
			$mod_groups[] = $group;
759
		}
760
	}
761
	unset($group);
762

    
763
	/* sync all modified groups */
764
	foreach ($mod_groups as $group) {
765
		local_group_set($group);
766
	}
767
}
768

    
769
function local_group_del_user($user) {
770
	global $config;
771

    
772
	if (!is_array($config['system']['group'])) {
773
		return;
774
	}
775

    
776
	foreach ($config['system']['group'] as $group) {
777
		if (is_array($group['member'])) {
778
			foreach ($group['member'] as $idx => $uid) {
779
				if ($user['uid'] == $uid) {
780
					unset($config['system']['group']['member'][$idx]);
781
				}
782
			}
783
		}
784
	}
785
}
786

    
787
function local_group_set($group, $reset = false) {
788
	global $debug;
789

    
790
	$group_name = $group['name'];
791
	$group_gid = $group['gid'];
792
	$group_members = '';
793
	if (!$reset && !empty($group['member']) && count($group['member']) > 0) {
794
		$group_members = implode(",", $group['member']);
795
	}
796

    
797
	if (empty($group_name) || $group['scope'] == "remote") {
798
		return;
799
	}
800

    
801
	/* determine add or mod */
802
	if (mwexec("/usr/sbin/pw groupshow -g " . escapeshellarg($group_gid) . " 2>&1", true) == 0) {
803
		$group_op = "groupmod -l";
804
	} else {
805
		$group_op = "groupadd -n";
806
	}
807

    
808
	/* add or mod group db */
809
	$cmd = "/usr/sbin/pw {$group_op} " .
810
		escapeshellarg($group_name) .
811
		" -g " . escapeshellarg($group_gid) .
812
		" -M " . escapeshellarg($group_members) . " 2>&1";
813

    
814
	if ($debug) {
815
		log_error(sprintf(gettext("Running: %s"), $cmd));
816
	}
817
	mwexec($cmd);
818

    
819
}
820

    
821
function local_group_del($group) {
822
	global $debug;
823

    
824
	/* delete from group db */
825
	$cmd = "/usr/sbin/pw groupdel " . escapeshellarg($group['name']);
826

    
827
	if ($debug) {
828
		log_error(sprintf(gettext("Running: %s"), $cmd));
829
	}
830
	mwexec($cmd);
831
}
832

    
833
function ldap_test_connection($authcfg) {
834
	global $debug, $config, $g;
835

    
836
	if ($authcfg) {
837
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
838
			$ldapproto = "ldaps";
839
		} else {
840
			$ldapproto = "ldap";
841
		}
842
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
843
		$ldapport = $authcfg['ldap_port'];
844
		if (!empty($ldapport)) {
845
			$ldapserver .= ":{$ldapport}";
846
		}
847
		$ldapbasedn = $authcfg['ldap_basedn'];
848
		$ldapbindun = $authcfg['ldap_binddn'];
849
		$ldapbindpw = $authcfg['ldap_bindpw'];
850
	} else {
851
		return false;
852
	}
853

    
854
	/* first check if there is even an LDAP server populated */
855
	if (!$ldapserver) {
856
		return false;
857
	}
858

    
859
	/* Setup CA environment if needed. */
860
	ldap_setup_caenv($authcfg);
861

    
862
	/* connect and see if server is up */
863
	$error = false;
864
	if (!($ldap = ldap_connect($ldapserver))) {
865
		$error = true;
866
	}
867

    
868
	if ($error == true) {
869
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
870
		return false;
871
	}
872

    
873
	return true;
874
}
875

    
876
function ldap_setup_caenv($authcfg) {
877
	global $g;
878
	require_once("certs.inc");
879

    
880
	unset($caref);
881
	if (empty($authcfg['ldap_caref']) || strstr($authcfg['ldap_urltype'], "Standard")) {
882
		putenv('LDAPTLS_REQCERT=never');
883
		return;
884
	} elseif ($authcfg['ldap_caref'] == "global") {
885
		putenv('LDAPTLS_REQCERT=hard');
886
		putenv("LDAPTLS_CACERTDIR=/etc/ssl/");
887
		putenv("LDAPTLS_CACERT=/etc/ssl/cert.pem");
888
	} else {
889
		$caref = lookup_ca($authcfg['ldap_caref']);
890
		$param = array('caref' => $authcfg['ldap_caref']);
891
		$cachain = ca_chain($param);
892
		if (!$caref) {
893
			log_error(sprintf(gettext("LDAP: Could not lookup CA by reference for host %s."), $authcfg['ldap_caref']));
894
			/* XXX: Prevent for credential leaking since we cannot setup the CA env. Better way? */
895
			putenv('LDAPTLS_REQCERT=hard');
896
			return;
897
		}
898
		if (!is_dir("{$g['varrun_path']}/certs")) {
899
			@mkdir("{$g['varrun_path']}/certs");
900
		}
901
		if (file_exists("{$g['varrun_path']}/certs/{$caref['refid']}.ca")) {
902
			@unlink("{$g['varrun_path']}/certs/{$caref['refid']}.ca");
903
		}
904
		file_put_contents("{$g['varrun_path']}/certs/{$caref['refid']}.ca", $cachain);
905
		@chmod("{$g['varrun_path']}/certs/{$caref['refid']}.ca", 0600);
906
		putenv('LDAPTLS_REQCERT=hard');
907
		/* XXX: Probably even the hashed link should be created for this? */
908
		putenv("LDAPTLS_CACERTDIR={$g['varrun_path']}/certs");
909
		putenv("LDAPTLS_CACERT={$g['varrun_path']}/certs/{$caref['refid']}.ca");
910
	}
911
}
912

    
913
function ldap_test_bind($authcfg) {
914
	global $debug, $config, $g;
915

    
916
	if ($authcfg) {
917
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
918
			$ldapproto = "ldaps";
919
		} else {
920
			$ldapproto = "ldap";
921
		}
922
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
923
		$ldapport = $authcfg['ldap_port'];
924
		if (!empty($ldapport)) {
925
			$ldapserver .= ":{$ldapport}";
926
		}
927
		$ldapbasedn = $authcfg['ldap_basedn'];
928
		$ldapbindun = $authcfg['ldap_binddn'];
929
		$ldapbindpw = $authcfg['ldap_bindpw'];
930
		$ldapver = $authcfg['ldap_protver'];
931
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
932
		if (empty($ldapbndun) || empty($ldapbindpw)) {
933
			$ldapanon = true;
934
		} else {
935
			$ldapanon = false;
936
		}
937
	} else {
938
		return false;
939
	}
940

    
941
	/* first check if there is even an LDAP server populated */
942
	if (!$ldapserver) {
943
		return false;
944
	}
945

    
946
	/* Setup CA environment if needed. */
947
	ldap_setup_caenv($authcfg);
948

    
949
	/* connect and see if server is up */
950
	$error = false;
951
	if (!($ldap = ldap_connect($ldapserver))) {
952
		$error = true;
953
	}
954

    
955
	if ($error == true) {
956
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
957
		return false;
958
	}
959

    
960
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
961
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
962
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
963
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
964
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
965

    
966
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
967
		if (!(@ldap_start_tls($ldap))) {
968
			log_error(sprintf(gettext("ERROR! ldap_test_bind() could not STARTTLS to server %s."), $ldapname));
969
			@ldap_close($ldap);
970
			return false;
971
		}
972
	}
973

    
974
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
975
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
976
	if ($ldapanon == true) {
977
		if (!($res = @ldap_bind($ldap))) {
978
			@ldap_close($ldap);
979
			return false;
980
		}
981
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
982
		@ldap_close($ldap);
983
		return false;
984
	}
985

    
986
	@ldap_unbind($ldap);
987

    
988
	return true;
989
}
990

    
991
function ldap_get_user_ous($show_complete_ou=true, $authcfg) {
992
	global $debug, $config, $g;
993

    
994
	if (!function_exists("ldap_connect")) {
995
		return;
996
	}
997

    
998
	$ous = array();
999

    
1000
	if ($authcfg) {
1001
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1002
			$ldapproto = "ldaps";
1003
		} else {
1004
			$ldapproto = "ldap";
1005
		}
1006
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1007
		$ldapport = $authcfg['ldap_port'];
1008
		if (!empty($ldapport)) {
1009
			$ldapserver .= ":{$ldapport}";
1010
		}
1011
		$ldapbasedn = $authcfg['ldap_basedn'];
1012
		$ldapbindun = $authcfg['ldap_binddn'];
1013
		$ldapbindpw = $authcfg['ldap_bindpw'];
1014
		$ldapver = $authcfg['ldap_protver'];
1015
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1016
			$ldapanon = true;
1017
		} else {
1018
			$ldapanon = false;
1019
		}
1020
		$ldapname = $authcfg['name'];
1021
		$ldapfallback = false;
1022
		$ldapscope = $authcfg['ldap_scope'];
1023
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1024
	} else {
1025
		return false;
1026
	}
1027

    
1028
	/* first check if there is even an LDAP server populated */
1029
	if (!$ldapserver) {
1030
		log_error(gettext("ERROR!  ldap_get_user_ous() backed selected with no LDAP authentication server defined."));
1031
		return $ous;
1032
	}
1033

    
1034
	/* Setup CA environment if needed. */
1035
	ldap_setup_caenv($authcfg);
1036

    
1037
	/* connect and see if server is up */
1038
	$error = false;
1039
	if (!($ldap = ldap_connect($ldapserver))) {
1040
		$error = true;
1041
	}
1042

    
1043
	if ($error == true) {
1044
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1045
		return $ous;
1046
	}
1047

    
1048
	$ldapfilter = "(|(ou=*)(cn=Users))";
1049

    
1050
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1051
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1052
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1053
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1054
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1055

    
1056
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1057
		if (!(@ldap_start_tls($ldap))) {
1058
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not STARTTLS to server %s."), $ldapname));
1059
			@ldap_close($ldap);
1060
			return false;
1061
		}
1062
	}
1063

    
1064
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1065
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1066
	if ($ldapanon == true) {
1067
		if (!($res = @ldap_bind($ldap))) {
1068
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind anonymously to server %s."), $ldapname));
1069
			@ldap_close($ldap);
1070
			return $ous;
1071
		}
1072
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1073
		log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind to server %s."), $ldapname));
1074
		@ldap_close($ldap);
1075
		return $ous;
1076
	}
1077

    
1078
	if ($ldapscope == "one") {
1079
		$ldapfunc = "ldap_list";
1080
	} else {
1081
		$ldapfunc = "ldap_search";
1082
	}
1083

    
1084
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
1085
	$info = @ldap_get_entries($ldap, $search);
1086

    
1087
	if (is_array($info)) {
1088
		foreach ($info as $inf) {
1089
			if (!$show_complete_ou) {
1090
				$inf_split = explode(",", $inf['dn']);
1091
				$ou = $inf_split[0];
1092
				$ou = str_replace("OU=", "", $ou);
1093
				$ou = str_replace("CN=", "", $ou);
1094
			} else {
1095
				if ($inf['dn']) {
1096
					$ou = $inf['dn'];
1097
				}
1098
			}
1099
			if ($ou) {
1100
				$ous[] = $ou;
1101
			}
1102
		}
1103
	}
1104

    
1105
	@ldap_unbind($ldap);
1106

    
1107
	return $ous;
1108
}
1109

    
1110
function ldap_get_groups($username, $authcfg) {
1111
	global $debug, $config;
1112

    
1113
	if (!function_exists("ldap_connect")) {
1114
		return;
1115
	}
1116

    
1117
	if (!$username) {
1118
		return false;
1119
	}
1120

    
1121
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1122
		$username_split = explode("@", $username);
1123
		$username = $username_split[0];
1124
	}
1125

    
1126
	if (stristr($username, "\\")) {
1127
		$username_split = explode("\\", $username);
1128
		$username = $username_split[0];
1129
	}
1130

    
1131
	//log_error("Getting LDAP groups for {$username}.");
1132
	if ($authcfg) {
1133
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1134
			$ldapproto = "ldaps";
1135
		} else {
1136
			$ldapproto = "ldap";
1137
		}
1138
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1139
		$ldapport = $authcfg['ldap_port'];
1140
		if (!empty($ldapport)) {
1141
			$ldapserver .= ":{$ldapport}";
1142
		}
1143
		$ldapbasedn = $authcfg['ldap_basedn'];
1144
		$ldapbindun = $authcfg['ldap_binddn'];
1145
		$ldapbindpw = $authcfg['ldap_bindpw'];
1146
		$ldapauthcont = $authcfg['ldap_authcn'];
1147
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1148
		$ldapgroupattribute = strtolower($authcfg['ldap_attr_member']);
1149
		if (isset($authcfg['ldap_rfc2307'])) {
1150
			$ldapfilter         = "(&(objectClass={$authcfg['ldap_attr_groupobj']})({$ldapgroupattribute}={$username}))";
1151
		} else {
1152
			$ldapfilter         = "({$ldapnameattribute}={$username})";
1153
		}
1154
		$ldaptype = "";
1155
		$ldapver = $authcfg['ldap_protver'];
1156
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1157
			$ldapanon = true;
1158
		} else {
1159
			$ldapanon = false;
1160
		}
1161
		$ldapname = $authcfg['name'];
1162
		$ldapfallback = false;
1163
		$ldapscope = $authcfg['ldap_scope'];
1164
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1165
	} else {
1166
		return false;
1167
	}
1168

    
1169
	if (isset($authcfg['ldap_rfc2307'])) {
1170
		$ldapdn = $ldapbasedn;
1171
	} else {
1172
		$ldapdn = $_SESSION['ldapdn'];
1173
	}
1174

    
1175
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
1176
	$ldapgroupattribute = strtolower($ldapgroupattribute);
1177
	$memberof = array();
1178

    
1179
	/* Setup CA environment if needed. */
1180
	ldap_setup_caenv($authcfg);
1181

    
1182
	/* connect and see if server is up */
1183
	$error = false;
1184
	if (!($ldap = ldap_connect($ldapserver))) {
1185
		$error = true;
1186
	}
1187

    
1188
	if ($error == true) {
1189
		log_error(sprintf(gettext("ERROR! ldap_get_groups() Could not connect to server %s."), $ldapname));
1190
		return $memberof;
1191
	}
1192

    
1193
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1194
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1195
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1196
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1197
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1198

    
1199
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1200
		if (!(@ldap_start_tls($ldap))) {
1201
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not STARTTLS to server %s."), $ldapname));
1202
			@ldap_close($ldap);
1203
			return false;
1204
		}
1205
	}
1206

    
1207
	/* bind as user that has rights to read group attributes */
1208
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1209
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1210
	if ($ldapanon == true) {
1211
		if (!($res = @ldap_bind($ldap))) {
1212
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind anonymously to server %s."), $ldapname));
1213
			@ldap_close($ldap);
1214
			return false;
1215
		}
1216
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1217
		log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind to server %s."), $ldapname));
1218
		@ldap_close($ldap);
1219
		return $memberof;
1220
	}
1221

    
1222
	/* get groups from DN found */
1223
	/* use ldap_read instead of search so we don't have to do a bunch of extra work */
1224
	/* since we know the DN is in $_SESSION['ldapdn'] */
1225
	//$search    = ldap_read($ldap, $ldapdn, "(objectclass=*)", array($ldapgroupattribute));
1226
	if ($ldapscope == "one") {
1227
		$ldapfunc = "ldap_list";
1228
	} else {
1229
		$ldapfunc = "ldap_search";
1230
	}
1231

    
1232
	$search = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
1233
	$info = @ldap_get_entries($ldap, $search);
1234

    
1235
	$gresults = isset($authcfg['ldap_rfc2307']) ? $info : $info[0][$ldapgroupattribute];
1236

    
1237
	if (is_array($gresults)) {
1238
		/* Iterate through the groups and throw them into an array */
1239
		foreach ($gresults as $grp) {
1240
			if (((isset($authcfg['ldap_rfc2307'])) && (stristr($grp["dn"], "CN=") !== false)) ||
1241
			    ((!isset($authcfg['ldap_rfc2307'])) && (stristr($grp, "CN=") !== false))) {
1242
				$grpsplit = isset($authcfg['ldap_rfc2307']) ? explode(",", $grp["dn"]) : explode(",", $grp);
1243
				$memberof[] = preg_replace("/CN=/i", "", $grpsplit[0]);
1244
			}
1245
		}
1246
	}
1247

    
1248
	/* Time to close LDAP connection */
1249
	@ldap_unbind($ldap);
1250

    
1251
	$groups = print_r($memberof, true);
1252

    
1253
	//log_error("Returning groups ".$groups." for user $username");
1254

    
1255
	return $memberof;
1256
}
1257

    
1258
function ldap_format_host($host) {
1259
	return is_ipaddrv6($host) ? "[$host]" : $host ;
1260
}
1261

    
1262
function ldap_backed($username, $passwd, $authcfg) {
1263
	global $debug, $config;
1264

    
1265
	if (!$username) {
1266
		return;
1267
	}
1268

    
1269
	if (!function_exists("ldap_connect")) {
1270
		return;
1271
	}
1272

    
1273
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1274
		$username_split = explode("@", $username);
1275
		$username = $username_split[0];
1276
	}
1277
	if (stristr($username, "\\")) {
1278
		$username_split = explode("\\", $username);
1279
		$username = $username_split[0];
1280
	}
1281

    
1282
	if ($authcfg) {
1283
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1284
			$ldapproto = "ldaps";
1285
		} else {
1286
			$ldapproto = "ldap";
1287
		}
1288
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1289
		$ldapport = $authcfg['ldap_port'];
1290
		if (!empty($ldapport)) {
1291
			$ldapserver .= ":{$ldapport}";
1292
		}
1293
		$ldapbasedn = $authcfg['ldap_basedn'];
1294
		$ldapbindun = $authcfg['ldap_binddn'];
1295
		$ldapbindpw = $authcfg['ldap_bindpw'];
1296
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1297
			$ldapanon = true;
1298
		} else {
1299
			$ldapanon = false;
1300
		}
1301
		$ldapauthcont = $authcfg['ldap_authcn'];
1302
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1303
		$ldapextendedqueryenabled = $authcfg['ldap_extended_enabled'];
1304
		$ldapextendedquery = $authcfg['ldap_extended_query'];
1305
		$ldapfilter = "";
1306
		if (!$ldapextendedqueryenabled) {
1307
			$ldapfilter = "({$ldapnameattribute}={$username})";
1308
		} else {
1309
			$ldapfilter = "(&({$ldapnameattribute}={$username})({$ldapextendedquery}))";
1310
		}
1311
		$ldaptype = "";
1312
		$ldapver = $authcfg['ldap_protver'];
1313
		$ldapname = $authcfg['name'];
1314
		$ldapscope = $authcfg['ldap_scope'];
1315
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1316
	} else {
1317
		return false;
1318
	}
1319

    
1320
	/* first check if there is even an LDAP server populated */
1321
	if (!$ldapserver) {
1322
		if ($ldapfallback) {
1323
			log_error(gettext("ERROR! ldap_backed() called with no LDAP authentication server defined.  Defaulting to local user database. Visit System -> User Manager."));
1324
			return local_backed($username, $passwd);
1325
		} else {
1326
			log_error(gettext("ERROR! ldap_backed() called with no LDAP authentication server defined."));
1327
		}
1328

    
1329
		return false;
1330
	}
1331

    
1332
	/* Setup CA environment if needed. */
1333
	ldap_setup_caenv($authcfg);
1334

    
1335
	/* Make sure we can connect to LDAP */
1336
	$error = false;
1337
	if (!($ldap = ldap_connect($ldapserver))) {
1338
		$error = true;
1339
	}
1340

    
1341
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1342
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1343
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1344
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1345
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1346

    
1347
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1348
		if (!(@ldap_start_tls($ldap))) {
1349
			log_error(sprintf(gettext("ERROR! ldap_backed() could not STARTTLS to server %s."), $ldapname));
1350
			@ldap_close($ldap);
1351
			return false;
1352
		}
1353
	}
1354

    
1355
	if ($error == true) {
1356
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1357
		return false;
1358
	}
1359

    
1360
	/* ok, its up.  now, lets bind as the bind user so we can search it */
1361
	$error = false;
1362
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1363
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1364
	if ($ldapanon == true) {
1365
		if (!($res = @ldap_bind($ldap))) {
1366
			$error = true;
1367
		}
1368
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1369
		$error = true;
1370
	}
1371

    
1372
	if ($error == true) {
1373
		@ldap_close($ldap);
1374
		log_error(sprintf(gettext("ERROR! Could not bind to server %s."), $ldapname));
1375
		return false;
1376
	}
1377

    
1378
	/* Get LDAP Authcontainers and split em up. */
1379
	$ldac_splits = explode(";", $ldapauthcont);
1380

    
1381
	/* setup the usercount so we think we haven't found anyone yet */
1382
	$usercount = 0;
1383

    
1384
	/*****************************************************************/
1385
	/*  We first find the user based on username and filter          */
1386
	/*  then, once we find the first occurrence of that person       */
1387
	/*  we set session variables to point to the OU and DN of the    */
1388
	/*  person.  To later be used by ldap_get_groups.                */
1389
	/*  that way we don't have to search twice.                      */
1390
	/*****************************************************************/
1391
	if ($debug) {
1392
		log_auth(sprintf(gettext("Now Searching for %s in directory."), $username));
1393
	}
1394
	/* Iterate through the user containers for search */
1395
	foreach ($ldac_splits as $i => $ldac_split) {
1396
		$ldac_split = isset($authcfg['ldap_utf8']) ? utf8_encode($ldac_split) : $ldac_split;
1397
		$ldapfilter = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapfilter) : $ldapfilter;
1398
		$ldapsearchbasedn = isset($authcfg['ldap_utf8']) ? utf8_encode("{$ldac_split},{$ldapbasedn}") : "{$ldac_split},{$ldapbasedn}";
1399
		/* Make sure we just use the first user we find */
1400
		if ($debug) {
1401
			log_auth(sprintf(gettext('Now Searching in server %1$s, container %2$s with filter %3$s.'), $ldapname, utf8_decode($ldac_split), utf8_decode($ldapfilter)));
1402
		}
1403
		if ($ldapscope == "one") {
1404
			$ldapfunc = "ldap_list";
1405
		} else {
1406
			$ldapfunc = "ldap_search";
1407
		}
1408
		/* Support legacy auth container specification. */
1409
		if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) {
1410
			$search = @$ldapfunc($ldap, $ldac_split, $ldapfilter);
1411
		} else {
1412
			$search = @$ldapfunc($ldap, $ldapsearchbasedn, $ldapfilter);
1413
		}
1414
		if (!$search) {
1415
			log_error(sprintf(gettext("Search resulted in error: %s"), ldap_error($ldap)));
1416
			continue;
1417
		}
1418
		$info = ldap_get_entries($ldap, $search);
1419
		$matches = $info['count'];
1420
		if ($matches == 1) {
1421
			$userdn = $_SESSION['ldapdn'] = $info[0]['dn'];
1422
			$_SESSION['ldapou'] = $ldac_split[$i];
1423
			$_SESSION['ldapon'] = "true";
1424
			$usercount = 1;
1425
			break;
1426
		}
1427
	}
1428

    
1429
	if ($usercount != 1) {
1430
		@ldap_unbind($ldap);
1431
		log_error(gettext("ERROR! Either LDAP search failed, or multiple users were found."));
1432
		return false;
1433
	}
1434

    
1435
	/* Now lets bind as the user we found */
1436
	$passwd = isset($authcfg['ldap_utf8']) ? utf8_encode($passwd) : $passwd;
1437
	if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
1438
		log_error(sprintf(gettext('ERROR! Could not login to server %1$s as user %2$s: %3$s'), $ldapname, $username, ldap_error($ldap)));
1439
		@ldap_unbind($ldap);
1440
		return false;
1441
	}
1442

    
1443
	if ($debug) {
1444
		$userdn = isset($authcfg['ldap_utf8']) ? utf8_decode($userdn) : $userdn;
1445
		log_auth(sprintf(gettext('Logged in successfully as %1$s via LDAP server %2$s with DN = %3$s.'), $username, $ldapname, $userdn));
1446
	}
1447

    
1448
	/* At this point we are bound to LDAP so the user was auth'd okay. Close connection. */
1449
	@ldap_unbind($ldap);
1450

    
1451
	return true;
1452
}
1453

    
1454
function radius_backed($username, $password, $authcfg, &$attributes = array()) {
1455
	global $debug, $config;
1456
	$ret = false;
1457

    
1458
	require_once("radius.inc");
1459
	require_once("Crypt/CHAP.php");
1460

    
1461
	if ($authcfg) {
1462
		$radiusservers = array();
1463
		$radiusservers[0]['ipaddr'] = $authcfg['host'];
1464
		$radiusservers[0]['port'] = $authcfg['radius_auth_port'];
1465
		$radiusservers[0]['sharedsecret'] = $authcfg['radius_secret'];
1466
		$radiusservers[0]['timeout'] = $authcfg['radius_timeout'];
1467
		if(isset($authcfg['radius_protocol'])) {
1468
			$radius_protocol = $authcfg['radius_protocol'];
1469
		} else {
1470
			$radius_protocol = 'PAP';
1471
		}
1472
	} else {
1473
		return false;
1474
	}
1475

    
1476
	// Create our instance
1477
	$classname = 'Auth_RADIUS_' . $radius_protocol;
1478
	$rauth = new $classname($username, $password);
1479

    
1480
	/* Add new servers to our instance */
1481
	foreach ($radiusservers as $radsrv) {
1482
		$timeout = (is_numeric($radsrv['timeout'])) ? $radsrv['timeout'] : 5;
1483
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret'], $timeout);
1484
	}
1485

    
1486
	// Construct data package
1487
	$rauth->username = $username;
1488
	switch ($radius_protocol) {
1489
		case 'CHAP_MD5':
1490
		case 'MSCHAPv1':
1491
			$classname = $radius_protocol == 'MSCHAPv1' ? 'Crypt_CHAP_MSv1' : 'Crypt_CHAP_MD5';
1492
			$crpt = new $classname;
1493
			$crpt->username = $username;
1494
			$crpt->password = $password;
1495
			$rauth->challenge = $crpt->challenge;
1496
			$rauth->chapid = $crpt->chapid;
1497
			$rauth->response = $crpt->challengeResponse();
1498
			$rauth->flags = 1;
1499
			break;
1500

    
1501
		case 'MSCHAPv2':
1502
			$crpt = new Crypt_CHAP_MSv2;
1503
			$crpt->username = $username;
1504
			$crpt->password = $password;
1505
			$rauth->challenge = $crpt->authChallenge;
1506
			$rauth->peerChallenge = $crpt->peerChallenge;
1507
			$rauth->chapid = $crpt->chapid;
1508
			$rauth->response = $crpt->challengeResponse();
1509
			break;
1510

    
1511
		default:
1512
			$rauth->password = $password;
1513
			break;
1514
	}
1515

    
1516
	if (PEAR::isError($rauth->start())) {
1517
		$retvalue['auth_val'] = 1;
1518
		$retvalue['error'] = $rauth->getError();
1519
		if ($debug) {
1520
			printf(gettext("RADIUS start: %s") . "<br />\n", $retvalue['error']);
1521
		}
1522
	}
1523

    
1524
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1525

    
1526
	/* Send request */
1527
	$result = $rauth->send();
1528
	if (PEAR::isError($result)) {
1529
		$retvalue['auth_val'] = 1;
1530
		$retvalue['error'] = $result->getMessage();
1531
		if ($debug) {
1532
			printf(gettext("RADIUS send failed: %s") . "<br />\n", $retvalue['error']);
1533
		}
1534
	} else if ($result === true) {
1535
		if ($rauth->getAttributes()) {
1536
			$attributes = $rauth->listAttributes();
1537
		}
1538
		$retvalue['auth_val'] = 2;
1539
		if ($debug) {
1540
			printf(gettext("RADIUS Auth succeeded")."<br />\n");
1541
		}
1542
		$ret = true;
1543
	} else {
1544
		$retvalue['auth_val'] = 3;
1545
		if ($debug) {
1546
			printf(gettext("RADIUS Auth rejected")."<br />\n");
1547
		}
1548
	}
1549

    
1550
	// close OO RADIUS_AUTHENTICATION
1551
	$rauth->close();
1552

    
1553
	return $ret;
1554
}
1555

    
1556
/*
1557
	$attributes must contain a "class" key containing the groups and local
1558
	groups must exist to match.
1559
*/
1560
function radius_get_groups($attributes) {
1561
	$groups = array();
1562
	if (!empty($attributes) && is_array($attributes) && (!empty($attributes['class']) || !empty($attributes['class_int']))) {
1563
		/* Some RADIUS servers return multiple class attributes, so check them all. */
1564
		$groups = array();
1565
		if (!empty($attributes['class']) && is_array($attributes['class'])) {
1566
			foreach ($attributes['class'] as $class) {
1567
				$groups = array_unique(array_merge($groups, explode(";", $class)));
1568
			}
1569
		}
1570

    
1571
		foreach ($groups as & $grp) {
1572
			$grp = trim($grp);
1573
			if (strtolower(substr($grp, 0, 3)) == "ou=") {
1574
				$grp = substr($grp, 3);
1575
			}
1576
		}
1577
	}
1578
	return $groups;
1579
}
1580

    
1581
function get_user_expiration_date($username) {
1582
	$user = getUserEntry($username);
1583
	if ($user['expires']) {
1584
		return $user['expires'];
1585
	}
1586
}
1587

    
1588
function is_account_expired($username) {
1589
	$expirydate = get_user_expiration_date($username);
1590
	if ($expirydate) {
1591
		if (strtotime("-1 day") > strtotime(date("m/d/Y", strtotime($expirydate)))) {
1592
			return true;
1593
		}
1594
	}
1595

    
1596
	return false;
1597
}
1598

    
1599
function is_account_disabled($username) {
1600
	$user = getUserEntry($username);
1601
	if (isset($user['disabled'])) {
1602
		return true;
1603
	}
1604

    
1605
	return false;
1606
}
1607

    
1608
function get_user_settings($username) {
1609
	global $config;
1610
	$settings = array();
1611
	$settings['widgets'] = $config['widgets'];
1612
	$settings['webgui']['dashboardcolumns'] = $config['system']['webgui']['dashboardcolumns'];
1613
	$settings['webgui']['webguihostnamemenu'] = $config['system']['webgui']['webguihostnamemenu'];
1614
	$settings['webgui']['webguicss'] = $config['system']['webgui']['webguicss'];
1615
	$settings['webgui']['logincss'] = $config['system']['webgui']['logincss'];
1616
	$settings['webgui']['interfacessort'] = isset($config['system']['webgui']['interfacessort']);
1617
	$settings['webgui']['dashboardavailablewidgetspanel'] = isset($config['system']['webgui']['dashboardavailablewidgetspanel']);
1618
	$settings['webgui']['webguifixedmenu'] = isset($config['system']['webgui']['webguifixedmenu']);
1619
	$settings['webgui']['webguileftcolumnhyper'] = isset($config['system']['webgui']['webguileftcolumnhyper']);
1620
	$settings['webgui']['disablealiaspopupdetail'] = isset($config['system']['webgui']['disablealiaspopupdetail']);
1621
	$settings['webgui']['systemlogsfilterpanel'] = isset($config['system']['webgui']['systemlogsfilterpanel']);
1622
	$settings['webgui']['systemlogsmanagelogpanel'] = isset($config['system']['webgui']['systemlogsmanagelogpanel']);
1623
	$settings['webgui']['statusmonitoringsettingspanel'] = isset($config['system']['webgui']['statusmonitoringsettingspanel']);
1624
	$settings['webgui']['pagenamefirst'] = isset($config['system']['webgui']['pagenamefirst']);
1625
	$user = getUserEntry($username);
1626
	if (isset($user['customsettings'])) {
1627
		$settings['customsettings'] = true;
1628
		if (isset($user['widgets'])) {
1629
			// This includes the 'sequence', and any widgetname-config per-widget settings.
1630
			$settings['widgets'] = $user['widgets'];
1631
		}
1632
		if (isset($user['dashboardcolumns'])) {
1633
			$settings['webgui']['dashboardcolumns'] = $user['dashboardcolumns'];
1634
		}
1635
		if (isset($user['webguicss'])) {
1636
			$settings['webgui']['webguicss'] = $user['webguicss'];
1637
		}
1638
		if (isset($user['webguihostnamemenu'])) {
1639
			$settings['webgui']['webguihostnamemenu'] = $user['webguihostnamemenu'];
1640
		}
1641
		$settings['webgui']['interfacessort'] = isset($user['interfacessort']);
1642
		$settings['webgui']['dashboardavailablewidgetspanel'] = isset($user['dashboardavailablewidgetspanel']);
1643
		$settings['webgui']['webguifixedmenu'] = isset($user['webguifixedmenu']);
1644
		$settings['webgui']['webguileftcolumnhyper'] = isset($user['webguileftcolumnhyper']);
1645
		$settings['webgui']['disablealiaspopupdetail'] = isset($user['disablealiaspopupdetail']);
1646
		$settings['webgui']['systemlogsfilterpanel'] = isset($user['systemlogsfilterpanel']);
1647
		$settings['webgui']['systemlogsmanagelogpanel'] = isset($user['systemlogsmanagelogpanel']);
1648
		$settings['webgui']['statusmonitoringsettingspanel'] = isset($user['statusmonitoringsettingspanel']);
1649
		$settings['webgui']['pagenamefirst'] = isset($user['pagenamefirst']);
1650
	} else {
1651
		$settings['customsettings'] = false;
1652
	}
1653

    
1654
	if ($settings['webgui']['dashboardcolumns'] < 1) {
1655
		$settings['webgui']['dashboardcolumns'] = 2;
1656
	}
1657

    
1658
	return $settings;
1659
}
1660

    
1661
function save_widget_settings($username, $settings, $message = "") {
1662
	global $config, $userindex;
1663
	$user = getUserEntry($username);
1664

    
1665
	if (strlen($message) > 0) {
1666
		$msgout = $message;
1667
	} else {
1668
		$msgout = gettext("Widget configuration has been changed.");
1669
	}
1670

    
1671
	if (isset($user['customsettings'])) {
1672
		$config['system']['user'][$userindex[$username]]['widgets'] = $settings;
1673
		write_config($msgout . " " . sprintf(gettext("(User %s)"), $username));
1674
	} else {
1675
		$config['widgets'] = $settings;
1676
		write_config($msgout);
1677
	}
1678
}
1679

    
1680
function auth_get_authserver($name) {
1681
	global $config;
1682

    
1683
	if (is_array($config['system']['authserver'])) {
1684
		foreach ($config['system']['authserver'] as $authcfg) {
1685
			if ($authcfg['name'] == $name) {
1686
				return $authcfg;
1687
			}
1688
		}
1689
	}
1690
	if ($name == "Local Database") {
1691
		return array("name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']);
1692
	}
1693
}
1694

    
1695
function auth_get_authserver_list() {
1696
	global $config;
1697

    
1698
	$list = array();
1699

    
1700
	if (is_array($config['system']['authserver'])) {
1701
		foreach ($config['system']['authserver'] as $authcfg) {
1702
			/* Add support for disabled entries? */
1703
			$list[$authcfg['name']] = $authcfg;
1704
		}
1705
	}
1706

    
1707
	$list["Local Database"] = array("name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']);
1708
	return $list;
1709
}
1710

    
1711
function getUserGroups($username, $authcfg, &$attributes = array()) {
1712
	global $config;
1713

    
1714
	$allowed_groups = array();
1715

    
1716
	switch ($authcfg['type']) {
1717
		case 'ldap':
1718
			$allowed_groups = @ldap_get_groups($username, $authcfg);
1719
			break;
1720
		case 'radius':
1721
			$allowed_groups = @radius_get_groups($attributes);
1722
			break;
1723
		default:
1724
			$user = getUserEntry($username);
1725
			$allowed_groups = @local_user_get_groups($user, true);
1726
			break;
1727
	}
1728

    
1729
	$member_groups = array();
1730
	if (is_array($config['system']['group'])) {
1731
		foreach ($config['system']['group'] as $group) {
1732
			if (in_array($group['name'], $allowed_groups)) {
1733
				$member_groups[] = $group['name'];
1734
			}
1735
		}
1736
	}
1737

    
1738
	return $member_groups;
1739
}
1740

    
1741
function authenticate_user($username, $password, $authcfg = NULL, &$attributes = array()) {
1742

    
1743
	if (is_array($username) || is_array($password)) {
1744
		return false;
1745
	}
1746

    
1747
	if (!$authcfg) {
1748
		return local_backed($username, $password);
1749
	}
1750

    
1751
	$authenticated = false;
1752
	switch ($authcfg['type']) {
1753
		case 'ldap':
1754
			if (ldap_backed($username, $password, $authcfg)) {
1755
				$authenticated = true;
1756
			}
1757
			break;
1758
		case 'radius':
1759
			if (radius_backed($username, $password, $authcfg, $attributes)) {
1760
				$authenticated = true;
1761
			}
1762
			break;
1763
		default:
1764
			/* lookup user object by name */
1765
			if (local_backed($username, $password)) {
1766
				$authenticated = true;
1767
			}
1768
			break;
1769
		}
1770

    
1771
	return $authenticated;
1772
}
1773

    
1774
function session_auth() {
1775
	global $config, $_SESSION, $page;
1776

    
1777
	// Handle HTTPS httponly and secure flags
1778
	$currentCookieParams = session_get_cookie_params();
1779
	session_set_cookie_params(
1780
		$currentCookieParams["lifetime"],
1781
		$currentCookieParams["path"],
1782
		NULL,
1783
		($config['system']['webgui']['protocol'] == "https"),
1784
		true
1785
	);
1786

    
1787
	phpsession_begin();
1788

    
1789
	// Detect protocol change
1790
	if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) {
1791
		phpsession_end();
1792
		return false;
1793
	}
1794

    
1795
	/* Validate incoming login request */
1796
	$attributes = array();
1797
	if (isset($_POST['login']) && !empty($_POST['usernamefld']) && !empty($_POST['passwordfld'])) {
1798
		$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
1799
		$remoteauth = authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg, $attributes);
1800
		if ($remoteauth || authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) {
1801
			// Generate a new id to avoid session fixation
1802
			session_regenerate_id();
1803
			$_SESSION['Logged_In'] = "True";
1804
			$_SESSION['remoteauth'] = $remoteauth;
1805
			$_SESSION['Username'] = $_POST['usernamefld'];
1806
			$_SESSION['user_radius_attributes'] = $attributes;
1807
			$_SESSION['last_access'] = time();
1808
			$_SESSION['protocol'] = $config['system']['webgui']['protocol'];
1809
			phpsession_end(true);
1810
			if (!isset($config['system']['webgui']['quietlogin'])) {
1811
				log_auth(sprintf(gettext("Successful login for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], $_SERVER['REMOTE_ADDR']));
1812
			}
1813
			if (isset($_POST['postafterlogin'])) {
1814
				return true;
1815
			} else {
1816
				if (empty($page)) {
1817
					$page = "/";
1818
				}
1819
				header("Location: {$page}");
1820
			}
1821
			exit;
1822
		} else {
1823
			/* give the user an error message */
1824
			$_SESSION['Login_Error'] = gettext("Username or Password incorrect");
1825
			log_auth("webConfigurator authentication error for '{$_POST['usernamefld']}' from {$_SERVER['REMOTE_ADDR']}");
1826
			if (isAjax()) {
1827
				echo "showajaxmessage('{$_SESSION['Login_Error']}');";
1828
				return;
1829
			}
1830
		}
1831
	}
1832

    
1833
	/* Show login page if they aren't logged in */
1834
	if (empty($_SESSION['Logged_In'])) {
1835
		phpsession_end(true);
1836
		return false;
1837
	}
1838

    
1839
	/* If session timeout isn't set, we don't mark sessions stale */
1840
	if (!isset($config['system']['webgui']['session_timeout'])) {
1841
		/* Default to 4 hour timeout if one is not set */
1842
		if ($_SESSION['last_access'] < (time() - 14400)) {
1843
			$_POST['logout'] = true;
1844
			$_SESSION['Logout'] = true;
1845
		} else {
1846
			$_SESSION['last_access'] = time();
1847
		}
1848
	} else if (intval($config['system']['webgui']['session_timeout']) == 0) {
1849
		/* only update if it wasn't ajax */
1850
		if (!isAjax()) {
1851
			$_SESSION['last_access'] = time();
1852
		}
1853
	} else {
1854
		/* Check for stale session */
1855
		if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
1856
			$_POST['logout'] = true;
1857
			$_SESSION['Logout'] = true;
1858
		} else {
1859
			/* only update if it wasn't ajax */
1860
			if (!isAjax()) {
1861
				$_SESSION['last_access'] = time();
1862
			}
1863
		}
1864
	}
1865

    
1866
	/* user hit the logout button */
1867
	if (isset($_POST['logout'])) {
1868

    
1869
		if ($_SESSION['Logout']) {
1870
			log_error(sprintf(gettext("Session timed out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR']));
1871
		} else {
1872
			log_error(sprintf(gettext("User logged out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR']));
1873
		}
1874

    
1875
		/* wipe out $_SESSION */
1876
		$_SESSION = array();
1877

    
1878
		if (isset($_COOKIE[session_name()])) {
1879
			setcookie(session_name(), '', time()-42000, '/');
1880
		}
1881

    
1882
		/* and destroy it */
1883
		phpsession_destroy();
1884

    
1885
		$scriptName = explode("/", $_SERVER["SCRIPT_FILENAME"]);
1886
		$scriptElms = count($scriptName);
1887
		$scriptName = $scriptName[$scriptElms-1];
1888

    
1889
		if (isAjax()) {
1890
			return false;
1891
		}
1892

    
1893
		/* redirect to page the user is on, it'll prompt them to login again */
1894
		header("Location: {$scriptName}");
1895

    
1896
		return false;
1897
	}
1898

    
1899
	/*
1900
	 * this is for debugging purpose if you do not want to use Ajax
1901
	 * to submit a HTML form. It basically disables the observation
1902
	 * of the submit event and hence does not trigger Ajax.
1903
	 */
1904
	if ($_REQUEST['disable_ajax']) {
1905
		$_SESSION['NO_AJAX'] = "True";
1906
	}
1907

    
1908
	/*
1909
	 * Same to re-enable Ajax.
1910
	 */
1911
	if ($_REQUEST['enable_ajax']) {
1912
		unset($_SESSION['NO_AJAX']);
1913
	}
1914
	phpsession_end(true);
1915
	return true;
1916
}
1917

    
1918
?>
(1-1/55)