Project

General

Profile

Download (56.9 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
				log_error("Removing user: {$user['name']}");
451
				unset($config['system']['user'][$i]);
452
				break;
453
			}
454
		}
455
	}
456

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

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

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

    
479
	foreach ($u2add as $user) {
480
		log_error("Adding user: {$user['name']}");
481
		$config['system']['user'][] = $user;
482
	}
483

    
484
	foreach ($g2add as $group) {
485
		log_error("Adding group: {$group['name']}");
486
		$config['system']['group'][] = $group;
487
	}
488

    
489
	/* Sort it alphabetically */
490
	usort($config['system']['user'], function($a, $b) {
491
		return strcmp($a['name'], $b['name']);
492
	});
493
	usort($config['system']['group'], function($a, $b) {
494
		return strcmp($a['name'], $b['name']);
495
	});
496

    
497
	write_config("Sync'd users and groups via XMLRPC");
498

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

    
503
	foreach ($u2add as $user) {
504
		local_user_set($user);
505
	}
506

    
507
	foreach ($g2add as $group) {
508
		local_group_set($group);
509
	}
510
}
511

    
512
function local_reset_accounts() {
513
	global $debug, $config;
514

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

    
545
	/* remove local groups to avoid gid conflicts */
546
	$gids = array();
547
	$fd = popen("/usr/sbin/pw groupshow -a", "r");
548
	if ($fd) {
549
		while (!feof($fd)) {
550
			$line = explode(":", fgets($fd));
551
			if (!strncmp($line[0], "_", 1)) {
552
				continue;
553
			}
554
			if ($line[2] < 2000) {
555
				continue;
556
			}
557
			if ($line[2] > 65000) {
558
				continue;
559
			}
560
			$cmd = "/usr/sbin/pw groupdel -g " . escapeshellarg($line[2]);
561
			if ($debug) {
562
				log_error(sprintf(gettext("Running: %s"), $cmd));
563
			}
564
			mwexec($cmd);
565
		}
566
		pclose($fd);
567
	}
568

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

    
573
	/* sync all local users */
574
	if (is_array($config['system']['user'])) {
575
		foreach ($config['system']['user'] as $user) {
576
			local_user_set($user);
577
		}
578
	}
579

    
580
	/* sync all local groups */
581
	if (is_array($config['system']['group'])) {
582
		foreach ($config['system']['group'] as $group) {
583
			local_group_set($group);
584
		}
585
	}
586
}
587

    
588
function local_user_set(& $user) {
589
	global $g, $debug;
590

    
591
	if (empty($user['password']) && empty($user['bcrypt-hash'])) {
592
		log_error("There is something wrong in the config because user {$user['name']} password is missing!");
593
		return;
594
	}
595

    
596

    
597
	$home_base = "/home/";
598
	$user_uid = $user['uid'];
599
	$user_name = $user['name'];
600
	$user_home = "{$home_base}{$user_name}";
601
	$user_shell = "/etc/rc.initial";
602
	$user_group = "nobody";
603

    
604
	// Ensure $home_base exists and is writable
605
	if (!is_dir($home_base)) {
606
		mkdir($home_base, 0755);
607
	}
608

    
609
	$lock_account = false;
610
	/* configure shell type */
611
	/* Cases here should be ordered by most privileged to least privileged. */
612
	if (userHasPrivilege($user, "user-shell-access") || userHasPrivilege($user, "page-all")) {
613
		$user_shell = "/bin/tcsh";
614
	} elseif (userHasPrivilege($user, "user-copy-files-chroot")) {
615
		$user_shell = "/usr/local/sbin/scponlyc";
616
	} elseif (userHasPrivilege($user, "user-copy-files")) {
617
		$user_shell = "/usr/local/bin/scponly";
618
	} elseif (userHasPrivilege($user, "user-ssh-tunnel")) {
619
		$user_shell = "/usr/local/sbin/ssh_tunnel_shell";
620
	} elseif (userHasPrivilege($user, "user-ipsec-xauth-dialin")) {
621
		$user_shell = "/sbin/nologin";
622
	} else {
623
		$user_shell = "/sbin/nologin";
624
		$lock_account = true;
625
	}
626

    
627
	/* Lock out disabled or expired users, unless it's root/admin. */
628
	if ((is_account_disabled($user_name) || is_account_expired($user_name)) && ($user_uid != 0)) {
629
		$user_shell = "/sbin/nologin";
630
		$lock_account = true;
631
	}
632

    
633
	/* root user special handling */
634
	if ($user_uid == 0) {
635
		$cmd = "/usr/sbin/pw usermod -q -n root -s /bin/sh -H 0";
636
		if ($debug) {
637
			log_error(sprintf(gettext("Running: %s"), $cmd));
638
		}
639
		$fd = popen($cmd, "w");
640
		if (empty($user['bcrypt-hash'])) {
641
			fwrite($fd, $user['password']);
642
		} else {
643
			fwrite($fd, $user['bcrypt-hash']);
644
		}
645
		pclose($fd);
646
		$user_group = "wheel";
647
		$user_home = "/root";
648
		$user_shell = "/etc/rc.initial";
649
	}
650

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

    
657
	$skel_dir = '/etc/skel';
658

    
659
	/* determine add or mod */
660
	if (($userattrs[0] != $user['name']) || (!strncmp($pwread, "pw:", 3))) {
661
		$user_op = "useradd -m -k " . escapeshellarg($skel_dir) . " -o";
662
	} else {
663
		$user_op = "usermod";
664
	}
665

    
666
	$comment = str_replace(array(":", "!", "@"), " ", $user['descr']);
667
	/* add or mod pw db */
668
	$cmd = "/usr/sbin/pw {$user_op} -q " .
669
			" -u " . escapeshellarg($user_uid) .
670
			" -n " . escapeshellarg($user_name) .
671
			" -g " . escapeshellarg($user_group) .
672
			" -s " . escapeshellarg($user_shell) .
673
			" -d " . escapeshellarg($user_home) .
674
			" -c " . escapeshellarg($comment) .
675
			" -H 0 2>&1";
676

    
677
	if ($debug) {
678
		log_error(sprintf(gettext("Running: %s"), $cmd));
679
	}
680
	$fd = popen($cmd, "w");
681
	if (empty($user['bcrypt-hash'])) {
682
		fwrite($fd, $user['password']);
683
	} else {
684
		fwrite($fd, $user['bcrypt-hash']);
685
	}
686
	pclose($fd);
687

    
688
	/* create user directory if required */
689
	if (!is_dir($user_home)) {
690
		mkdir($user_home, 0700);
691
	}
692
	@chown($user_home, $user_name);
693
	@chgrp($user_home, $user_group);
694

    
695
	/* Make sure all users have last version of config files */
696
	foreach (glob("{$skel_dir}/dot.*") as $dot_file) {
697
		$target = $user_home . '/' . substr(basename($dot_file), 3);
698
		@copy($dot_file, $target);
699
		@chown($target, $user_name);
700
		@chgrp($target, $user_group);
701
	}
702

    
703
	/* write out ssh authorized key file */
704
	if ($user['authorizedkeys']) {
705
		if (!is_dir("{$user_home}/.ssh")) {
706
			@mkdir("{$user_home}/.ssh", 0700);
707
			@chown("{$user_home}/.ssh", $user_name);
708
		}
709
		$keys = base64_decode($user['authorizedkeys']);
710
		@file_put_contents("{$user_home}/.ssh/authorized_keys", $keys);
711
		@chown("{$user_home}/.ssh/authorized_keys", $user_name);
712
	} else {
713
		unlink_if_exists("{$user_home}/.ssh/authorized_keys");
714
	}
715

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

    
719
}
720

    
721
function local_user_del($user) {
722
	global $debug;
723

    
724
	/* remove all memberships */
725
	local_user_set_groups($user);
726

    
727
	/* Don't remove /root */
728
	if ($user['uid'] != 0) {
729
		$rmhome = "-r";
730
	}
731

    
732
	/* read from pw db */
733
	$fd = popen("/usr/sbin/pw usershow -n {$user['name']} 2>&1", "r");
734
	$pwread = fgets($fd);
735
	pclose($fd);
736
	$userattrs = explode(":", trim($pwread));
737

    
738
	if ($userattrs[0] != $user['name']) {
739
		log_error("Tried to remove user {$user['name']} but got user {$userattrs[0]} instead. Bailing.");
740
		return;
741
	}
742

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

    
746
	if ($debug) {
747
		log_error(sprintf(gettext("Running: %s"), $cmd));
748
	}
749
	mwexec($cmd);
750

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

    
755
function local_user_set_password(&$user, $password) {
756

    
757
	unset($user['password']);
758
	unset($user['md5-hash']);
759
	$user['bcrypt-hash'] = password_hash($password, PASSWORD_BCRYPT);
760

    
761
	/* Maintain compatibility with FreeBSD - change $2y$ prefix to $2b$
762
	 * https://reviews.freebsd.org/D2742
763
	 * XXX: Can be removed as soon as r284483 is MFC'd.
764
	 */
765
	if ($user['bcrypt-hash'][2] == "y") {
766
		$user['bcrypt-hash'][2] = "b";
767
	}
768

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

    
777
}
778

    
779
function local_user_get_groups($user, $all = false) {
780
	global $debug, $config;
781

    
782
	$groups = array();
783
	if (!is_array($config['system']['group'])) {
784
		return $groups;
785
	}
786

    
787
	foreach ($config['system']['group'] as $group) {
788
		if ($all || (!$all && ($group['name'] != "all"))) {
789
			if (is_array($group['member'])) {
790
				if (in_array($user['uid'], $group['member'])) {
791
					$groups[] = $group['name'];
792
				}
793
			}
794
		}
795
	}
796

    
797
	if ($all) {
798
		$groups[] = "all";
799
	}
800

    
801
	sort($groups);
802

    
803
	return $groups;
804

    
805
}
806

    
807
function local_user_set_groups($user, $new_groups = NULL) {
808
	global $debug, $config, $groupindex, $userindex;
809

    
810
	if (!is_array($config['system']['group'])) {
811
		return;
812
	}
813

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

    
817
	if (!is_array($new_groups)) {
818
		$new_groups = array();
819
	}
820

    
821
	if (!is_array($cur_groups)) {
822
		$cur_groups = array();
823
	}
824

    
825
	/* determine which memberships to add */
826
	foreach ($new_groups as $groupname) {
827
		if ($groupname == '' || in_array($groupname, $cur_groups)) {
828
			continue;
829
		}
830
		$group = & $config['system']['group'][$groupindex[$groupname]];
831
		$group['member'][] = $user['uid'];
832
		$mod_groups[] = $group;
833

    
834
		/*
835
		 * If it's a new user, make sure it is added before try to
836
		 * add it as a member of a group
837
		 */
838
		if (!isset($userindex[$user['uid']])) {
839
			local_user_set($user);
840
		}
841
	}
842
	unset($group);
843

    
844
	/* determine which memberships to remove */
845
	foreach ($cur_groups as $groupname) {
846
		if (in_array($groupname, $new_groups)) {
847
			continue;
848
		}
849
		if (!isset($config['system']['group'][$groupindex[$groupname]])) {
850
			continue;
851
		}
852
		$group = & $config['system']['group'][$groupindex[$groupname]];
853
		if (is_array($group['member'])) {
854
			$index = array_search($user['uid'], $group['member']);
855
			array_splice($group['member'], $index, 1);
856
			$mod_groups[] = $group;
857
		}
858
	}
859
	unset($group);
860

    
861
	/* sync all modified groups */
862
	foreach ($mod_groups as $group) {
863
		local_group_set($group);
864
	}
865
}
866

    
867
function local_group_del_user($user) {
868
	global $config;
869

    
870
	if (!is_array($config['system']['group'])) {
871
		return;
872
	}
873

    
874
	foreach ($config['system']['group'] as $group) {
875
		if (is_array($group['member'])) {
876
			foreach ($group['member'] as $idx => $uid) {
877
				if ($user['uid'] == $uid) {
878
					unset($config['system']['group']['member'][$idx]);
879
				}
880
			}
881
		}
882
	}
883
}
884

    
885
function local_group_set($group, $reset = false) {
886
	global $debug;
887

    
888
	$group_name = $group['name'];
889
	$group_gid = $group['gid'];
890
	$group_members = '';
891

    
892
	if (!$reset && !empty($group['member']) && count($group['member']) > 0) {
893
		$group_members = implode(",", $group['member']);
894
	}
895

    
896
	if (empty($group_name)) {
897
		return;
898
	}
899

    
900
	// If the group is now remote, make sure there is no local group with the same name
901
	if ($group['scope'] == "remote") {
902
		local_group_del($group);
903
		return;
904
	}
905

    
906
	/* determine add or mod */
907
	if (mwexec("/usr/sbin/pw groupshow -g " . escapeshellarg($group_gid) . " 2>&1", true) == 0) {
908
		$group_op = "groupmod -l";
909
	} else {
910
		$group_op = "groupadd -n";
911
	}
912

    
913
	/* add or mod group db */
914
	$cmd = "/usr/sbin/pw {$group_op} " .
915
		escapeshellarg($group_name) .
916
		" -g " . escapeshellarg($group_gid) .
917
		" -M " . escapeshellarg($group_members) . " 2>&1";
918

    
919
	if ($debug) {
920
		log_error(sprintf(gettext("Running: %s"), $cmd));
921
	}
922

    
923
	mwexec($cmd);
924
}
925

    
926
function local_group_del($group) {
927
	global $debug;
928

    
929
	/* delete from group db */
930
	$cmd = "/usr/sbin/pw groupdel " . escapeshellarg($group['name']);
931

    
932
	if ($debug) {
933
		log_error(sprintf(gettext("Running: %s"), $cmd));
934
	}
935
	mwexec($cmd);
936
}
937

    
938
function ldap_test_connection($authcfg) {
939
	if ($authcfg) {
940
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
941
			$ldapproto = "ldaps";
942
		} else {
943
			$ldapproto = "ldap";
944
		}
945
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
946
		$ldapport = $authcfg['ldap_port'];
947
		if (!empty($ldapport)) {
948
			$ldapserver .= ":{$ldapport}";
949
		}
950
	} else {
951
		return false;
952
	}
953

    
954
	/* first check if there is even an LDAP server populated */
955
	if (!$ldapserver) {
956
		return false;
957
	}
958

    
959
	/* Setup CA environment if needed. */
960
	ldap_setup_caenv($authcfg);
961

    
962
	/* connect and see if server is up */
963
	$error = false;
964
	if (!($ldap = ldap_connect($ldapserver))) {
965
		$error = true;
966
	}
967

    
968
	if ($error == true) {
969
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $authcfg['name']));
970
		return false;
