Project

General

Profile

Download (56.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-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($u2add, $u2del, $g2add, $g2del) {
421
	global $config, $debug;
422

    
423
	if (empty($u2add) && empty($u2del) && empty($g2add) && empty($g2del)) {
424
		/* Nothing to be done here */
425
		return;
426
	}
427

    
428
	foreach($u2del as $user) {
429
		if ($user['uid'] < 2000 || $user['uid'] > 65000) {
430
			continue;
431
		}
432

    
433
		/*
434
		 * If a crontab was created to user, pw userdel will be
435
		 * interactive and can cause issues. Just remove crontab
436
		 * before run it when necessary
437
		 */
438
		unlink_if_exists("/var/cron/tabs/{$user['name']}");
439
		$cmd = "/usr/sbin/pw userdel -n " .
440
		    escapeshellarg($user['name']);
441
		if ($debug) {
442
			log_error(sprintf(gettext("Running: %s"), $cmd));
443
		}
444
		mwexec($cmd);
445
		local_group_del_user($user);
446

    
447
		$system_user = $config['system']['user'];
448
		for ($i = 0; $i < count($system_user); $i++) {
449
			if ($system_user[$i]['name'] == $user['name']) {
450
				unset($config['system']['user'][$i]);
451
				break;
452
			}
453
		}
454
	}
455

    
456
	foreach($g2del as $group) {
457
		if ($group['gid'] < 1999 || $group['gid'] > 65000) {
458
			continue;
459
		}
460

    
461
		$cmd = "/usr/sbin/pw groupdel -g " .
462
		    escapeshellarg($group['name']);
463
		if ($debug) {
464
			log_error(sprintf(gettext("Running: %s"), $cmd));
465
		}
466
		mwexec($cmd);
467

    
468
		$system_group = $config['system']['group'];
469
		for ($i = 0; $i < count($system_group); $i++) {
470
			if ($system_group[$i]['name'] == $group['name']) {
471
				unset($config['system']['group'][$i]);
472
				break;
473
			}
474
		}
475
	}
476

    
477
	foreach ($u2add as $user) {
478
		$config['system']['user'][] = $user;
479
	}
480

    
481
	foreach ($g2add as $group) {
482
		$config['system']['group'][] = $group;
483
	}
484

    
485
	write_config("Sync'd users and groups via XMLRPC");
486

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

    
491
	foreach ($u2add as $user) {
492
		local_user_set($user);
493
	}
494

    
495
	foreach ($g2add as $group) {
496
		local_group_set($group);
497
	}
498
}
499

    
500
function local_reset_accounts() {
501
	global $debug, $config;
502

    
503
	/* remove local users to avoid uid conflicts */
504
	$fd = popen("/usr/sbin/pw usershow -a", "r");
505
	if ($fd) {
506
		while (!feof($fd)) {
507
			$line = explode(":", fgets($fd));
508
			if ($line[0] != "admin") {
509
				if (!strncmp($line[0], "_", 1)) {
510
					continue;
511
				}
512
				if ($line[2] < 2000) {
513
					continue;
514
				}
515
				if ($line[2] > 65000) {
516
					continue;
517
				}
518
			}
519
			/*
520
			 * If a crontab was created to user, pw userdel will be interactive and
521
			 * can cause issues. Just remove crontab before run it when necessary
522
			 */
523
			unlink_if_exists("/var/cron/tabs/{$line[0]}");
524
			$cmd = "/usr/sbin/pw userdel -n " . escapeshellarg($line[0]);
525
			if ($debug) {
526
				log_error(sprintf(gettext("Running: %s"), $cmd));
527
			}
528
			mwexec($cmd);
529
		}
530
		pclose($fd);
531
	}
532

    
533
	/* remove local groups to avoid gid conflicts */
534
	$gids = array();
535
	$fd = popen("/usr/sbin/pw groupshow -a", "r");
536
	if ($fd) {
537
		while (!feof($fd)) {
538
			$line = explode(":", fgets($fd));
539
			if (!strncmp($line[0], "_", 1)) {
540
				continue;
541
			}
542
			if ($line[2] < 2000) {
543
				continue;
544
			}
545
			if ($line[2] > 65000) {
546
				continue;
547
			}
548
			$cmd = "/usr/sbin/pw groupdel -g " . escapeshellarg($line[2]);
549
			if ($debug) {
550
				log_error(sprintf(gettext("Running: %s"), $cmd));
551
			}
552
			mwexec($cmd);
553
		}
554
		pclose($fd);
555
	}
556

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

    
561
	/* sync all local users */
562
	if (is_array($config['system']['user'])) {
563
		foreach ($config['system']['user'] as $user) {
564
			local_user_set($user);
565
		}
566
	}
567

    
568
	/* sync all local groups */
569
	if (is_array($config['system']['group'])) {
570
		foreach ($config['system']['group'] as $group) {
571
			local_group_set($group);
572
		}
573
	}
574
}
575

    
576
function local_user_set(& $user) {
577
	global $g, $debug;
578

    
579
	if (empty($user['password']) && empty($user['bcrypt-hash'])) {
580
		log_error("There is something wrong in the config because user {$user['name']} password is missing!");
581
		return;
582
	}
583

    
584

    
585
	$home_base = "/home/";
586
	$user_uid = $user['uid'];
587
	$user_name = $user['name'];
588
	$user_home = "{$home_base}{$user_name}";
589
	$user_shell = "/etc/rc.initial";
590
	$user_group = "nobody";
591

    
592
	// Ensure $home_base exists and is writable
593
	if (!is_dir($home_base)) {
594
		mkdir($home_base, 0755);
595
	}
596

    
597
	$lock_account = false;
598
	/* configure shell type */
599
	/* Cases here should be ordered by most privileged to least privileged. */
600
	if (userHasPrivilege($user, "user-shell-access") || userHasPrivilege($user, "page-all")) {
601
		$user_shell = "/bin/tcsh";
602
	} elseif (userHasPrivilege($user, "user-copy-files-chroot")) {
603
		$user_shell = "/usr/local/sbin/scponlyc";
604
	} elseif (userHasPrivilege($user, "user-copy-files")) {
605
		$user_shell = "/usr/local/bin/scponly";
606
	} elseif (userHasPrivilege($user, "user-ssh-tunnel")) {
607
		$user_shell = "/usr/local/sbin/ssh_tunnel_shell";
608
	} elseif (userHasPrivilege($user, "user-ipsec-xauth-dialin")) {
609
		$user_shell = "/sbin/nologin";
610
	} else {
611
		$user_shell = "/sbin/nologin";
612
		$lock_account = true;
613
	}
614

    
615
	/* Lock out disabled or expired users, unless it's root/admin. */
616
	if ((is_account_disabled($user_name) || is_account_expired($user_name)) && ($user_uid != 0)) {
617
		$user_shell = "/sbin/nologin";
618
		$lock_account = true;
619
	}
620

    
621
	/* root user special handling */
622
	if ($user_uid == 0) {
623
		$cmd = "/usr/sbin/pw usermod -q -n root -s /bin/sh -H 0";
624
		if ($debug) {
625
			log_error(sprintf(gettext("Running: %s"), $cmd));
626
		}
627
		$fd = popen($cmd, "w");
628
		if (empty($user['bcrypt-hash'])) {
629
			fwrite($fd, $user['password']);
630
		} else {
631
			fwrite($fd, $user['bcrypt-hash']);
632
		}
633
		pclose($fd);
634
		$user_group = "wheel";
635
		$user_home = "/root";
636
		$user_shell = "/etc/rc.initial";
637
	}
638

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

    
645
	$skel_dir = '/etc/skel';
646

    
647
	/* determine add or mod */
648
	if (($userattrs[0] != $user['name']) || (!strncmp($pwread, "pw:", 3))) {
649
		$user_op = "useradd -m -k " . escapeshellarg($skel_dir) . " -o";
650
	} else {
651
		$user_op = "usermod";
652
	}
653

    
654
	$comment = str_replace(array(":", "!", "@"), " ", $user['descr']);
655
	/* add or mod pw db */
656
	$cmd = "/usr/sbin/pw {$user_op} -q " .
657
			" -u " . escapeshellarg($user_uid) .
658
			" -n " . escapeshellarg($user_name) .
659
			" -g " . escapeshellarg($user_group) .
660
			" -s " . escapeshellarg($user_shell) .
661
			" -d " . escapeshellarg($user_home) .
662
			" -c " . escapeshellarg($comment) .
663
			" -H 0 2>&1";
664

    
665
	if ($debug) {
666
		log_error(sprintf(gettext("Running: %s"), $cmd));
667
	}
668
	$fd = popen($cmd, "w");
669
	if (empty($user['bcrypt-hash'])) {
670
		fwrite($fd, $user['password']);
671
	} else {
672
		fwrite($fd, $user['bcrypt-hash']);
673
	}
674
	pclose($fd);
675

    
676
	/* create user directory if required */
677
	if (!is_dir($user_home)) {
678
		mkdir($user_home, 0700);
679
	}
680
	@chown($user_home, $user_name);
681
	@chgrp($user_home, $user_group);
682

    
683
	/* Make sure all users have last version of config files */
684
	foreach (glob("{$skel_dir}/dot.*") as $dot_file) {
685
		$target = $user_home . '/' . substr(basename($dot_file), 3);
686
		@copy($dot_file, $target);
687
		@chown($target, $user_name);
688
		@chgrp($target, $user_group);
689
	}
690

    
691
	/* write out ssh authorized key file */
692
	if ($user['authorizedkeys']) {
693
		if (!is_dir("{$user_home}/.ssh")) {
694
			@mkdir("{$user_home}/.ssh", 0700);
695
			@chown("{$user_home}/.ssh", $user_name);
696
		}
697
		$keys = base64_decode($user['authorizedkeys']);
698
		@file_put_contents("{$user_home}/.ssh/authorized_keys", $keys);
699
		@chown("{$user_home}/.ssh/authorized_keys", $user_name);
700
	} else {
701
		unlink_if_exists("{$user_home}/.ssh/authorized_keys");
702
	}
703

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

    
707
}
708

    
709
function local_user_del($user) {
710
	global $debug;
711

    
712
	/* remove all memberships */
713
	local_user_set_groups($user);
714

    
715
	/* Don't remove /root */
716
	if ($user['uid'] != 0) {
717
		$rmhome = "-r";
718
	}
719

    
720
	/* read from pw db */
721
	$fd = popen("/usr/sbin/pw usershow -n {$user['name']} 2>&1", "r");
722
	$pwread = fgets($fd);
723
	pclose($fd);
724
	$userattrs = explode(":", trim($pwread));
725

    
726
	if ($userattrs[0] != $user['name']) {
727
		log_error("Tried to remove user {$user['name']} but got user {$userattrs[0]} instead. Bailing.");
728
		return;
729
	}
730

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

    
734
	if ($debug) {
735
		log_error(sprintf(gettext("Running: %s"), $cmd));
736
	}
737
	mwexec($cmd);
738

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

    
743
function local_user_set_password(&$user, $password) {
744

    
745
	unset($user['password']);
746
	unset($user['md5-hash']);
747
	$user['bcrypt-hash'] = password_hash($password, PASSWORD_BCRYPT);
748

    
749
	/* Maintain compatibility with FreeBSD - change $2y$ prefix to $2b$
750
	 * https://reviews.freebsd.org/D2742
751
	 * XXX: Can be removed as soon as r284483 is MFC'd.
752
	 */
753
	if ($user['bcrypt-hash'][2] == "y") {
754
		$user['bcrypt-hash'][2] = "b";
755
	}
756

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

    
765
}
766

    
767
function local_user_get_groups($user, $all = false) {
768
	global $debug, $config;
769

    
770
	$groups = array();
771
	if (!is_array($config['system']['group'])) {
772
		return $groups;
773
	}
774

    
775
	foreach ($config['system']['group'] as $group) {
776
		if ($all || (!$all && ($group['name'] != "all"))) {
777
			if (is_array($group['member'])) {
778
				if (in_array($user['uid'], $group['member'])) {
779
					$groups[] = $group['name'];
780
				}
781
			}
782
		}
783
	}
784

    
785
	if ($all) {
786
		$groups[] = "all";
787
	}
788

    
789
	sort($groups);
790

    
791
	return $groups;
792

    
793
}
794

    
795
function local_user_set_groups($user, $new_groups = NULL) {
796
	global $debug, $config, $groupindex;
797

    
798
	if (!is_array($config['system']['group'])) {
799
		return;
800
	}
801

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

    
805
	if (!is_array($new_groups)) {
806
		$new_groups = array();
807
	}
808

    
809
	if (!is_array($cur_groups)) {
810
		$cur_groups = array();
811
	}
812

    
813
	/* determine which memberships to add */
814
	foreach ($new_groups as $groupname) {
815
		if ($groupname == '' || in_array($groupname, $cur_groups)) {
816
			continue;
817
		}
818
		$group = & $config['system']['group'][$groupindex[$groupname]];
819
		$group['member'][] = $user['uid'];
820
		$mod_groups[] = $group;
821
	}
822
	unset($group);
823

    
824
	/* determine which memberships to remove */
825
	foreach ($cur_groups as $groupname) {
826
		if (in_array($groupname, $new_groups)) {
827
			continue;
828
		}
829
		if (!isset($config['system']['group'][$groupindex[$groupname]])) {
830
			continue;
831
		}
832
		$group = & $config['system']['group'][$groupindex[$groupname]];
833
		if (is_array($group['member'])) {
834
			$index = array_search($user['uid'], $group['member']);
835
			array_splice($group['member'], $index, 1);
836
			$mod_groups[] = $group;
837
		}
838
	}
839
	unset($group);
840

    
841
	/* sync all modified groups */
842
	foreach ($mod_groups as $group) {
843
		local_group_set($group);
844
	}
845
}
846

    
847
function local_group_del_user($user) {
848
	global $config;
849

    
850
	if (!is_array($config['system']['group'])) {
851
		return;
852
	}
853

    
854
	foreach ($config['system']['group'] as $group) {
855
		if (is_array($group['member'])) {
856
			foreach ($group['member'] as $idx => $uid) {
857
				if ($user['uid'] == $uid) {
858
					unset($config['system']['group']['member'][$idx]);
859
				}
860
			}
861
		}
862
	}
863
}
864

    
865
function local_group_set($group, $reset = false) {
866
	global $debug;
867

    
868
	$group_name = $group['name'];
869
	$group_gid = $group['gid'];
870
	$group_members = '';
871
	if (!$reset && !empty($group['member']) && count($group['member']) > 0) {
872
		$group_members = implode(",", $group['member']);
873
	}
874

    
875
	if (empty($group_name) || $group['scope'] == "remote") {
876
		return;
877
	}
878

    
879
	/* determine add or mod */
880
	if (mwexec("/usr/sbin/pw groupshow -g " . escapeshellarg($group_gid) . " 2>&1", true) == 0) {
881
		$group_op = "groupmod -l";
882
	} else {
883
		$group_op = "groupadd -n";
884
	}
885

    
886
	/* add or mod group db */
887
	$cmd = "/usr/sbin/pw {$group_op} " .
888
		escapeshellarg($group_name) .
889
		" -g " . escapeshellarg($group_gid) .
890
		" -M " . escapeshellarg($group_members) . " 2>&1";
891

    
892
	if ($debug) {
893
		log_error(sprintf(gettext("Running: %s"), $cmd));
894
	}
895
	mwexec($cmd);
896

    
897
}
898

    
899
function local_group_del($group) {
900
	global $debug;
901

    
902
	/* delete from group db */
903
	$cmd = "/usr/sbin/pw groupdel " . escapeshellarg($group['name']);
904

    
905
	if ($debug) {
906
		log_error(sprintf(gettext("Running: %s"), $cmd));
907
	}
908
	mwexec($cmd);
909
}
910

    
911
function ldap_test_connection($authcfg) {
912
	global $debug, $config, $g;
913

    
914
	if ($authcfg) {
915
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
916
			$ldapproto = "ldaps";
917
		} else {
918
			$ldapproto = "ldap";
919
		}
920
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
921
		$ldapport = $authcfg['ldap_port'];
922
		if (!empty($ldapport)) {
923
			$ldapserver .= ":{$ldapport}";
924
		}
925
		$ldapbasedn = $authcfg['ldap_basedn'];
926
		$ldapbindun = $authcfg['ldap_binddn'];
927
		$ldapbindpw = $authcfg['ldap_bindpw'];
928
	} else {
929
		return false;
930
	}
931

    
932
	/* first check if there is even an LDAP server populated */
933
	if (!$ldapserver) {
934
		return false;
935
	}
936

    
937
	/* Setup CA environment if needed. */
938
	ldap_setup_caenv($authcfg);
939

    
940
	/* connect and see if server is up */
941
	$error = false;
942
	if (!($ldap = ldap_connect($ldapserver))) {
943
		$error = true;
944
	}
945

    
946
	if ($error == true) {
947
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
948
		return false;
949
	}
950

    
951
	return true;
952
}
953

    
954
function ldap_setup_caenv($authcfg) {
955
	global $g;
956
	require_once("certs.inc");
957

    
958
	unset($caref);
959
	if (empty($authcfg['ldap_caref']) || strstr($authcfg['ldap_urltype'], "Standard")) {
960
		putenv('LDAPTLS_REQCERT=never');
961
		return;
962
	} elseif ($authcfg['ldap_caref'] == "global") {
963
		putenv('LDAPTLS_REQCERT=hard');
964
		putenv("LDAPTLS_CACERTDIR=/etc/ssl/");
965
		putenv("LDAPTLS_CACERT=/etc/ssl/cert.pem");
966
	} else {
967
		$caref = lookup_ca($authcfg['ldap_caref']);
968
		$param = array('caref' => $authcfg['ldap_caref']);
969
		$cachain = ca_chain($param);
970
		if (!$caref) {
971
			log_error(sprintf(gettext("LDAP: Could not lookup CA by reference for host %s."), $authcfg['ldap_caref']));
972
			/* XXX: Prevent for credential leaking since we cannot setup the CA env. Better way? */
973
			putenv('LDAPTLS_REQCERT=hard');
974
			return;
975
		}
976
		if (!is_dir("{$g['varrun_path']}/certs")) {
977
			@mkdir("{$g['varrun_path']}/certs");
978
		}
979
		if (file_exists("{$g['varrun_path']}/certs/{$caref['refid']}.ca")) {
980
			@unlink("{$g['varrun_path']}/certs/{$caref['refid']}.ca");
981
		}
982
		file_put_contents("{$g['varrun_path']}/certs/{$caref['refid']}.ca", $cachain);
983
		@chmod("{$g['varrun_path']}/certs/{$caref['refid']}.ca", 0600);
984
		putenv('LDAPTLS_REQCERT=hard');
985
		/* XXX: Probably even the hashed link should be created for this? */
986
		putenv("LDAPTLS_CACERTDIR={$g['varrun_path']}/certs");
987
		putenv("LDAPTLS_CACERT={$g['varrun_path']}/certs/{$caref['refid']}.ca");
988
	}
989
}
990

    
991
function ldap_test_bind($authcfg) {
992
	global $debug, $config, $g;
993

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

    
1019
	/* first check if there is even an LDAP server populated */
1020
	if (!$ldapserver) {
1021
		return false;
1022
	}
1023

    
1024
	/* Setup CA environment if needed. */
1025
	ldap_setup_caenv($authcfg);
1026

    
1027
	/* connect and see if server is up */
1028
	$error = false;
1029
	if (!($ldap = ldap_connect($ldapserver))) {
1030
		$error = true;
1031
	}
1032

    
1033
	if ($error == true) {
1034
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1035
		return false;
1036
	}
1037

    
1038
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1039
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1040
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1041
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1042
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1043

    
1044
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1045
		if (!(@ldap_start_tls($ldap))) {
1046
			log_error(sprintf(gettext("ERROR! ldap_test_bind() could not STARTTLS to server %s."), $ldapname));
1047
			@ldap_close($ldap);
1048
			return false;
1049
		}
1050
	}
1051

    
1052
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1053
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1054
	if ($ldapanon == true) {
1055
		if (!($res = @ldap_bind($ldap))) {
1056
			@ldap_close($ldap);
1057
			return false;
1058
		}
1059
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1060
		@ldap_close($ldap);
1061
		return false;
1062
	}
1063

    
1064
	@ldap_unbind($ldap);
1065

    
1066
	return true;
1067
}
1068

    
1069
function ldap_get_user_ous($show_complete_ou=true, $authcfg) {
1070
	global $debug, $config, $g;
1071

    
1072
	if (!function_exists("ldap_connect")) {
1073
		return;
1074
	}
1075

    
1076
	$ous = array();
1077

    
1078
	if ($authcfg) {
1079
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1080
			$ldapproto = "ldaps";
1081
		} else {
1082
			$ldapproto = "ldap";
1083
		}
1084
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1085
		$ldapport = $authcfg['ldap_port'];
1086
		if (!empty($ldapport)) {
1087
			$ldapserver .= ":{$ldapport}";
1088
		}
1089
		$ldapbasedn = $authcfg['ldap_basedn'];
1090
		$ldapbindun = $authcfg['ldap_binddn'];
1091
		$ldapbindpw = $authcfg['ldap_bindpw'];
1092
		$ldapver = $authcfg['ldap_protver'];
1093
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1094
			$ldapanon = true;
1095
		} else {
1096
			$ldapanon = false;
1097
		}
