Project

General

Profile

Download (54.3 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-2016 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
	} else {
885
		$caref = lookup_ca($authcfg['ldap_caref']);
886
		$param = array('caref' => $authcfg['ldap_caref']);
887
		$cachain = ca_chain($param);
888
		if (!$caref) {
889
			log_error(sprintf(gettext("LDAP: Could not lookup CA by reference for host %s."), $authcfg['ldap_caref']));
890
			/* XXX: Prevent for credential leaking since we cannot setup the CA env. Better way? */
891
			putenv('LDAPTLS_REQCERT=hard');
892
			return;
893
		}
894
		if (!is_dir("{$g['varrun_path']}/certs")) {
895
			@mkdir("{$g['varrun_path']}/certs");
896
		}
897
		if (file_exists("{$g['varrun_path']}/certs/{$caref['refid']}.ca")) {
898
			@unlink("{$g['varrun_path']}/certs/{$caref['refid']}.ca");
899
		}
900
		file_put_contents("{$g['varrun_path']}/certs/{$caref['refid']}.ca", $cachain);
901
		@chmod("{$g['varrun_path']}/certs/{$caref['refid']}.ca", 0600);
902
		putenv('LDAPTLS_REQCERT=hard');
903
		/* XXX: Probably even the hashed link should be created for this? */
904
		putenv("LDAPTLS_CACERTDIR={$g['varrun_path']}/certs");
905
		putenv("LDAPTLS_CACERT={$g['varrun_path']}/certs/{$caref['refid']}.ca");
906
	}
907
}
908

    
909
function ldap_test_bind($authcfg) {
910
	global $debug, $config, $g;
911

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

    
937
	/* first check if there is even an LDAP server populated */
938
	if (!$ldapserver) {
939
		return false;
940
	}
941

    
942
	/* Setup CA environment if needed. */
943
	ldap_setup_caenv($authcfg);
944

    
945
	/* connect and see if server is up */
946
	$error = false;
947
	if (!($ldap = ldap_connect($ldapserver))) {
948
		$error = true;
949
	}
950

    
951
	if ($error == true) {
952
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
953
		return false;
954
	}
955

    
956
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
957
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
958
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
959
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
960
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
961

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

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

    
982
	@ldap_unbind($ldap);
983

    
984
	return true;
985
}
986

    
987
function ldap_get_user_ous($show_complete_ou=true, $authcfg) {
988
	global $debug, $config, $g;
989

    
990
	if (!function_exists("ldap_connect")) {
991
		return;
992
	}
993

    
994
	$ous = array();
995

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

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

    
1030
	/* Setup CA environment if needed. */
1031
	ldap_setup_caenv($authcfg);
1032

    
1033
	/* connect and see if server is up */
1034
	$error = false;
1035
	if (!($ldap = ldap_connect($ldapserver))) {
1036
		$error = true;
1037
	}
1038

    
1039
	if ($error == true) {
1040
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1041
		return $ous;
1042
	}
1043

    
1044
	$ldapfilter = "(|(ou=*)(cn=Users))";
1045

    
1046
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1047
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1048
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1049
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1050
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1051

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

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

    
1074
	if ($ldapscope == "one") {
1075
		$ldapfunc = "ldap_list";
1076
	} else {
1077
		$ldapfunc = "ldap_search";
1078
	}
1079

    
1080
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
1081
	$info = @ldap_get_entries($ldap, $search);
1082

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

    
1101
	@ldap_unbind($ldap);
1102

    
1103
	return $ous;
1104
}
1105

    
1106
function ldap_get_groups($username, $authcfg) {
1107
	global $debug, $config;
1108

    
1109
	if (!function_exists("ldap_connect")) {
1110
		return;
1111
	}
1112

    
1113
	if (!$username) {
1114
		return false;
1115
	}
1116

    
1117
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1118
		$username_split = explode("@", $username);
1119
		$username = $username_split[0];
1120
	}
1121

    
1122
	if (stristr($username, "\\")) {
1123
		$username_split = explode("\\", $username);
1124
		$username = $username_split[0];
1125
	}
1126

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

    
1165
	if (isset($authcfg['ldap_rfc2307'])) {
1166
		$ldapdn = $ldapbasedn;
1167
	} else {
1168
		$ldapdn = $_SESSION['ldapdn'];
1169
	}