971
	}
972

    
973
	return true;
974
}
975

    
976
function ldap_setup_caenv($authcfg) {
977
	global $g;
978
	require_once("certs.inc");
979

    
980
	unset($caref);
981
	if (empty($authcfg['ldap_caref']) || strstr($authcfg['ldap_urltype'], "Standard")) {
982
		putenv('LDAPTLS_REQCERT=never');
983
		return;
984
	} elseif ($authcfg['ldap_caref'] == "global") {
985
		putenv('LDAPTLS_REQCERT=hard');
986
		putenv("LDAPTLS_CACERTDIR=/etc/ssl/");
987
		putenv("LDAPTLS_CACERT=/etc/ssl/cert.pem");
988
	} else {
989
		$caref = lookup_ca($authcfg['ldap_caref']);
990
		$param = array('caref' => $authcfg['ldap_caref']);
991
		$cachain = ca_chain($param);
992
		if (!$caref) {
993
			log_error(sprintf(gettext("LDAP: Could not lookup CA by reference for host %s."), $authcfg['ldap_caref']));
994
			/* XXX: Prevent for credential leaking since we cannot setup the CA env. Better way? */
995
			putenv('LDAPTLS_REQCERT=hard');
996
			return;
997
		}
998
		if (!is_dir("{$g['varrun_path']}/certs")) {
999
			@mkdir("{$g['varrun_path']}/certs");
1000
		}
1001
		if (file_exists("{$g['varrun_path']}/certs/{$caref['refid']}.ca")) {
1002
			@unlink("{$g['varrun_path']}/certs/{$caref['refid']}.ca");
1003
		}
1004
		file_put_contents("{$g['varrun_path']}/certs/{$caref['refid']}.ca", $cachain);
1005
		@chmod("{$g['varrun_path']}/certs/{$caref['refid']}.ca", 0600);
1006
		putenv('LDAPTLS_REQCERT=hard');
1007
		/* XXX: Probably even the hashed link should be created for this? */
1008
		putenv("LDAPTLS_CACERTDIR={$g['varrun_path']}/certs");
1009
		putenv("LDAPTLS_CACERT={$g['varrun_path']}/certs/{$caref['refid']}.ca");
1010
	}
1011
}
1012

    
1013
function ldap_test_bind($authcfg) {
1014
	global $debug, $config, $g;
1015

    
1016
	if ($authcfg) {
1017
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1018
			$ldapproto = "ldaps";
1019
		} else {
1020
			$ldapproto = "ldap";
1021
		}
1022
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1023
		$ldapport = $authcfg['ldap_port'];
1024
		if (!empty($ldapport)) {
1025
			$ldapserver .= ":{$ldapport}";
1026
		}
1027
		$ldapbasedn = $authcfg['ldap_basedn'];
1028
		$ldapbindun = $authcfg['ldap_binddn'];
1029
		$ldapbindpw = $authcfg['ldap_bindpw'];
1030
		$ldapver = $authcfg['ldap_protver'];
1031
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1032
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1033
			$ldapanon = true;
1034
		} else {
1035
			$ldapanon = false;
1036
		}