1098
		$ldapname = $authcfg['name'];
1099
		$ldapfallback = false;
1100
		$ldapscope = $authcfg['ldap_scope'];
1101
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1102
	} else {
1103
		return false;
1104
	}
1105

    
1106
	/* first check if there is even an LDAP server populated */
1107
	if (!$ldapserver) {
1108
		log_error(gettext("ERROR!  ldap_get_user_ous() backed selected with no LDAP authentication server defined."));
1109
		return $ous;
1110
	}
1111

    
1112
	/* Setup CA environment if needed. */
1113
	ldap_setup_caenv($authcfg);
1114

    
1115
	/* connect and see if server is up */
1116
	$error = false;
1117
	if (!($ldap = ldap_connect($ldapserver))) {
1118
		$error = true;
1119
	}
1120

    
1121
	if ($error == true) {
1122
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1123
		return $ous;
1124
	}
1125

    
1126
	$ldapfilter = "(|(ou=*)(cn=Users))";
1127

    
1128
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1129
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1130
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1131
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1132
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1133

    
1134
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1135
		if (!(@ldap_start_tls($ldap))) {
1136
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not STARTTLS to server %s."), $ldapname));
1137
			@ldap_close($ldap);
1138
			return false;
1139
		}
1140
	}
1141

    
1142
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1143
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1144
	if ($ldapanon == true) {
1145
		if (!($res = @ldap_bind($ldap))) {
1146
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind anonymously to server %s."), $ldapname));
1147
			@ldap_close($ldap);
1148
			return $ous;
1149
		}
1150
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1151
		log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind to server %s."), $ldapname));
1152
		@ldap_close($ldap);
1153
		return $ous;
1154
	}