1170

    
1171
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
1172
	$ldapgroupattribute = strtolower($ldapgroupattribute);
1173
	$memberof = array();
1174

    
1175
	/* Setup CA environment if needed. */
1176
	ldap_setup_caenv($authcfg);
1177

    
1178
	/* connect and see if server is up */
1179
	$error = false;
1180
	if (!($ldap = ldap_connect($ldapserver))) {
1181
		$error = true;
1182
	}
1183

    
1184
	if ($error == true) {
1185
		log_error(sprintf(gettext("ERROR! ldap_get_groups() Could not connect to server %s."), $ldapname));
1186
		return $memberof;
1187
	}
1188

    
1189
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1190
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1191
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1192
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1193
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1194

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

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

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

    
1228
	$search = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
1229
	$info = @ldap_get_entries($ldap, $search);
1230

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

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

    
1244
	/* Time to close LDAP connection */
1245
	@ldap_unbind($ldap);
1246

    
1247
	$groups = print_r($memberof, true);
1248

    
1249
	//log_error("Returning groups ".$groups." for user $username");
1250

    
1251
	return $memberof;
1252
}
1253

    
1254
function ldap_format_host($host) {
1255
	return is_ipaddrv6($host) ? "[$host]" : $host ;
1256
}
1257

    
1258
function ldap_backed($username, $passwd, $authcfg) {
1259
	global $debug, $config;
1260

    
1261
	if (!$username) {
1262
		return;
1263
	}
1264

    
1265
	if (!function_exists("ldap_connect")) {
1266
		return;
1267
	}
1268

    
1269
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1270
		$username_split = explode("@", $username);
1271
		$username = $username_split[0];
1272
	}
1273
	if (stristr($username, "\\")) {
1274
		$username_split = explode("\\", $username);
1275
		$username = $username_split[0];
1276
	}
1277

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

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

    
1325
		return false;
1326
	}
1327

    
1328
	/* Setup CA environment if needed. */
1329
	ldap_setup_caenv($authcfg);
1330

    
1331
	/* Make sure we can connect to LDAP */
1332
	$error = false;
1333
	if (!($ldap = ldap_connect($ldapserver))) {
1334
		$error = true;
1335
	}
1336

    
1337
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1338
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1339
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1340
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1341
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1342

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

    
1351
	if ($error == true) {
1352
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1353
		return false;
1354
	}
1355

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

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

    
1374
	/* Get LDAP Authcontainers and split em up. */
1375
	$ldac_splits = explode(";", $ldapauthcont);
1376

    
1377
	/* setup the usercount so we think we haven't found anyone yet */
1378
	$usercount = 0;
1379

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

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

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

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

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

    
1447
	return true;
1448
}
1449

    
1450
function radius_backed($username, $password, $authcfg, &$attributes = array()) {
1451
	global $debug, $config;
1452
	$ret = false;
1453

    
1454
	require_once("radius.inc");
1455
	require_once("Crypt/CHAP.php");
1456

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

    
1472
	// Create our instance
1473
	$classname = 'Auth_RADIUS_' . $radius_protocol;
1474
	$rauth = new $classname($username, $password);
1475

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

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

    
1497
		case 'MSCHAPv2':
1498
			$crpt = new Crypt_CHAP_MSv2;
1499
			$crpt->username = $username;
1500
			$crpt->password = $password;
1501
			$rauth->challenge = $crpt->authChallenge;
1502
			$rauth->peerChallenge = $crpt->peerChallenge;
1503
			$rauth->chapid = $crpt->chapid;
1504
			$rauth->response = $crpt->challengeResponse();
1505
			break;
1506

    
1507
		default:
1508
			$rauth->password = $password;
1509
			break;
1510
	}
1511

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

    
1520
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1521

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

    
1546
	// close OO RADIUS_AUTHENTICATION
1547
	$rauth->close();
1548

    
1549
	return $ret;
1550
}
1551

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

    
1567
		foreach ($groups as & $grp) {
1568
			$grp = trim($grp);
1569
			if (strtolower(substr($grp, 0, 3)) == "ou=") {
1570
				$grp = substr($grp, 3);
1571
			}
1572
		}