1037
	} else {
1038
		return false;
1039
	}
1040

    
1041
	/* first check if there is even an LDAP server populated */
1042
	if (!$ldapserver) {
1043
		return false;
1044
	}
1045

    
1046
	/* Setup CA environment if needed. */
1047
	ldap_setup_caenv($authcfg);
1048

    
1049
	/* connect and see if server is up */
1050
	$error = false;
1051
	if (!($ldap = ldap_connect($ldapserver))) {
1052
		$error = true;
1053
	}
1054

    
1055
	if ($error == true) {
1056
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1057
		return false;
1058
	}
1059

    
1060
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1061
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1062
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1063
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1064
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1065

    
1066
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1067
		if (!(@ldap_start_tls($ldap))) {
1068
			log_error(sprintf(gettext("ERROR! ldap_test_bind() could not STARTTLS to server %s."), $ldapname));
1069
			@ldap_close($ldap);
1070
			return false;
1071
		}
1072
	}
1073

    
1074
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1075
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1076
	if ($ldapanon == true) {
1077
		if (!($res = @ldap_bind($ldap))) {
1078
			@ldap_close($ldap);
1079
			return false;
1080
		}
1081
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1082
		@ldap_close($ldap);
1083
		return false;
1084
	}
1085

    
1086
	@ldap_unbind($ldap);
1087

    
1088
	return true;
1089
}
1090

    
1091
function ldap_get_user_ous($show_complete_ou=true, $authcfg) {
1092
	global $debug, $config, $g;
1093

    
1094
	if (!function_exists("ldap_connect")) {
1095
		return;
1096
	}
1097

    
1098
	$ous = array();
1099

    
1100
	if ($authcfg) {
1101
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1102
			$ldapproto = "ldaps";
1103
		} else {
1104
			$ldapproto = "ldap";
1105
		}
1106
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1107
		$ldapport = $authcfg['ldap_port'];
1108
		if (!empty($ldapport)) {
1109
			$ldapserver .= ":{$ldapport}";
1110
		}
1111
		$ldapbasedn = $authcfg['ldap_basedn'];
1112
		$ldapbindun = $authcfg['ldap_binddn'];
1113
		$ldapbindpw = $authcfg['ldap_bindpw'];
1114
		$ldapver = $authcfg['ldap_protver'];
1115
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1116
			$ldapanon = true;
1117
		} else {
1118
			$ldapanon = false;
1119
		}
1120
		$ldapname = $authcfg['name'];