1155

    
1156
	if ($ldapscope == "one") {
1157
		$ldapfunc = "ldap_list";
1158
	} else {
1159
		$ldapfunc = "ldap_search";
1160
	}
1161

    
1162
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
1163
	$info = @ldap_get_entries($ldap, $search);
1164

    
1165
	if (is_array($info)) {
1166
		foreach ($info as $inf) {
1167
			if (!$show_complete_ou) {
1168
				$inf_split = explode(",", $inf['dn']);
1169
				$ou = $inf_split[0];
1170
				$ou = str_replace("OU=", "", $ou);
1171
				$ou = str_replace("CN=", "", $ou);
1172
			} else {
1173
				if ($inf['dn']) {
1174
					$ou = $inf['dn'];
1175
				}
1176
			}
1177
			if ($ou) {
1178
				$ous[] = $ou;
1179
			}
1180
		}
1181
	}
1182

    
1183
	@ldap_unbind($ldap);
1184

    
1185
	return $ous;
1186
}
1187

    
1188
function ldap_get_groups($username, $authcfg) {
1189
	global $debug, $config;
1190

    
1191
	if (!function_exists("ldap_connect")) {
1192
		return;
1193
	}
1194

    
1195
	if (!$username) {
1196
		return false;
1197
	}
1198

    
1199
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1200
		$username_split = explode("@", $username);
1201
		$username = $username_split[0];
1202
	}