1573
	}
1574
	return $groups;
1575
}
1576

    
1577
function get_user_expiration_date($username) {
1578
	$user = getUserEntry($username);
1579
	if ($user['expires']) {
1580
		return $user['expires'];
1581
	}
1582
}
1583

    
1584
function is_account_expired($username) {
1585
	$expirydate = get_user_expiration_date($username);
1586
	if ($expirydate) {
1587
		if (strtotime("-1 day") > strtotime(date("m/d/Y", strtotime($expirydate)))) {
1588
			return true;
1589
		}
1590
	}
1591

    
1592
	return false;
1593
}
1594

    
1595
function is_account_disabled($username) {
1596
	$user = getUserEntry($username);
1597
	if (isset($user['disabled'])) {
1598
		return true;
1599
	}
1600

    
1601
	return false;
1602
}
1603

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

    
1650
	if ($settings['webgui']['dashboardcolumns'] < 1) {
1651
		$settings['webgui']['dashboardcolumns'] = 2;
1652
	}
1653

    
1654
	return $settings;
1655
}
1656

    
1657
function save_widget_settings($username, $settings, $message = "") {
1658
	global $config, $userindex;
1659
	$user = getUserEntry($username);
1660

    
1661
	if (strlen($message) > 0) {
1662
		$msgout = $message;
1663
	} else {
1664
		$msgout = gettext("Widget configuration has been changed.");
1665
	}
1666

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

    
1676
function auth_get_authserver($name) {
1677
	global $config;
1678

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

    
1691
function auth_get_authserver_list() {
1692
	global $config;
1693

    
1694
	$list = array();
1695

    
1696
	if (is_array($config['system']['authserver'])) {
1697
		foreach ($config['system']['authserver'] as $authcfg) {
1698
			/* Add support for disabled entries? */
1699
			$list[$authcfg['name']] = $authcfg;
1700
		}
1701
	}
1702

    
1703
	$list["Local Database"] = array("name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']);
1704
	return $list;
1705
}
1706

    
1707
function getUserGroups($username, $authcfg, &$attributes = array()) {
1708
	global $config;
1709

    
1710
	$allowed_groups = array();
1711

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

    
1725
	$member_groups = array();
1726
	if (is_array($config['system']['group'])) {
1727
		foreach ($config['system']['group'] as $group) {
1728
			if (in_array($group['name'], $allowed_groups)) {
1729
				$member_groups[] = $group['name'];
1730
			}
1731
		}
1732
	}
1733

    
1734
	return $member_groups;
1735
}
1736

    
1737
function authenticate_user($username, $password, $authcfg = NULL, &$attributes = array()) {
1738

    
1739
	if (is_array($username) || is_array($password)) {
1740
		return false;
1741
	}
1742

    
1743
	if (!$authcfg) {
1744
		return local_backed($username, $password);
1745
	}
1746

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

    
1767
	return $authenticated;
1768
}
1769

    
1770
function session_auth() {
1771
	global $config, $_SESSION, $page;
1772

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

    
1783
	phpsession_begin();
1784

    
1785
	// Detect protocol change
1786
	if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) {
1787
		phpsession_end();
1788
		return false;
1789
	}
1790

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

    
1829
	/* Show login page if they aren't logged in */
1830
	if (empty($_SESSION['Logged_In'])) {
1831
		phpsession_end(true);
1832
		return false;
1833
	}
1834

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

    
1862
	/* user hit the logout button */
1863
	if (isset($_POST['logout'])) {
1864

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

    
1871
		/* wipe out $_SESSION */
1872
		$_SESSION = array();
1873

    
1874
		if (isset($_COOKIE[session_name()])) {
1875
			setcookie(session_name(), '', time()-42000, '/');
1876
		}
1877

    
1878
		/* and destroy it */
1879
		phpsession_destroy();
1880

    
1881
		$scriptName = explode("/", $_SERVER["SCRIPT_FILENAME"]);
1882
		$scriptElms = count($scriptName);
1883
		$scriptName = $scriptName[$scriptElms-1];
1884

    
1885
		if (isAjax()) {
1886
			return false;
1887
		}
1888

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

    
1892
		return false;
1893
	}
1894

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

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

    
1914
?>
(1-1/54)