1121
		$ldapfallback = false;
1122
		$ldapscope = $authcfg['ldap_scope'];
1123
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1124
	} else {
1125
		return false;
1126
	}
1127

    
1128
	/* first check if there is even an LDAP server populated */
1129
	if (!$ldapserver) {
1130
		log_error(gettext("ERROR!  ldap_get_user_ous() backed selected with no LDAP authentication server defined."));
1131
		return $ous;
1132
	}
1133

    
1134
	/* Setup CA environment if needed. */
1135
	ldap_setup_caenv($authcfg);
1136

    
1137
	/* connect and see if server is up */
1138
	$error = false;
1139
	if (!($ldap = ldap_connect($ldapserver))) {
1140
		$error = true;
1141
	}
1142

    
1143
	if ($error == true) {
1144
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1145
		return $ous;
1146
	}
1147

    
1148
	$ldapfilter = "(|(ou=*)(cn=Users))";
1149

    
1150
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1151
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1152
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1153
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1154
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1155

    
1156
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1157
		if (!(@ldap_start_tls($ldap))) {
1158
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not STARTTLS to server %s."), $ldapname));
1159
			@ldap_close($ldap);
1160
			return false;
1161
		}
1162
	}
1163

    
1164
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1165
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1166
	if ($ldapanon == true) {
1167
		if (!($res = @ldap_bind($ldap))) {
1168
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind anonymously to server %s."), $ldapname));
1169
			@ldap_close($ldap);
1170
			return $ous;
1171
		}
1172
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1173
		log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind to server %s."), $ldapname));
1174
		@ldap_close($ldap);
1175
		return $ous;
1176
	}
1177

    
1178
	if ($ldapscope == "one") {
1179
		$ldapfunc = "ldap_list";
1180
	} else {
1181
		$ldapfunc = "ldap_search";
1182
	}
1183

    
1184
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
1185
	$info = @ldap_get_entries($ldap, $search);
1186

    
1187
	if (is_array($info)) {
1188
		foreach ($info as $inf) {
1189
			if (!$show_complete_ou) {
1190
				$inf_split = explode(",", $inf['dn']);
1191
				$ou = $inf_split[0];
1192
				$ou = str_replace("OU=", "", $ou);
1193
				$ou = str_replace("CN=", "", $ou);
1194
			} else {
1195
				if ($inf['dn']) {
1196
					$ou = $inf['dn'];
1197
				}
1198
			}
1199
			if ($ou) {
1200
				$ous[] = $ou;
1201
			}
1202
		}
1203
	}
1204

    
1205
	@ldap_unbind($ldap);
1206

    
1207
	return $ous;
1208
}
1209

    
1210
function ldap_get_groups($username, $authcfg) {
1211
	global $debug, $config;
1212

    
1213
	if (!function_exists("ldap_connect")) {
1214
		return;
1215
	}
1216

    
1217
	if (!$username) {
1218
		return false;
1219
	}
1220

    
1221
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1222
		$username_split = explode("@", $username);
1223
		$username = $username_split[0];
1224
	}
1225

    
1226
	if (stristr($username, "\\")) {
1227
		$username_split = explode("\\", $username);
1228
		$username = $username_split[0];
1229
	}
1230

    
1231
	//log_error("Getting LDAP groups for {$username}.");
1232
	if ($authcfg) {
1233
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1234
			$ldapproto = "ldaps";
1235
		} else {
1236
			$ldapproto = "ldap";
1237
		}
1238
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1239
		$ldapport = $authcfg['ldap_port'];
1240
		if (!empty($ldapport)) {
1241
			$ldapserver .= ":{$ldapport}";
1242
		}
1243
		$ldapbasedn = $authcfg['ldap_basedn'];
1244
		$ldapbindun = $authcfg['ldap_binddn'];
1245
		$ldapbindpw = $authcfg['ldap_bindpw'];
1246
		$ldapauthcont = $authcfg['ldap_authcn'];
1247
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1248
		$ldapgroupattribute = strtolower($authcfg['ldap_attr_member']);
1249
		if (isset($authcfg['ldap_rfc2307'])) {
1250
			$ldapfilter         = "(&(objectClass={$authcfg['ldap_attr_groupobj']})({$ldapgroupattribute}={$username}))";
1251
		} else {
1252
			$ldapfilter         = "({$ldapnameattribute}={$username})";
1253
		}
1254
		$ldaptype = "";
1255
		$ldapver = $authcfg['ldap_protver'];
1256
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1257
			$ldapanon = true;
1258
		} else {
1259
			$ldapanon = false;
1260
		}
1261
		$ldapname = $authcfg['name'];
1262
		$ldapfallback = false;
1263
		$ldapscope = $authcfg['ldap_scope'];
1264
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1265
	} else {
1266
		return false;
1267
	}
1268

    
1269
	if (isset($authcfg['ldap_rfc2307'])) {
1270
		$ldapdn = $ldapbasedn;
1271
	} else {
1272
		$ldapdn = $_SESSION['ldapdn'];
1273
	}
1274

    
1275
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
1276
	$ldapgroupattribute = strtolower($ldapgroupattribute);
1277
	$memberof = array();
1278

    
1279
	/* Setup CA environment if needed. */
1280
	ldap_setup_caenv($authcfg);
1281

    
1282
	/* connect and see if server is up */
1283
	$error = false;
1284
	if (!($ldap = ldap_connect($ldapserver))) {
1285
		$error = true;
1286
	}
1287

    
1288
	if ($error == true) {
1289
		log_error(sprintf(gettext("ERROR! ldap_get_groups() Could not connect to server %s."), $ldapname));
1290
		return $memberof;
1291
	}
1292

    
1293
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1294
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1295
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1296
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1297
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1298

    
1299
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1300
		if (!(@ldap_start_tls($ldap))) {
1301
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not STARTTLS to server %s."), $ldapname));
1302
			@ldap_close($ldap);
1303
			return false;
1304
		}
1305
	}
1306

    
1307
	/* bind as user that has rights to read group attributes */
1308
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1309
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1310
	if ($ldapanon == true) {
1311
		if (!($res = @ldap_bind($ldap))) {
1312
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind anonymously to server %s."), $ldapname));
1313
			@ldap_close($ldap);
1314
			return false;
1315
		}
1316
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1317
		log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind to server %s."), $ldapname));
1318
		@ldap_close($ldap);
1319
		return $memberof;
1320
	}
1321

    
1322
	/* get groups from DN found */
1323
	/* use ldap_read instead of search so we don't have to do a bunch of extra work */
1324
	/* since we know the DN is in $_SESSION['ldapdn'] */
1325
	//$search    = ldap_read($ldap, $ldapdn, "(objectclass=*)", array($ldapgroupattribute));
1326
	if ($ldapscope == "one") {
1327
		$ldapfunc = "ldap_list";
1328
	} else {
1329
		$ldapfunc = "ldap_search";
1330
	}