1203

    
1204
	if (stristr($username, "\\")) {
1205
		$username_split = explode("\\", $username);
1206
		$username = $username_split[0];
1207
	}
1208

    
1209
	//log_error("Getting LDAP groups for {$username}.");
1210
	if ($authcfg) {
1211
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1212
			$ldapproto = "ldaps";
1213
		} else {
1214
			$ldapproto = "ldap";
1215
		}
1216
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1217
		$ldapport = $authcfg['ldap_port'];
1218
		if (!empty($ldapport)) {
1219
			$ldapserver .= ":{$ldapport}";
1220
		}
1221
		$ldapbasedn = $authcfg['ldap_basedn'];
1222
		$ldapbindun = $authcfg['ldap_binddn'];
1223
		$ldapbindpw = $authcfg['ldap_bindpw'];
1224
		$ldapauthcont = $authcfg['ldap_authcn'];
1225
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1226
		$ldapgroupattribute = strtolower($authcfg['ldap_attr_member']);
1227
		if (isset($authcfg['ldap_rfc2307'])) {
1228
			$ldapfilter         = "(&(objectClass={$authcfg['ldap_attr_groupobj']})({$ldapgroupattribute}={$username}))";
1229
		} else {
1230
			$ldapfilter         = "({$ldapnameattribute}={$username})";
1231
		}
1232
		$ldaptype = "";
1233
		$ldapver = $authcfg['ldap_protver'];
1234
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1235
			$ldapanon = true;
1236
		} else {
1237
			$ldapanon = false;
1238
		}
1239
		$ldapname = $authcfg['name'];
1240
		$ldapfallback = false;
1241
		$ldapscope = $authcfg['ldap_scope'];
1242
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1243
	} else {
1244
		return false;
1245
	}
1246

    
1247
	if (isset($authcfg['ldap_rfc2307'])) {
1248
		$ldapdn = $ldapbasedn;
1249
	} else {
1250
		$ldapdn = $_SESSION['ldapdn'];
1251
	}
1252

    
1253
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
1254
	$ldapgroupattribute = strtolower($ldapgroupattribute);
1255
	$memberof = array();
1256

    
1257
	/* Setup CA environment if needed. */
1258
	ldap_setup_caenv($authcfg);
1259

    
1260
	/* connect and see if server is up */
1261
	$error = false;
1262
	if (!($ldap = ldap_connect($ldapserver))) {
1263
		$error = true;
1264
	}
1265

    
1266
	if ($error == true) {
1267
		log_error(sprintf(gettext("ERROR! ldap_get_groups() Could not connect to server %s."), $ldapname));
1268
		return $memberof;
1269
	}
1270

    
1271
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1272
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1273
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1274
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1275
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1276

    
1277
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1278
		if (!(@ldap_start_tls($ldap))) {
1279
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not STARTTLS to server %s."), $ldapname));
1280
			@ldap_close($ldap);
1281
			return false;
1282
		}
1283
	}
1284

    
1285
	/* bind as user that has rights to read group attributes */