1331

    
1332
	$search = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
1333
	$info = @ldap_get_entries($ldap, $search);
1334

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

    
1337
	if (is_array($gresults)) {
1338
		/* Iterate through the groups and throw them into an array */
1339
		foreach ($gresults as $grp) {
1340
			if (((isset($authcfg['ldap_rfc2307'])) && (stristr($grp["dn"], "CN=") !== false)) ||
1341
			    ((!isset($authcfg['ldap_rfc2307'])) && (stristr($grp, "CN=") !== false))) {
1342
				$grpsplit = isset($authcfg['ldap_rfc2307']) ? explode(",", $grp["dn"]) : explode(",", $grp);
1343
				$memberof[] = preg_replace("/CN=/i", "", $grpsplit[0]);
1344
			}
1345
		}
1346
	}
1347

    
1348
	/* Time to close LDAP connection */
1349
	@ldap_unbind($ldap);
1350

    
1351
	$groups = print_r($memberof, true);
1352

    
1353
	//log_error("Returning groups ".$groups." for user $username");
1354

    
1355
	return $memberof;
1356
}
1357

    
1358
function ldap_format_host($host) {
1359
	return is_ipaddrv6($host) ? "[$host]" : $host ;
1360
}
1361

    
1362
function ldap_backed($username, $passwd, $authcfg) {
1363
	global $debug, $config;
1364

    
1365
	if (!$username) {
1366
		return;
1367
	}
1368

    
1369
	if (!function_exists("ldap_connect")) {
1370
		return;
1371
	}
1372

    
1373
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1374
		$username_split = explode("@", $username);
1375
		$username = $username_split[0];
1376
	}
1377
	if (stristr($username, "\\")) {
1378
		$username_split = explode("\\", $username);
1379
		$username = $username_split[0];
1380
	}
1381

    
1382
	$username = ldap_escape($username, null, LDAP_ESCAPE_FILTER);
1383

    
1384
	if ($authcfg) {
1385
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1386
			$ldapproto = "ldaps";
1387
		} else {
1388
			$ldapproto = "ldap";
1389
		}
1390
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1391
		$ldapport = $authcfg['ldap_port'];
1392
		if (!empty($ldapport)) {
1393
			$ldapserver .= ":{$ldapport}";
1394
		}
1395
		$ldapbasedn = $authcfg['ldap_basedn'];
1396
		$ldapbindun = $authcfg['ldap_binddn'];
1397
		$ldapbindpw = $authcfg['ldap_bindpw'];
1398
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1399
			$ldapanon = true;
1400
		} else {
1401
			$ldapanon = false;
1402
		}
1403
		$ldapauthcont = $authcfg['ldap_authcn'];
1404
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1405
		$ldapextendedqueryenabled = $authcfg['ldap_extended_enabled'];
1406
		$ldapextendedquery = $authcfg['ldap_extended_query'];
1407
		$ldapfilter = "";
1408
		if (!$ldapextendedqueryenabled) {
1409
			$ldapfilter = "({$ldapnameattribute}={$username})";
1410
		} else {
1411
			$ldapfilter = "(&({$ldapnameattribute}={$username})({$ldapextendedquery}))";
1412
		}
1413
		$ldaptype = "";
1414
		$ldapver = $authcfg['ldap_protver'];
1415
		$ldapname = $authcfg['name'];
1416
		$ldapscope = $authcfg['ldap_scope'];
1417
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1418
	} else {
1419
		return false;
1420
	}
1421

    
1422
	/* first check if there is even an LDAP server populated */
1423
	if (!$ldapserver) {
1424
		if ($ldapfallback) {
1425
			log_error(gettext("ERROR! ldap_backed() called with no LDAP authentication server defined.  Defaulting to local user database. Visit System -> User Manager."));
1426
			return local_backed($username, $passwd);
1427
		} else {
1428
			log_error(gettext("ERROR! ldap_backed() called with no LDAP authentication server defined."));
1429
		}
1430

    
1431
		return false;
1432
	}
1433

    
1434
	/* Setup CA environment if needed. */
1435
	ldap_setup_caenv($authcfg);
1436

    
1437
	/* Make sure we can connect to LDAP */
1438
	$error = false;
1439
	if (!($ldap = ldap_connect($ldapserver))) {
1440
		$error = true;
1441
	}
1442

    
1443
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1444
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1445
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1446
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1447
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1448

    
1449
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1450
		if (!(@ldap_start_tls($ldap))) {
1451
			log_error(sprintf(gettext("ERROR! ldap_backed() could not STARTTLS to server %s."), $ldapname));
1452
			@ldap_close($ldap);
1453
			return false;
1454
		}
1455
	}
1456

    
1457
	if ($error == true) {
1458
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1459
		return false;
1460
	}
1461

    
1462
	/* ok, its up.  now, lets bind as the bind user so we can search it */
1463
	$error = false;
1464
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1465
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1466
	if ($ldapanon == true) {
1467
		if (!($res = @ldap_bind($ldap))) {
1468
			$error = true;
1469
		}
1470
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1471
		$error = true;
1472
	}
1473

    
1474
	if ($error == true) {
1475
		@ldap_close($ldap);
1476
		log_error(sprintf(gettext("ERROR! Could not bind to server %s."), $ldapname));
1477
		return false;
1478
	}
1479

    
1480
	/* Get LDAP Authcontainers and split em up. */
1481
	$ldac_splits = explode(";", $ldapauthcont);
1482

    
1483
	/* setup the usercount so we think we haven't found anyone yet */
1484
	$usercount = 0;
1485

    
1486
	/*****************************************************************/
1487
	/*  We first find the user based on username and filter          */
1488
	/*  then, once we find the first occurrence of that person       */
1489
	/*  we set session variables to point to the OU and DN of the    */
1490
	/*  person.  To later be used by ldap_get_groups.                */
1491
	/*  that way we don't have to search twice.                      */
1492
	/*****************************************************************/
1493
	if ($debug) {
1494
		log_auth(sprintf(gettext("Now Searching for %s in directory."), $username));
1495
	}
1496
	/* Iterate through the user containers for search */
1497
	foreach ($ldac_splits as $i => $ldac_split) {
1498
		$ldac_split = isset($authcfg['ldap_utf8']) ? utf8_encode($ldac_split) : $ldac_split;
1499
		$ldapfilter = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapfilter) : $ldapfilter;
1500
		$ldapsearchbasedn = isset($authcfg['ldap_utf8']) ? utf8_encode("{$ldac_split},{$ldapbasedn}") : "{$ldac_split},{$ldapbasedn}";
1501
		/* Make sure we just use the first user we find */
1502
		if ($debug) {
1503
			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)));
1504
		}
1505
		if ($ldapscope == "one") {
1506
			$ldapfunc = "ldap_list";
1507
		} else {
1508
			$ldapfunc = "ldap_search";
1509
		}
1510
		/* Support legacy auth container specification. */
1511
		if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) {
1512
			$search = @$ldapfunc($ldap, $ldac_split, $ldapfilter);
1513
		} else {
1514
			$search = @$ldapfunc($ldap, $ldapsearchbasedn, $ldapfilter);
1515
		}
1516
		if (!$search) {
1517
			log_error(sprintf(gettext("Search resulted in error: %s"), ldap_error($ldap)));
1518
			continue;
1519
		}
1520
		$info = ldap_get_entries($ldap, $search);
1521
		$matches = $info['count'];
1522
		if ($matches == 1) {
1523
			$userdn = $_SESSION['ldapdn'] = $info[0]['dn'];
1524
			$_SESSION['ldapou'] = $ldac_split[$i];
1525
			$_SESSION['ldapon'] = "true";
1526
			$usercount = 1;
1527
			break;
1528
		}
1529
	}
1530

    
1531
	if ($usercount != 1) {
1532
		@ldap_unbind($ldap);
1533
		log_error(gettext("ERROR! Either LDAP search failed, or multiple users were found."));
1534
		return false;
1535
	}
1536

    
1537
	/* Now lets bind as the user we found */
1538
	$passwd = isset($authcfg['ldap_utf8']) ? utf8_encode($passwd) : $passwd;
1539
	if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
1540
		log_error(sprintf(gettext('ERROR! Could not login to server %1$s as user %2$s: %3$s'), $ldapname, $username, ldap_error($ldap)));
1541
		@ldap_unbind($ldap);
1542
		return false;
1543
	}
1544

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

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

    
1553
	return true;