1286
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1287
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1288
	if ($ldapanon == true) {
1289
		if (!($res = @ldap_bind($ldap))) {
1290
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind anonymously to server %s."), $ldapname));
1291
			@ldap_close($ldap);
1292
			return false;
1293
		}
1294
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1295
		log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind to server %s."), $ldapname));
1296
		@ldap_close($ldap);
1297
		return $memberof;
1298
	}
1299

    
1300
	/* get groups from DN found */
1301
	/* use ldap_read instead of search so we don't have to do a bunch of extra work */
1302
	/* since we know the DN is in $_SESSION['ldapdn'] */
1303
	//$search    = ldap_read($ldap, $ldapdn, "(objectclass=*)", array($ldapgroupattribute));
1304
	if ($ldapscope == "one") {
1305
		$ldapfunc = "ldap_list";
1306
	} else {
1307
		$ldapfunc = "ldap_search";
1308
	}
1309

    
1310
	$search = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
1311
	$info = @ldap_get_entries($ldap, $search);
1312

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

    
1315
	if (is_array($gresults)) {
1316
		/* Iterate through the groups and throw them into an array */
1317
		foreach ($gresults as $grp) {
1318
			if (((isset($authcfg['ldap_rfc2307'])) && (stristr($grp["dn"], "CN=") !== false)) ||
1319
			    ((!isset($authcfg['ldap_rfc2307'])) && (stristr($grp, "CN=") !== false))) {
1320
				$grpsplit = isset($authcfg['ldap_rfc2307']) ? explode(",", $grp["dn"]) : explode(",", $grp);
1321
				$memberof[] = preg_replace("/CN=/i", "", $grpsplit[0]);
1322
			}
1323
		}
1324
	}
1325

    
1326
	/* Time to close LDAP connection */
1327
	@ldap_unbind($ldap);
1328

    
1329
	$groups = print_r($memberof, true);
1330

    
1331
	//log_error("Returning groups ".$groups." for user $username");
1332

    
1333
	return $memberof;
1334
}
1335

    
1336
function ldap_format_host($host) {
1337
	return is_ipaddrv6($host) ? "[$host]" : $host ;
1338
}
1339

    
1340
function ldap_backed($username, $passwd, $authcfg) {
1341
	global $debug, $config;
1342

    
1343
	if (!$username) {
1344
		return;
1345
	}
1346

    
1347
	if (!function_exists("ldap_connect")) {
1348
		return;
1349
	}
1350

    
1351
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1352
		$username_split = explode("@", $username);
1353
		$username = $username_split[0];
1354
	}
1355
	if (stristr($username, "\\")) {
1356
		$username_split = explode("\\", $username);
1357
		$username = $username_split[0];
1358
	}
1359

    
1360
	if ($authcfg) {
1361
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1362
			$ldapproto = "ldaps";
1363
		} else {
1364
			$ldapproto = "ldap";
1365
		}
1366
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1367
		$ldapport = $authcfg['ldap_port'];
1368
		if (!empty($ldapport)) {
1369
			$ldapserver .= ":{$ldapport}";
1370
		}
1371
		$ldapbasedn = $authcfg['ldap_basedn'];
1372
		$ldapbindun = $authcfg['ldap_binddn'];
1373
		$ldapbindpw = $authcfg['ldap_bindpw'];
1374
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1375
			$ldapanon = true;
1376
		} else {
1377
			$ldapanon = false;
1378
		}
1379
		$ldapauthcont = $authcfg['ldap_authcn'];
1380
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1381
		$ldapextendedqueryenabled = $authcfg['ldap_extended_enabled'];
1382
		$ldapextendedquery = $authcfg['ldap_extended_query'];
1383
		$ldapfilter = "";
1384
		if (!$ldapextendedqueryenabled) {
1385
			$ldapfilter = "({$ldapnameattribute}={$username})";
1386
		} else {
1387
			$ldapfilter = "(&({$ldapnameattribute}={$username})({$ldapextendedquery}))";
1388
		}
1389
		$ldaptype = "";
1390
		$ldapver = $authcfg['ldap_protver'];
1391
		$ldapname = $authcfg['name'];
1392
		$ldapscope = $authcfg['ldap_scope'];
1393
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1394
	} else {
1395
		return false;
1396
	}
1397

    
1398
	/* first check if there is even an LDAP server populated */
1399
	if (!$ldapserver) {
1400
		if ($ldapfallback) {
1401
			log_error(gettext("ERROR! ldap_backed() called with no LDAP authentication server defined.  Defaulting to local user database. Visit System -> User Manager."));
1402
			return local_backed($username, $passwd);
1403
		} else {
1404
			log_error(gettext("ERROR! ldap_backed() called with no LDAP authentication server defined."));
1405
		}
1406

    
1407
		return false;
1408
	}
1409

    
1410
	/* Setup CA environment if needed. */
1411
	ldap_setup_caenv($authcfg);
1412

    
1413
	/* Make sure we can connect to LDAP */
1414
	$error = false;
1415
	if (!($ldap = ldap_connect($ldapserver))) {
1416
		$error = true;
1417
	}
1418

    
1419
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1420
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1421
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1422
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1423
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1424

    
1425
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1426
		if (!(@ldap_start_tls($ldap))) {
1427
			log_error(sprintf(gettext("ERROR! ldap_backed() could not STARTTLS to server %s."), $ldapname));
1428
			@ldap_close($ldap);
1429
			return false;
1430
		}
1431
	}
1432

    
1433
	if ($error == true) {
1434
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1435
		return false;
1436
	}
1437

    
1438
	/* ok, its up.  now, lets bind as the bind user so we can search it */
1439
	$error = false;
1440
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1441
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1442
	if ($ldapanon == true) {
1443
		if (!($res = @ldap_bind($ldap))) {
1444
			$error = true;
1445
		}
1446
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1447
		$error = true;
1448
	}
1449

    
1450
	if ($error == true) {
1451
		@ldap_close($ldap);
1452
		log_error(sprintf(gettext("ERROR! Could not bind to server %s."), $ldapname));
1453
		return false;
1454
	}
1455

    
1456
	/* Get LDAP Authcontainers and split em up. */
1457
	$ldac_splits = explode(";", $ldapauthcont);
1458

    
1459
	/* setup the usercount so we think we haven't found anyone yet */
1460
	$usercount = 0;
1461

    
1462
	/*****************************************************************/
1463
	/*  We first find the user based on username and filter          */
1464
	/*  then, once we find the first occurrence of that person       */
1465
	/*  we set session variables to point to the OU and DN of the    */
1466
	/*  person.  To later be used by ldap_get_groups.                */
1467
	/*  that way we don't have to search twice.                      */
1468
	/*****************************************************************/
1469
	if ($debug) {
1470
		log_auth(sprintf(gettext("Now Searching for %s in directory."), $username));
1471
	}
1472
	/* Iterate through the user containers for search */
1473
	foreach ($ldac_splits as $i => $ldac_split) {
1474
		$ldac_split = isset($authcfg['ldap_utf8']) ? utf8_encode($ldac_split) : $ldac_split;
1475
		$ldapfilter = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapfilter) : $ldapfilter;
1476
		$ldapsearchbasedn = isset($authcfg['ldap_utf8']) ? utf8_encode("{$ldac_split},{$ldapbasedn}") : "{$ldac_split},{$ldapbasedn}";
1477
		/* Make sure we just use the first user we find */
1478
		if ($debug) {
1479
			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)));
1480
		}
1481
		if ($ldapscope == "one") {
1482
			$ldapfunc = "ldap_list";
1483
		} else {
1484
			$ldapfunc = "ldap_search";
1485
		}
1486
		/* Support legacy auth container specification. */
1487
		if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) {
1488
			$search = @$ldapfunc($ldap, $ldac_split, $ldapfilter);
1489
		} else {
1490
			$search = @$ldapfunc($ldap, $ldapsearchbasedn, $ldapfilter);
1491
		}
1492
		if (!$search) {
1493
			log_error(sprintf(gettext("Search resulted in error: %s"), ldap_error($ldap)));
1494
			continue;
1495
		}
1496
		$info = ldap_get_entries($ldap, $search);
1497
		$matches = $info['count'];
1498
		if ($matches == 1) {
1499
			$userdn = $_SESSION['ldapdn'] = $info[0]['dn'];
1500
			$_SESSION['ldapou'] = $ldac_split[$i];
1501
			$_SESSION['ldapon'] = "true";
1502
			$usercount = 1;
1503
			break;
1504
		}
1505
	}
1506

    
1507
	if ($usercount != 1) {
1508
		@ldap_unbind($ldap);
1509
		log_error(gettext("ERROR! Either LDAP search failed, or multiple users were found."));
1510
		return false;
1511
	}
1512

    
1513
	/* Now lets bind as the user we found */
1514
	$passwd = isset($authcfg['ldap_utf8']) ? utf8_encode($passwd) : $passwd;
1515
	if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
1516
		log_error(sprintf(gettext('ERROR! Could not login to server %1$s as user %2$s: %3$s'), $ldapname, $username, ldap_error($ldap)));
1517
		@ldap_unbind($ldap);
1518
		return false;
1519
	}
1520

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

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

    
1529
	return true;