1554
}
1555

    
1556
function radius_backed($username, $password, $authcfg, &$attributes = array()) {
1557
	global $debug, $config;
1558
	$ret = false;
1559

    
1560
	require_once("Auth/RADIUS.php");
1561
	require_once("Crypt/CHAP.php");
1562

    
1563
	if ($authcfg) {
1564
		$radiusservers = array();
1565
		$radiusservers[0]['ipaddr'] = $authcfg['host'];
1566
		$radiusservers[0]['port'] = $authcfg['radius_auth_port'];
1567
		$radiusservers[0]['sharedsecret'] = $authcfg['radius_secret'];
1568
		$radiusservers[0]['timeout'] = $authcfg['radius_timeout'];
1569
		if(isset($authcfg['radius_protocol'])) {
1570
			$radius_protocol = $authcfg['radius_protocol'];
1571
		} else {
1572
			$radius_protocol = 'PAP';
1573
		}
1574
	} else {
1575
		return false;
1576
	}
1577

    
1578
	// Create our instance
1579
	$classname = 'Auth_RADIUS_' . $radius_protocol;
1580
	$rauth = new $classname($username, $password);
1581

    
1582
	/* Add new servers to our instance */
1583
	foreach ($radiusservers as $radsrv) {
1584
		$timeout = (is_numeric($radsrv['timeout'])) ? $radsrv['timeout'] : 5;
1585
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret'], $timeout);
1586
	}
1587

    
1588
	// Construct data package
1589
	$rauth->username = $username;
1590
	switch ($radius_protocol) {
1591
		case 'CHAP_MD5':
1592
		case 'MSCHAPv1':
1593
			$classname = $radius_protocol == 'MSCHAPv1' ? 'Crypt_CHAP_MSv1' : 'Crypt_CHAP_MD5';
1594
			$crpt = new $classname;
1595
			$crpt->username = $username;
1596
			$crpt->password = $password;
1597
			$rauth->challenge = $crpt->challenge;
1598
			$rauth->chapid = $crpt->chapid;
1599
			$rauth->response = $crpt->challengeResponse();
1600
			$rauth->flags = 1;
1601
			break;
1602

    
1603
		case 'MSCHAPv2':
1604
			$crpt = new Crypt_CHAP_MSv2;
1605
			$crpt->username = $username;
1606
			$crpt->password = $password;
1607
			$rauth->challenge = $crpt->authChallenge;
1608
			$rauth->peerChallenge = $crpt->peerChallenge;
1609
			$rauth->chapid = $crpt->chapid;
1610
			$rauth->response = $crpt->challengeResponse();
1611
			break;
1612

    
1613
		default:
1614
			$rauth->password = $password;
1615
			break;
1616
	}
1617

    
1618
	if (PEAR::isError($rauth->start())) {
1619
		$retvalue['auth_val'] = 1;
1620
		$retvalue['error'] = $rauth->getError();
1621
		if ($debug) {
1622
			printf(gettext("RADIUS start: %s") . "<br />\n", $retvalue['error']);
1623
		}
1624
	}
1625

    
1626
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1627

    
1628
	/* Send request */
1629
	$result = $rauth->send();
1630
	if (PEAR::isError($result)) {
1631
		$retvalue['auth_val'] = 1;
1632
		$retvalue['error'] = $result->getMessage();
1633
		if ($debug) {
1634
			printf(gettext("RADIUS send failed: %s") . "<br />\n", $retvalue['error']);
1635
		}
1636
	} else if ($result === true) {
1637
		if ($rauth->getAttributes()) {
1638
			$attributes = $rauth->listAttributes();
1639
		}
1640
		$retvalue['auth_val'] = 2;
1641
		if ($debug) {
1642
			printf(gettext("RADIUS Auth succeeded")."<br />\n");
1643
		}
1644
		$ret = true;
1645
	} else {
1646
		$retvalue['auth_val'] = 3;
1647
		if ($debug) {
1648
			printf(gettext("RADIUS Auth rejected")."<br />\n");
1649
		}
1650
	}
1651

    
1652
	$rauth->close();
1653

    
1654
	return $ret;
1655
}
1656

    
1657
/*
1658
	$attributes must contain a "class" key containing the groups and local
1659
	groups must exist to match.
1660
*/
1661
function radius_get_groups($attributes) {
1662
	$groups = array();
1663
	if (!empty($attributes) && is_array($attributes) && (!empty($attributes['class']) || !empty($attributes['class_int']))) {
1664
		/* Some RADIUS servers return multiple class attributes, so check them all. */
1665
		$groups = array();
1666
		if (!empty($attributes['class']) && is_array($attributes['class'])) {
1667
			foreach ($attributes['class'] as $class) {
1668
				$groups = array_unique(array_merge($groups, explode(";", $class)));
1669
			}
1670
		}
1671

    
1672
		foreach ($groups as & $grp) {
1673
			$grp = trim($grp);
1674
			if (strtolower(substr($grp, 0, 3)) == "ou=") {
1675
				$grp = substr($grp, 3);
1676
			}
1677
		}
1678
	}
1679
	return $groups;
1680
}
1681

    
1682
function get_user_expiration_date($username) {
1683
	$user = getUserEntry($username);
1684
	if ($user['expires']) {
1685
		return $user['expires'];
1686
	}
1687
}
1688

    
1689
function is_account_expired($username) {
1690
	$expirydate = get_user_expiration_date($username);
1691
	if ($expirydate) {
1692
		if (strtotime("-1 day") > strtotime(date("m/d/Y", strtotime($expirydate)))) {
1693
			return true;
1694
		}
1695
	}
1696

    
1697
	return false;
1698
}
1699

    
1700
function is_account_disabled($username) {
1701
	$user = getUserEntry($username);
1702
	if (isset($user['disabled'])) {
1703
		return true;
1704
	}
1705

    
1706
	return false;
1707
}
1708

    
1709
function get_user_settings($username) {
1710
	global $config;
1711
	$settings = array();
1712
	$settings['widgets'] = $config['widgets'];
1713
	$settings['webgui']['dashboardcolumns'] = $config['system']['webgui']['dashboardcolumns'];
1714
	$settings['webgui']['webguihostnamemenu'] = $config['system']['webgui']['webguihostnamemenu'];
1715
	$settings['webgui']['webguicss'] = $config['system']['webgui']['webguicss'];
1716
	$settings['webgui']['logincss'] = $config['system']['webgui']['logincss'];
1717
	$settings['webgui']['interfacessort'] = isset($config['system']['webgui']['interfacessort']);
1718
	$settings['webgui']['dashboardavailablewidgetspanel'] = isset($config['system']['webgui']['dashboardavailablewidgetspanel']);
1719
	$settings['webgui']['webguifixedmenu'] = isset($config['system']['webgui']['webguifixedmenu']);
1720
	$settings['webgui']['webguileftcolumnhyper'] = isset($config['system']['webgui']['webguileftcolumnhyper']);
1721
	$settings['webgui']['disablealiaspopupdetail'] = isset($config['system']['webgui']['disablealiaspopupdetail']);
1722
	$settings['webgui']['systemlogsfilterpanel'] = isset($config['system']['webgui']['systemlogsfilterpanel']);
1723
	$settings['webgui']['systemlogsmanagelogpanel'] = isset($config['system']['webgui']['systemlogsmanagelogpanel']);
1724
	$settings['webgui']['statusmonitoringsettingspanel'] = isset($config['system']['webgui']['statusmonitoringsettingspanel']);
1725
	$settings['webgui']['pagenamefirst'] = isset($config['system']['webgui']['pagenamefirst']);
1726
	$user = getUserEntry($username);
1727
	if (isset($user['customsettings'])) {
1728
		$settings['customsettings'] = true;
1729
		if (isset($user['widgets'])) {
1730
			// This includes the 'sequence', and any widgetname-config per-widget settings.
1731
			$settings['widgets'] = $user['widgets'];
1732
		}
1733
		if (isset($user['dashboardcolumns'])) {
1734
			$settings['webgui']['dashboardcolumns'] = $user['dashboardcolumns'];
1735
		}
1736
		if (isset($user['webguicss'])) {
1737
			$settings['webgui']['webguicss'] = $user['webguicss'];
1738
		}
1739
		if (isset($user['webguihostnamemenu'])) {
1740
			$settings['webgui']['webguihostnamemenu'] = $user['webguihostnamemenu'];
1741
		}
1742
		$settings['webgui']['interfacessort'] = isset($user['interfacessort']);
1743
		$settings['webgui']['dashboardavailablewidgetspanel'] = isset($user['dashboardavailablewidgetspanel']);
1744
		$settings['webgui']['webguifixedmenu'] = isset($user['webguifixedmenu']);
1745
		$settings['webgui']['webguileftcolumnhyper'] = isset($user['webguileftcolumnhyper']);
1746
		$settings['webgui']['disablealiaspopupdetail'] = isset($user['disablealiaspopupdetail']);
1747
		$settings['webgui']['systemlogsfilterpanel'] = isset($user['systemlogsfilterpanel']);
1748
		$settings['webgui']['systemlogsmanagelogpanel'] = isset($user['systemlogsmanagelogpanel']);
1749
		$settings['webgui']['statusmonitoringsettingspanel'] = isset($user['statusmonitoringsettingspanel']);
1750
		$settings['webgui']['pagenamefirst'] = isset($user['pagenamefirst']);
1751
	} else {
1752
		$settings['customsettings'] = false;
1753
	}
1754

    
1755
	if ($settings['webgui']['dashboardcolumns'] < 1) {
1756
		$settings['webgui']['dashboardcolumns'] = 2;
1757
	}
1758

    
1759
	return $settings;
1760
}
1761

    
1762
function save_widget_settings($username, $settings, $message = "") {
1763
	global $config, $userindex;
1764
	$user = getUserEntry($username);
1765

    
1766
	if (strlen($message) > 0) {
1767
		$msgout = $message;
1768
	} else {
1769
		$msgout = gettext("Widget configuration has been changed.");
1770
	}
1771

    
1772
	if (isset($user['customsettings'])) {
1773
		$config['system']['user'][$userindex[$username]]['widgets'] = $settings;
1774
		write_config($msgout . " " . sprintf(gettext("(User %s)"), $username));
1775
	} else {
1776
		$config['widgets'] = $settings;
1777
		write_config($msgout);
1778
	}
1779
}
1780

    
1781
function auth_get_authserver($name) {
1782
	global $config;
1783

    
1784
	if (is_array($config['system']['authserver'])) {
1785
		foreach ($config['system']['authserver'] as $authcfg) {
1786
			if ($authcfg['name'] == $name) {
1787
				return $authcfg;
1788
			}
1789
		}
1790
	}
1791
	if ($name == "Local Database") {
1792
		return array("name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']);
1793
	}
1794
}
1795

    
1796
function auth_get_authserver_list() {
1797
	global $config;
1798

    
1799
	$list = array();
1800

    
1801
	if (is_array($config['system']['authserver'])) {
1802
		foreach ($config['system']['authserver'] as $authcfg) {
1803
			/* Add support for disabled entries? */
1804
			$list[$authcfg['name']] = $authcfg;
1805
		}
1806
	}
1807

    
1808
	$list["Local Database"] = array("name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']);
1809
	return $list;
1810
}
1811

    
1812
function getUserGroups($username, $authcfg, &$attributes = array()) {
1813
	global $config;
1814

    
1815
	$allowed_groups = array();
1816

    
1817
	switch ($authcfg['type']) {
1818
		case 'ldap':
1819
			$allowed_groups = @ldap_get_groups($username, $authcfg);
1820
			break;
1821
		case 'radius':
1822
			$allowed_groups = @radius_get_groups($attributes);
1823
			break;
1824
		default:
1825
			$user = getUserEntry($username);
1826
			$allowed_groups = @local_user_get_groups($user, true);
1827
			break;
1828
	}
1829

    
1830
	$member_groups = array();
1831
	if (is_array($config['system']['group'])) {
1832
		foreach ($config['system']['group'] as $group) {
1833
			if (in_array($group['name'], $allowed_groups)) {
1834
				$member_groups[] = $group['name'];
1835
			}
1836
		}
1837
	}
1838

    
1839
	return $member_groups;
1840
}
1841

    
1842
function authenticate_user($username, $password, $authcfg = NULL, &$attributes = array()) {
1843

    
1844
	if (is_array($username) || is_array($password)) {
1845
		return false;
1846
	}
1847

    
1848
	if (!$authcfg) {
1849
		return local_backed($username, $password);
1850
	}
1851

    
1852
	$authenticated = false;
1853
	switch ($authcfg['type']) {
1854
		case 'ldap':
1855
			if (ldap_backed($username, $password, $authcfg)) {
1856
				$authenticated = true;
1857
			}
1858
			break;
1859
		case 'radius':
1860
			if (radius_backed($username, $password, $authcfg, $attributes)) {
1861
				$authenticated = true;
1862
			}
1863
			break;
1864
		default:
1865
			/* lookup user object by name */
1866
			if (local_backed($username, $password)) {
1867
				$authenticated = true;
1868
			}
1869
			break;
1870
		}
1871

    
1872
	return $authenticated;
1873
}
1874

    
1875
function session_auth() {
1876
	global $config, $_SESSION, $page;
1877

    
1878
	// Handle HTTPS httponly and secure flags
1879
	$currentCookieParams = session_get_cookie_params();
1880
	session_set_cookie_params(
1881
		$currentCookieParams["lifetime"],
1882
		$currentCookieParams["path"],
1883
		NULL,
1884
		($config['system']['webgui']['protocol'] == "https"),
1885
		true
1886
	);
1887

    
1888
	phpsession_begin();
1889

    
1890
	// Detect protocol change
1891
	if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) {
1892
		phpsession_end();
1893
		return false;
1894
	}
1895

    
1896
	/* Validate incoming login request */
1897
	$attributes = array();
1898
	if (isset($_POST['login']) && !empty($_POST['usernamefld']) && !empty($_POST['passwordfld'])) {
1899
		$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
1900
		$remoteauth = authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg, $attributes);
1901
		if ($remoteauth || authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) {
1902
			// Generate a new id to avoid session fixation
1903
			session_regenerate_id();
1904
			$_SESSION['Logged_In'] = "True";
1905
			$_SESSION['remoteauth'] = $remoteauth;
1906
			$_SESSION['Username'] = $_POST['usernamefld'];
1907
			$_SESSION['user_radius_attributes'] = $attributes;
1908
			$_SESSION['last_access'] = time();
1909
			$_SESSION['protocol'] = $config['system']['webgui']['protocol'];
1910
			phpsession_end(true);
1911
			if (!isset($config['system']['webgui']['quietlogin'])) {
1912
				log_auth(sprintf(gettext("Successful login for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], $_SERVER['REMOTE_ADDR']));
1913
			}
1914
			if (isset($_POST['postafterlogin'])) {
1915
				return true;
1916
			} else {
1917
				if (empty($page)) {
1918
					$page = "/";
1919
				}
1920
				header("Location: {$page}");
1921
			}
1922
			exit;
1923
		} else {
1924
			/* give the user an error message */
1925
			$_SESSION['Login_Error'] = gettext("Username or Password incorrect");
1926
			log_auth("webConfigurator authentication error for '{$_POST['usernamefld']}' from {$_SERVER['REMOTE_ADDR']}");
1927
			if (isAjax()) {
1928
				echo "showajaxmessage('{$_SESSION['Login_Error']}');";
1929
				return;
1930
			}
1931
		}
1932
	}
1933

    
1934
	/* Show login page if they aren't logged in */
1935
	if (empty($_SESSION['Logged_In'])) {
1936
		phpsession_end(true);
1937
		return false;
1938
	}
1939

    
1940
	/* If session timeout isn't set, we don't mark sessions stale */
1941
	if (!isset($config['system']['webgui']['session_timeout'])) {
1942
		/* Default to 4 hour timeout if one is not set */
1943
		if ($_SESSION['last_access'] < (time() - 14400)) {
1944
			$_POST['logout'] = true;
1945
			$_SESSION['Logout'] = true;
1946
		} else {
1947
			$_SESSION['last_access'] = time();
1948
		}
1949
	} else if (intval($config['system']['webgui']['session_timeout']) == 0) {
1950
		/* only update if it wasn't ajax */
1951
		if (!isAjax()) {
1952
			$_SESSION['last_access'] = time();
1953
		}
1954
	} else {
1955
		/* Check for stale session */
1956
		if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
1957
			$_POST['logout'] = true;
1958
			$_SESSION['Logout'] = true;
1959
		} else {
1960
			/* only update if it wasn't ajax */
1961
			if (!isAjax()) {
1962
				$_SESSION['last_access'] = time();
1963
			}
1964
		}
1965
	}
1966

    
1967
	/* user hit the logout button */
1968
	if (isset($_POST['logout'])) {
1969

    
1970
		if ($_SESSION['Logout']) {
1971
			log_error(sprintf(gettext("Session timed out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR']));
1972
		} else {
1973
			log_error(sprintf(gettext("User logged out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR']));
1974
		}
1975

    
1976
		/* wipe out $_SESSION */
1977
		$_SESSION = array();
1978

    
1979
		if (isset($_COOKIE[session_name()])) {
1980
			setcookie(session_name(), '', time()-42000, '/');
1981
		}
1982

    
1983
		/* and destroy it */
1984
		phpsession_destroy();
1985

    
1986
		$scriptName = explode("/", $_SERVER["SCRIPT_FILENAME"]);
1987
		$scriptElms = count($scriptName);
1988
		$scriptName = $scriptName[$scriptElms-1];
1989

    
1990
		if (isAjax()) {
1991
			return false;
1992
		}
1993

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

    
1997
		return false;
1998
	}
1999

    
2000
	/*
2001
	 * this is for debugging purpose if you do not want to use Ajax
2002
	 * to submit a HTML form. It basically disables the observation
2003
	 * of the submit event and hence does not trigger Ajax.
2004
	 */
2005
	if ($_REQUEST['disable_ajax']) {
2006
		$_SESSION['NO_AJAX'] = "True";
2007
	}
2008

    
2009
	/*
2010
	 * Same to re-enable Ajax.
2011
	 */
2012
	if ($_REQUEST['enable_ajax']) {
2013
		unset($_SESSION['NO_AJAX']);
2014
	}
2015
	phpsession_end(true);
2016
	return true;
2017
}
2018

    
2019
?>
(2-2/60)