1530
}
1531

    
1532
function radius_backed($username, $password, $authcfg, &$attributes = array()) {
1533
	global $debug, $config;
1534
	$ret = false;
1535

    
1536
	require_once("radius.inc");
1537
	require_once("Crypt/CHAP.php");
1538

    
1539
	if ($authcfg) {
1540
		$radiusservers = array();
1541
		$radiusservers[0]['ipaddr'] = $authcfg['host'];
1542
		$radiusservers[0]['port'] = $authcfg['radius_auth_port'];
1543
		$radiusservers[0]['sharedsecret'] = $authcfg['radius_secret'];
1544
		$radiusservers[0]['timeout'] = $authcfg['radius_timeout'];
1545
		if(isset($authcfg['radius_protocol'])) {
1546
			$radius_protocol = $authcfg['radius_protocol'];
1547
		} else {
1548
			$radius_protocol = 'PAP';
1549
		}
1550
	} else {
1551
		return false;
1552
	}
1553

    
1554
	// Create our instance
1555
	$classname = 'Auth_RADIUS_' . $radius_protocol;
1556
	$rauth = new $classname($username, $password);
1557

    
1558
	/* Add new servers to our instance */
1559
	foreach ($radiusservers as $radsrv) {
1560
		$timeout = (is_numeric($radsrv['timeout'])) ? $radsrv['timeout'] : 5;
1561
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret'], $timeout);
1562
	}
1563

    
1564
	// Construct data package
1565
	$rauth->username = $username;
1566
	switch ($radius_protocol) {
1567
		case 'CHAP_MD5':
1568
		case 'MSCHAPv1':
1569
			$classname = $radius_protocol == 'MSCHAPv1' ? 'Crypt_CHAP_MSv1' : 'Crypt_CHAP_MD5';
1570
			$crpt = new $classname;
1571
			$crpt->username = $username;
1572
			$crpt->password = $password;
1573
			$rauth->challenge = $crpt->challenge;
1574
			$rauth->chapid = $crpt->chapid;
1575
			$rauth->response = $crpt->challengeResponse();
1576
			$rauth->flags = 1;
1577
			break;
1578

    
1579
		case 'MSCHAPv2':
1580
			$crpt = new Crypt_CHAP_MSv2;
1581
			$crpt->username = $username;
1582
			$crpt->password = $password;
1583
			$rauth->challenge = $crpt->authChallenge;
1584
			$rauth->peerChallenge = $crpt->peerChallenge;
1585
			$rauth->chapid = $crpt->chapid;
1586
			$rauth->response = $crpt->challengeResponse();
1587
			break;
1588

    
1589
		default:
1590
			$rauth->password = $password;
1591
			break;
1592
	}
1593

    
1594
	if (PEAR::isError($rauth->start())) {
1595
		$retvalue['auth_val'] = 1;
1596
		$retvalue['error'] = $rauth->getError();
1597
		if ($debug) {
1598
			printf(gettext("RADIUS start: %s") . "<br />\n", $retvalue['error']);
1599
		}
1600
	}
1601

    
1602
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1603

    
1604
	/* Send request */
1605
	$result = $rauth->send();
1606
	if (PEAR::isError($result)) {
1607
		$retvalue['auth_val'] = 1;
1608
		$retvalue['error'] = $result->getMessage();
1609
		if ($debug) {
1610
			printf(gettext("RADIUS send failed: %s") . "<br />\n", $retvalue['error']);
1611
		}
1612
	} else if ($result === true) {
1613
		if ($rauth->getAttributes()) {
1614
			$attributes = $rauth->listAttributes();
1615
		}
1616
		$retvalue['auth_val'] = 2;
1617
		if ($debug) {
1618
			printf(gettext("RADIUS Auth succeeded")."<br />\n");
1619
		}
1620
		$ret = true;
1621
	} else {
1622
		$retvalue['auth_val'] = 3;
1623
		if ($debug) {
1624
			printf(gettext("RADIUS Auth rejected")."<br />\n");
1625
		}
1626
	}
1627

    
1628
	// close OO RADIUS_AUTHENTICATION
1629
	$rauth->close();
1630

    
1631
	return $ret;
1632
}
1633

    
1634
/*
1635
	$attributes must contain a "class" key containing the groups and local
1636
	groups must exist to match.
1637
*/
1638
function radius_get_groups($attributes) {
1639
	$groups = array();
1640
	if (!empty($attributes) && is_array($attributes) && (!empty($attributes['class']) || !empty($attributes['class_int']))) {
1641
		/* Some RADIUS servers return multiple class attributes, so check them all. */
1642
		$groups = array();
1643
		if (!empty($attributes['class']) && is_array($attributes['class'])) {
1644
			foreach ($attributes['class'] as $class) {
1645
				$groups = array_unique(array_merge($groups, explode(";", $class)));
1646
			}
1647
		}
1648

    
1649
		foreach ($groups as & $grp) {
1650
			$grp = trim($grp);
1651
			if (strtolower(substr($grp, 0, 3)) == "ou=") {
1652
				$grp = substr($grp, 3);
1653
			}
1654
		}
1655
	}
1656
	return $groups;
1657
}
1658

    
1659
function get_user_expiration_date($username) {
1660
	$user = getUserEntry($username);
1661
	if ($user['expires']) {
1662
		return $user['expires'];
1663
	}
1664
}
1665

    
1666
function is_account_expired($username) {
1667
	$expirydate = get_user_expiration_date($username);
1668
	if ($expirydate) {
1669
		if (strtotime("-1 day") > strtotime(date("m/d/Y", strtotime($expirydate)))) {
1670
			return true;
1671
		}
1672
	}
1673

    
1674
	return false;
1675
}
1676

    
1677
function is_account_disabled($username) {
1678
	$user = getUserEntry($username);
1679
	if (isset($user['disabled'])) {
1680
		return true;
1681
	}
1682

    
1683
	return false;
1684
}
1685

    
1686
function get_user_settings($username) {
1687
	global $config;
1688
	$settings = array();
1689
	$settings['widgets'] = $config['widgets'];
1690
	$settings['webgui']['dashboardcolumns'] = $config['system']['webgui']['dashboardcolumns'];
1691
	$settings['webgui']['webguihostnamemenu'] = $config['system']['webgui']['webguihostnamemenu'];
1692
	$settings['webgui']['webguicss'] = $config['system']['webgui']['webguicss'];
1693
	$settings['webgui']['logincss'] = $config['system']['webgui']['logincss'];
1694
	$settings['webgui']['interfacessort'] = isset($config['system']['webgui']['interfacessort']);
1695
	$settings['webgui']['dashboardavailablewidgetspanel'] = isset($config['system']['webgui']['dashboardavailablewidgetspanel']);
1696
	$settings['webgui']['webguifixedmenu'] = isset($config['system']['webgui']['webguifixedmenu']);
1697
	$settings['webgui']['webguileftcolumnhyper'] = isset($config['system']['webgui']['webguileftcolumnhyper']);
1698
	$settings['webgui']['disablealiaspopupdetail'] = isset($config['system']['webgui']['disablealiaspopupdetail']);
1699
	$settings['webgui']['systemlogsfilterpanel'] = isset($config['system']['webgui']['systemlogsfilterpanel']);
1700
	$settings['webgui']['systemlogsmanagelogpanel'] = isset($config['system']['webgui']['systemlogsmanagelogpanel']);
1701
	$settings['webgui']['statusmonitoringsettingspanel'] = isset($config['system']['webgui']['statusmonitoringsettingspanel']);
1702
	$settings['webgui']['pagenamefirst'] = isset($config['system']['webgui']['pagenamefirst']);
1703
	$user = getUserEntry($username);
1704
	if (isset($user['customsettings'])) {
1705
		$settings['customsettings'] = true;
1706
		if (isset($user['widgets'])) {
1707
			// This includes the 'sequence', and any widgetname-config per-widget settings.
1708
			$settings['widgets'] = $user['widgets'];
1709
		}
1710
		if (isset($user['dashboardcolumns'])) {
1711
			$settings['webgui']['dashboardcolumns'] = $user['dashboardcolumns'];
1712
		}
1713
		if (isset($user['webguicss'])) {
1714
			$settings['webgui']['webguicss'] = $user['webguicss'];
1715
		}
1716
		if (isset($user['webguihostnamemenu'])) {
1717
			$settings['webgui']['webguihostnamemenu'] = $user['webguihostnamemenu'];
1718
		}
1719
		$settings['webgui']['interfacessort'] = isset($user['interfacessort']);
1720
		$settings['webgui']['dashboardavailablewidgetspanel'] = isset($user['dashboardavailablewidgetspanel']);
1721
		$settings['webgui']['webguifixedmenu'] = isset($user['webguifixedmenu']);
1722
		$settings['webgui']['webguileftcolumnhyper'] = isset($user['webguileftcolumnhyper']);
1723
		$settings['webgui']['disablealiaspopupdetail'] = isset($user['disablealiaspopupdetail']);
1724
		$settings['webgui']['systemlogsfilterpanel'] = isset($user['systemlogsfilterpanel']);
1725
		$settings['webgui']['systemlogsmanagelogpanel'] = isset($user['systemlogsmanagelogpanel']);
1726
		$settings['webgui']['statusmonitoringsettingspanel'] = isset($user['statusmonitoringsettingspanel']);
1727
		$settings['webgui']['pagenamefirst'] = isset($user['pagenamefirst']);
1728
	} else {
1729
		$settings['customsettings'] = false;
1730
	}
1731

    
1732
	if ($settings['webgui']['dashboardcolumns'] < 1) {
1733
		$settings['webgui']['dashboardcolumns'] = 2;
1734
	}
1735

    
1736
	return $settings;
1737
}
1738

    
1739
function save_widget_settings($username, $settings, $message = "") {
1740
	global $config, $userindex;
1741
	$user = getUserEntry($username);
1742

    
1743
	if (strlen($message) > 0) {
1744
		$msgout = $message;
1745
	} else {
1746
		$msgout = gettext("Widget configuration has been changed.");
1747
	}
1748

    
1749
	if (isset($user['customsettings'])) {
1750
		$config['system']['user'][$userindex[$username]]['widgets'] = $settings;
1751
		write_config($msgout . " " . sprintf(gettext("(User %s)"), $username));
1752
	} else {
1753
		$config['widgets'] = $settings;
1754
		write_config($msgout);
1755
	}
1756
}
1757

    
1758
function auth_get_authserver($name) {
1759
	global $config;
1760

    
1761
	if (is_array($config['system']['authserver'])) {
1762
		foreach ($config['system']['authserver'] as $authcfg) {
1763
			if ($authcfg['name'] == $name) {
1764
				return $authcfg;
1765
			}
1766
		}
1767
	}
1768
	if ($name == "Local Database") {
1769
		return array("name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']);
1770
	}
1771
}
1772

    
1773
function auth_get_authserver_list() {
1774
	global $config;
1775

    
1776
	$list = array();
1777

    
1778
	if (is_array($config['system']['authserver'])) {
1779
		foreach ($config['system']['authserver'] as $authcfg) {
1780
			/* Add support for disabled entries? */
1781
			$list[$authcfg['name']] = $authcfg;
1782
		}
1783
	}
1784

    
1785
	$list["Local Database"] = array("name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']);
1786
	return $list;
1787
}
1788

    
1789
function getUserGroups($username, $authcfg, &$attributes = array()) {
1790
	global $config;
1791

    
1792
	$allowed_groups = array();
1793

    
1794
	switch ($authcfg['type']) {
1795
		case 'ldap':
1796
			$allowed_groups = @ldap_get_groups($username, $authcfg);
1797
			break;
1798
		case 'radius':
1799
			$allowed_groups = @radius_get_groups($attributes);
1800
			break;
1801
		default:
1802
			$user = getUserEntry($username);
1803
			$allowed_groups = @local_user_get_groups($user, true);
1804
			break;
1805
	}
1806

    
1807
	$member_groups = array();
1808
	if (is_array($config['system']['group'])) {
1809
		foreach ($config['system']['group'] as $group) {
1810
			if (in_array($group['name'], $allowed_groups)) {
1811
				$member_groups[] = $group['name'];
1812
			}
1813
		}
1814
	}
1815

    
1816
	return $member_groups;
1817
}
1818

    
1819
function authenticate_user($username, $password, $authcfg = NULL, &$attributes = array()) {
1820

    
1821
	if (is_array($username) || is_array($password)) {
1822
		return false;
1823
	}
1824

    
1825
	if (!$authcfg) {
1826
		return local_backed($username, $password);
1827
	}
1828

    
1829
	$authenticated = false;
1830
	switch ($authcfg['type']) {
1831
		case 'ldap':
1832
			if (ldap_backed($username, $password, $authcfg)) {
1833
				$authenticated = true;
1834
			}
1835
			break;
1836
		case 'radius':
1837
			if (radius_backed($username, $password, $authcfg, $attributes)) {
1838
				$authenticated = true;
1839
			}
1840
			break;
1841
		default:
1842
			/* lookup user object by name */
1843
			if (local_backed($username, $password)) {
1844
				$authenticated = true;
1845
			}
1846
			break;
1847
		}
1848

    
1849
	return $authenticated;
1850
}
1851

    
1852
function session_auth() {
1853
	global $config, $_SESSION, $page;
1854

    
1855
	// Handle HTTPS httponly and secure flags
1856
	$currentCookieParams = session_get_cookie_params();
1857
	session_set_cookie_params(
1858
		$currentCookieParams["lifetime"],
1859
		$currentCookieParams["path"],
1860
		NULL,
1861
		($config['system']['webgui']['protocol'] == "https"),
1862
		true
1863
	);
1864

    
1865
	phpsession_begin();
1866

    
1867
	// Detect protocol change
1868
	if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) {
1869
		phpsession_end();
1870
		return false;
1871
	}
1872

    
1873
	/* Validate incoming login request */
1874
	$attributes = array();
1875
	if (isset($_POST['login']) && !empty($_POST['usernamefld']) && !empty($_POST['passwordfld'])) {
1876
		$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
1877
		$remoteauth = authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg, $attributes);
1878
		if ($remoteauth || authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) {
1879
			// Generate a new id to avoid session fixation
1880
			session_regenerate_id();
1881
			$_SESSION['Logged_In'] = "True";
1882
			$_SESSION['remoteauth'] = $remoteauth;
1883
			$_SESSION['Username'] = $_POST['usernamefld'];
1884
			$_SESSION['user_radius_attributes'] = $attributes;
1885
			$_SESSION['last_access'] = time();
1886
			$_SESSION['protocol'] = $config['system']['webgui']['protocol'];
1887
			phpsession_end(true);
1888
			if (!isset($config['system']['webgui']['quietlogin'])) {
1889
				log_auth(sprintf(gettext("Successful login for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], $_SERVER['REMOTE_ADDR']));
1890
			}
1891
			if (isset($_POST['postafterlogin'])) {
1892
				return true;
1893
			} else {
1894
				if (empty($page)) {
1895
					$page = "/";
1896
				}
1897
				header("Location: {$page}");
1898
			}
1899
			exit;
1900
		} else {
1901
			/* give the user an error message */
1902
			$_SESSION['Login_Error'] = gettext("Username or Password incorrect");
1903
			log_auth("webConfigurator authentication error for '{$_POST['usernamefld']}' from {$_SERVER['REMOTE_ADDR']}");
1904
			if (isAjax()) {
1905
				echo "showajaxmessage('{$_SESSION['Login_Error']}');";
1906
				return;
1907
			}
1908
		}
1909
	}
1910

    
1911
	/* Show login page if they aren't logged in */
1912
	if (empty($_SESSION['Logged_In'])) {
1913
		phpsession_end(true);
1914
		return false;
1915
	}
1916

    
1917
	/* If session timeout isn't set, we don't mark sessions stale */
1918
	if (!isset($config['system']['webgui']['session_timeout'])) {
1919
		/* Default to 4 hour timeout if one is not set */
1920
		if ($_SESSION['last_access'] < (time() - 14400)) {
1921
			$_POST['logout'] = true;
1922
			$_SESSION['Logout'] = true;
1923
		} else {
1924
			$_SESSION['last_access'] = time();
1925
		}
1926
	} else if (intval($config['system']['webgui']['session_timeout']) == 0) {
1927
		/* only update if it wasn't ajax */
1928
		if (!isAjax()) {
1929
			$_SESSION['last_access'] = time();
1930
		}
1931
	} else {
1932
		/* Check for stale session */
1933
		if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
1934
			$_POST['logout'] = true;
1935
			$_SESSION['Logout'] = true;
1936
		} else {
1937
			/* only update if it wasn't ajax */
1938
			if (!isAjax()) {
1939
				$_SESSION['last_access'] = time();
1940
			}
1941
		}
1942
	}
1943

    
1944
	/* user hit the logout button */
1945
	if (isset($_POST['logout'])) {
1946

    
1947
		if ($_SESSION['Logout']) {
1948
			log_error(sprintf(gettext("Session timed out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR']));
1949
		} else {
1950
			log_error(sprintf(gettext("User logged out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR']));
1951
		}
1952

    
1953
		/* wipe out $_SESSION */
1954
		$_SESSION = array();
1955

    
1956
		if (isset($_COOKIE[session_name()])) {
1957
			setcookie(session_name(), '', time()-42000, '/');
1958
		}
1959

    
1960
		/* and destroy it */
1961
		phpsession_destroy();
1962

    
1963
		$scriptName = explode("/", $_SERVER["SCRIPT_FILENAME"]);
1964
		$scriptElms = count($scriptName);
1965
		$scriptName = $scriptName[$scriptElms-1];
1966

    
1967
		if (isAjax()) {
1968
			return false;
1969
		}
1970

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

    
1974
		return false;
1975
	}
1976

    
1977
	/*
1978
	 * this is for debugging purpose if you do not want to use Ajax
1979
	 * to submit a HTML form. It basically disables the observation
1980
	 * of the submit event and hence does not trigger Ajax.
1981
	 */
1982
	if ($_REQUEST['disable_ajax']) {
1983
		$_SESSION['NO_AJAX'] = "True";
1984
	}
1985

    
1986
	/*
1987
	 * Same to re-enable Ajax.
1988
	 */
1989
	if ($_REQUEST['enable_ajax']) {
1990
		unset($_SESSION['NO_AJAX']);
1991
	}
1992
	phpsession_end(true);
1993
	return true;
1994
}
1995

    
1996
?>
(1-1/55)