Project

General

Profile

Download (61.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-2013 BSD Perimeter
10
 * Copyright (c) 2013-2016 Electric Sheep Fencing
11
 * Copyright (c) 2014-2019 Rubicon Communications, LLC (Netgate)
12
 * All rights reserved.
13
 *
14
 * Licensed under the Apache License, Version 2.0 (the "License");
15
 * you may not use this file except in compliance with the License.
16
 * You may obtain a copy of the License at
17
 *
18
 * http://www.apache.org/licenses/LICENSE-2.0
19
 *
20
 * Unless required by applicable law or agreed to in writing, software
21
 * distributed under the License is distributed on an "AS IS" BASIS,
22
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23
 * See the License for the specific language governing permissions and
24
 * limitations under the License.
25
 */
26

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

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

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

    
45
	/* Fetch the contents of the lockout table. */
46
	$entries = array();
47
	exec("/sbin/pfctl -t 'sshguard' -T show", $entries);
48

    
49
	/* If the client is in the lockout table, print an error, kill states, and exit */
50
	if (in_array($_SERVER['REMOTE_ADDR'], array_map('trim', $entries))) {
51
		if (!security_checks_disabled()) {
52
			/* They may never see the error since the connection will be cut off, but try to be nice anyhow. */
53
			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."));
54
			/* If they are locked out, they shouldn't have a state. Disconnect their connections. */
55
			$retval = pfSense_kill_states($_SERVER['REMOTE_ADDR']);
56
			if (is_ipaddrv4($_SERVER['REMOTE_ADDR'])) {
57
				$retval = pfSense_kill_states("0.0.0.0/0", $_SERVER['REMOTE_ADDR']);
58
			} elseif (is_ipaddrv6($_SERVER['REMOTE_ADDR'])) {
59
				$retval = pfSense_kill_states("::", $_SERVER['REMOTE_ADDR']);
60
			}
61
			exit;
62
		}
63
		$security_passed = false;
64
	}
65
}
66

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

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

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

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

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

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

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

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

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

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

    
196
			if (!$found_host) {
197
				$interface_list_ips = get_configured_ip_addresses();
198
				foreach ($interface_list_ips as $ilips) {
199
					if (strcasecmp($referrer_host, $ilips) == 0) {
200
						$found_host = true;
201
						break;
202
					}
203
				}
204
				$interface_list_ipv6s = get_configured_ipv6_addresses(true);
205
				foreach ($interface_list_ipv6s as $ilipv6s) {
206
					$ilipv6s = explode('%', $ilipv6s)[0];
207
					if (strcasecmp($referrer_host, $ilipv6s) == 0) {
208
						$found_host = true;
209
						break;
210
					}
211
				}
212
				if ($referrer_host == "127.0.0.1" || $referrer_host == "localhost") {
213
					// allow SSH port forwarded connections and links from localhost
214
					$found_host = true;
215
				}
216
			}
217

    
218
			/* Fall back to probing active interface addresses rather than config.xml to allow
219
			 * changed addresses that have not yet been applied.
220
			 * See https://redmine.pfsense.org/issues/8822
221
			 */
222
			if (!$found_host) {
223
				$refifs = get_interface_arr();
224
				foreach ($refifs as $rif) {
225
					if (($referrer_host == find_interface_ip($rif)) ||
226
					    ($referrer_host == find_interface_ipv6($rif)) ||
227
					    ($referrer_host == find_interface_ipv6_ll($rif))) {
228
						$found_host = true;
229
						break;
230
					}
231
				}
232
			}
233
		}
234
		if ($found_host == false) {
235
			if (!security_checks_disabled()) {
236
				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.");
237
				exit;
238
			}
239
			$security_passed = false;
240
		}
241
	} else {
242
		$security_passed = false;
243
	}
244
}
245

    
246
if (function_exists("display_error_form") && $security_passed) {
247
	/* Security checks passed, so it should be OK to turn them back on */
248
	restore_security_checks();
249
}
250
unset($security_passed);
251

    
252
$groupindex = index_groups();
253
$userindex = index_users();
254

    
255
function index_groups() {
256
	global $g, $debug, $config, $groupindex;
257

    
258
	$groupindex = array();
259

    
260
	if (is_array($config['system']['group'])) {
261
		$i = 0;
262
		foreach ($config['system']['group'] as $groupent) {
263
			$groupindex[$groupent['name']] = $i;
264
			$i++;
265
		}
266
	}
267

    
268
	return ($groupindex);
269
}
270

    
271
function index_users() {
272
	global $g, $debug, $config;
273

    
274
	if (is_array($config['system']['user'])) {
275
		$i = 0;
276
		foreach ($config['system']['user'] as $userent) {
277
			$userindex[$userent['name']] = $i;
278
			$i++;
279
		}
280
	}
281

    
282
	return ($userindex);
283
}
284

    
285
function & getUserEntry($name) {
286
	global $debug, $config, $userindex;
287
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
288

    
289
	if (isset($userindex[$name])) {
290
		return $config['system']['user'][$userindex[$name]];
291
	} elseif ($authcfg['type'] != "Local Database") {
292
		$user = array();
293
		$user['name'] = $name;
294
		return $user;
295
	}
296
}
297

    
298
function & getUserEntryByUID($uid) {
299
	global $debug, $config;
300

    
301
	if (is_array($config['system']['user'])) {
302
		foreach ($config['system']['user'] as & $user) {
303
			if ($user['uid'] == $uid) {
304
				return $user;
305
			}
306
		}
307
	}
308

    
309
	return false;
310
}
311

    
312
function & getGroupEntry($name) {
313
	global $debug, $config, $groupindex;
314
	if (isset($groupindex[$name])) {
315
		return $config['system']['group'][$groupindex[$name]];
316
	}
317
}
318

    
319
function & getGroupEntryByGID($gid) {
320
	global $debug, $config;
321

    
322
	if (is_array($config['system']['group'])) {
323
		foreach ($config['system']['group'] as & $group) {
324
			if ($group['gid'] == $gid) {
325
				return $group;
326
			}
327
		}
328
	}
329

    
330
	return false;
331
}
332

    
333
function get_user_privileges(& $user) {
334
	global $config, $_SESSION;
335

    
336
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
337
	$allowed_groups = array();
338

    
339
	$privs = $user['priv'];
340
	if (!is_array($privs)) {
341
		$privs = array();
342
	}
343

    
344
	// cache auth results for a short time to ease load on auth services & logs
345
	if (isset($config['system']['webgui']['auth_refresh_time'])) {
346
		$recheck_time = $config['system']['webgui']['auth_refresh_time'];
347
	} else {
348
		$recheck_time = 30;
349
	}
350

    
351
	if ($authcfg['type'] == "ldap") {
352
		if (isset($_SESSION["ldap_allowed_groups"]) &&
353
		    (time() <= $_SESSION["auth_check_time"] + $recheck_time)) {
354
			$allowed_groups = $_SESSION["ldap_allowed_groups"];
355
		} else {
356
			$allowed_groups = @ldap_get_groups($user['name'], $authcfg);
357
			$_SESSION["ldap_allowed_groups"] = $allowed_groups;
358
			$_SESSION["auth_check_time"] = time();
359
		}
360
	} elseif ($authcfg['type'] == "radius") {
361
		if (isset($_SESSION["radius_allowed_groups"]) &&
362
		    (time() <= $_SESSION["auth_check_time"] + $recheck_time)) {
363
			$allowed_groups = $_SESSION["radius_allowed_groups"];
364
		} else {
365
			$allowed_groups = @radius_get_groups($_SESSION['user_radius_attributes']);
366
			$_SESSION["radius_allowed_groups"] = $allowed_groups;
367
			$_SESSION["auth_check_time"] = time();
368
		}
369
	}
370

    
371
	if (empty($allowed_groups)) {
372
		$allowed_groups = local_user_get_groups($user, true);
373
	}
374

    
375
	if (!is_array($allowed_groups)) {
376
		$allowed_groups = array('all');
377
	} else {
378
		$allowed_groups[] = 'all';
379
	}
380

    
381
	foreach ($allowed_groups as $name) {
382
		$group = getGroupEntry($name);
383
		if (is_array($group['priv'])) {
384
			$privs = array_merge($privs, $group['priv']);
385
		}
386
	}
387

    
388
	return $privs;
389
}
390

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

    
393
	if (!$privid || !is_array($userent)) {
394
		return false;
395
	}
396

    
397
	$privs = get_user_privileges($userent);
398

    
399
	if (!is_array($privs)) {
400
		return false;
401
	}
402

    
403
	if (!in_array($privid, $privs)) {
404
		return false;
405
	}
406

    
407
	return true;
408
}
409

    
410
function local_backed($username, $passwd) {
411

    
412
	$user = getUserEntry($username);
413
	if (!$user) {
414
		return false;
415
	}
416

    
417
	if (is_account_disabled($username) || is_account_expired($username)) {
418
		return false;
419
	}
420

    
421
	if ($user['bcrypt-hash']) {
422
		if (password_verify($passwd, $user['bcrypt-hash'])) {
423
			return true;
424
		}
425
	}
426

    
427
	//for backwards compatibility
428
	if ($user['password']) {
429
		if (crypt($passwd, $user['password']) == $user['password']) {
430
			return true;
431
		}
432
	}
433

    
434
	if ($user['md5-hash']) {
435
		if (md5($passwd) == $user['md5-hash']) {
436
			return true;
437
		}
438
	}
439

    
440
	return false;
441
}
442

    
443
function local_sync_accounts($u2add, $u2del, $g2add, $g2del) {
444
	global $config, $debug;
445

    
446
	if (empty($u2add) && empty($u2del) && empty($g2add) && empty($g2del)) {
447
		/* Nothing to be done here */
448
		return;
449
	}
450

    
451
	foreach($u2del as $user) {
452
		if ($user['uid'] < 2000 || $user['uid'] > 65000) {
453
			continue;
454
		}
455

    
456
		/*
457
		 * If a crontab was created to user, pw userdel will be
458
		 * interactive and can cause issues. Just remove crontab
459
		 * before run it when necessary
460
		 */
461
		unlink_if_exists("/var/cron/tabs/{$user['name']}");
462
		$cmd = "/usr/sbin/pw userdel -n " .
463
		    escapeshellarg($user['name']);
464
		if ($debug) {
465
			log_error(sprintf(gettext("Running: %s"), $cmd));
466
		}
467
		mwexec($cmd);
468
		local_group_del_user($user);
469

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

    
480
	foreach($g2del as $group) {
481
		if ($group['gid'] < 1999 || $group['gid'] > 65000) {
482
			continue;
483
		}
484

    
485
		$cmd = "/usr/sbin/pw groupdel -g " .
486
		    escapeshellarg($group['name']);
487
		if ($debug) {
488
			log_error(sprintf(gettext("Running: %s"), $cmd));
489
		}
490
		mwexec($cmd);
491

    
492
		$system_group = $config['system']['group'];
493
		for ($i = 0; $i < count($system_group); $i++) {
494
			if ($system_group[$i]['name'] == $group['name']) {
495
				log_error("Removing group: {$group['name']}");
496
				unset($config['system']['group'][$i]);
497
				break;
498
			}
499
		}
500
	}
501

    
502
	foreach ($u2add as $user) {
503
		log_error("Adding user: {$user['name']}");
504
		$config['system']['user'][] = $user;
505
	}
506

    
507
	foreach ($g2add as $group) {
508
		log_error("Adding group: {$group['name']}");
509
		$config['system']['group'][] = $group;
510
	}
511

    
512
	/* Sort it alphabetically */
513
	usort($config['system']['user'], function($a, $b) {
514
		return strcmp($a['name'], $b['name']);
515
	});
516
	usort($config['system']['group'], function($a, $b) {
517
		return strcmp($a['name'], $b['name']);
518
	});
519

    
520
	write_config("Sync'd users and groups via XMLRPC");
521

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

    
526
	foreach ($u2add as $user) {
527
		local_user_set($user);
528
	}
529

    
530
	foreach ($g2add as $group) {
531
		local_group_set($group);
532
	}
533
}
534

    
535
function local_reset_accounts() {
536
	global $debug, $config;
537

    
538
	/* remove local users to avoid uid conflicts */
539
	$fd = popen("/usr/sbin/pw usershow -a", "r");
540
	if ($fd) {
541
		while (!feof($fd)) {
542
			$line = explode(":", fgets($fd));
543
			if ($line[0] != "admin") {
544
				if (!strncmp($line[0], "_", 1)) {
545
					continue;
546
				}
547
				if ($line[2] < 2000) {
548
					continue;
549
				}
550
				if ($line[2] > 65000) {
551
					continue;
552
				}
553
			}
554
			/*
555
			 * If a crontab was created to user, pw userdel will be interactive and
556
			 * can cause issues. Just remove crontab before run it when necessary
557
			 */
558
			unlink_if_exists("/var/cron/tabs/{$line[0]}");
559
			$cmd = "/usr/sbin/pw userdel -n " . escapeshellarg($line[0]);
560
			if ($debug) {
561
				log_error(sprintf(gettext("Running: %s"), $cmd));
562
			}
563
			mwexec($cmd);
564
		}
565
		pclose($fd);
566
	}
567

    
568
	/* remove local groups to avoid gid conflicts */
569
	$gids = array();
570
	$fd = popen("/usr/sbin/pw groupshow -a", "r");
571
	if ($fd) {
572
		while (!feof($fd)) {
573
			$line = explode(":", fgets($fd));
574
			if (!strncmp($line[0], "_", 1)) {
575
				continue;
576
			}
577
			if ($line[2] < 2000) {
578
				continue;
579
			}
580
			if ($line[2] > 65000) {
581
				continue;
582
			}
583
			$cmd = "/usr/sbin/pw groupdel -g " . escapeshellarg($line[2]);
584
			if ($debug) {
585
				log_error(sprintf(gettext("Running: %s"), $cmd));
586
			}
587
			mwexec($cmd);
588
		}
589
		pclose($fd);
590
	}
591

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

    
596
	/* sync all local users */
597
	if (is_array($config['system']['user'])) {
598
		foreach ($config['system']['user'] as $user) {
599
			local_user_set($user);
600
		}
601
	}
602

    
603
	/* sync all local groups */
604
	if (is_array($config['system']['group'])) {
605
		foreach ($config['system']['group'] as $group) {
606
			local_group_set($group);
607
		}
608
	}
609
}
610

    
611
function local_user_set(& $user) {
612
	global $g, $debug;
613

    
614
	if (empty($user['password']) && empty($user['bcrypt-hash'])) {
615
		log_error("There is something wrong in the config because user {$user['name']} password is missing!");
616
		return;
617
	}
618

    
619

    
620
	$home_base = "/home/";
621
	$user_uid = $user['uid'];
622
	$user_name = $user['name'];
623
	$user_home = "{$home_base}{$user_name}";
624
	$user_shell = "/etc/rc.initial";
625
	$user_group = "nobody";
626

    
627
	// Ensure $home_base exists and is writable
628
	if (!is_dir($home_base)) {
629
		mkdir($home_base, 0755);
630
	}
631

    
632
	$lock_account = false;
633
	/* configure shell type */
634
	/* Cases here should be ordered by most privileged to least privileged. */
635
	if (userHasPrivilege($user, "user-shell-access") || userHasPrivilege($user, "page-all")) {
636
		$user_shell = "/bin/tcsh";
637
	} elseif (userHasPrivilege($user, "user-copy-files-chroot")) {
638
		$user_shell = "/usr/local/sbin/scponlyc";
639
	} elseif (userHasPrivilege($user, "user-copy-files")) {
640
		$user_shell = "/usr/local/bin/scponly";
641
	} elseif (userHasPrivilege($user, "user-ssh-tunnel")) {
642
		$user_shell = "/usr/local/sbin/ssh_tunnel_shell";
643
	} elseif (userHasPrivilege($user, "user-ipsec-xauth-dialin")) {
644
		$user_shell = "/sbin/nologin";
645
	} else {
646
		$user_shell = "/sbin/nologin";
647
		$lock_account = true;
648
	}
649

    
650
	/* Lock out disabled or expired users, unless it's root/admin. */
651
	if ((is_account_disabled($user_name) || is_account_expired($user_name)) && ($user_uid != 0)) {
652
		$user_shell = "/sbin/nologin";
653
		$lock_account = true;
654
	}
655

    
656
	/* root user special handling */
657
	if ($user_uid == 0) {
658
		$cmd = "/usr/sbin/pw usermod -q -n root -s /bin/sh -H 0";
659
		if ($debug) {
660
			log_error(sprintf(gettext("Running: %s"), $cmd));
661
		}
662
		$fd = popen($cmd, "w");
663
		if (empty($user['bcrypt-hash'])) {
664
			fwrite($fd, $user['password']);
665
		} else {
666
			fwrite($fd, $user['bcrypt-hash']);
667
		}
668
		pclose($fd);
669
		$user_group = "wheel";
670
		$user_home = "/root";
671
		$user_shell = "/etc/rc.initial";
672
	}
673

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

    
680
	$skel_dir = '/etc/skel';
681

    
682
	/* determine add or mod */
683
	if (($userattrs[0] != $user['name']) || (!strncmp($pwread, "pw:", 3))) {
684
		$user_op = "useradd -m -k " . escapeshellarg($skel_dir) . " -o";
685
	} else {
686
		$user_op = "usermod";
687
	}
688

    
689
	$comment = str_replace(array(":", "!", "@"), " ", $user['descr']);
690
	/* add or mod pw db */
691
	$cmd = "/usr/sbin/pw {$user_op} -q " .
692
			" -u " . escapeshellarg($user_uid) .
693
			" -n " . escapeshellarg($user_name) .
694
			" -g " . escapeshellarg($user_group) .
695
			" -s " . escapeshellarg($user_shell) .
696
			" -d " . escapeshellarg($user_home) .
697
			" -c " . escapeshellarg($comment) .
698
			" -H 0 2>&1";
699

    
700
	if ($debug) {
701
		log_error(sprintf(gettext("Running: %s"), $cmd));
702
	}
703
	$fd = popen($cmd, "w");
704
	if (empty($user['bcrypt-hash'])) {
705
		fwrite($fd, $user['password']);
706
	} else {
707
		fwrite($fd, $user['bcrypt-hash']);
708
	}
709
	pclose($fd);
710

    
711
	/* create user directory if required */
712
	if (!is_dir($user_home)) {
713
		mkdir($user_home, 0700);
714
	}
715
	@chown($user_home, $user_name);
716
	@chgrp($user_home, $user_group);
717

    
718
	/* Make sure all users have last version of config files */
719
	foreach (glob("{$skel_dir}/dot.*") as $dot_file) {
720
		$target = $user_home . '/' . substr(basename($dot_file), 3);
721
		@copy($dot_file, $target);
722
		@chown($target, $user_name);
723
		@chgrp($target, $user_group);
724
	}
725

    
726
	/* write out ssh authorized key file */
727
	if ($user['authorizedkeys']) {
728
		if (!is_dir("{$user_home}/.ssh")) {
729
			@mkdir("{$user_home}/.ssh", 0700);
730
			@chown("{$user_home}/.ssh", $user_name);
731
		}
732
		$keys = base64_decode($user['authorizedkeys']);
733
		@file_put_contents("{$user_home}/.ssh/authorized_keys", $keys);
734
		@chown("{$user_home}/.ssh/authorized_keys", $user_name);
735
	} else {
736
		unlink_if_exists("{$user_home}/.ssh/authorized_keys");
737
	}
738

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

    
742
}
743

    
744
function local_user_del($user) {
745
	global $debug;
746

    
747
	/* remove all memberships */
748
	local_user_set_groups($user);
749

    
750
	/* Don't remove /root */
751
	if ($user['uid'] != 0) {
752
		$rmhome = "-r";
753
	}
754

    
755
	/* read from pw db */
756
	$fd = popen("/usr/sbin/pw usershow -n {$user['name']} 2>&1", "r");
757
	$pwread = fgets($fd);
758
	pclose($fd);
759
	$userattrs = explode(":", trim($pwread));
760

    
761
	if ($userattrs[0] != $user['name']) {
762
		log_error("Tried to remove user {$user['name']} but got user {$userattrs[0]} instead. Bailing.");
763
		return;
764
	}
765

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

    
769
	if ($debug) {
770
		log_error(sprintf(gettext("Running: %s"), $cmd));
771
	}
772
	mwexec($cmd);
773

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

    
778
function local_user_set_password(&$user, $password) {
779
	unset($user['password']);
780
	unset($user['md5-hash']);
781
	$user['bcrypt-hash'] = password_hash($password, PASSWORD_BCRYPT);
782
}
783

    
784
function local_user_get_groups($user, $all = false) {
785
	global $debug, $config;
786

    
787
	$groups = array();
788
	if (!is_array($config['system']['group'])) {
789
		return $groups;
790
	}
791

    
792
	foreach ($config['system']['group'] as $group) {
793
		if ($all || (!$all && ($group['name'] != "all"))) {
794
			if (is_array($group['member'])) {
795
				if (in_array($user['uid'], $group['member'])) {
796
					$groups[] = $group['name'];
797
				}
798
			}
799
		}
800
	}
801

    
802
	if ($all) {
803
		$groups[] = "all";
804
	}
805

    
806
	sort($groups);
807

    
808
	return $groups;
809

    
810
}
811

    
812
function local_user_set_groups($user, $new_groups = NULL) {
813
	global $debug, $config, $groupindex, $userindex;
814

    
815
	if (!is_array($config['system']['group'])) {
816
		return;
817
	}
818

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

    
822
	if (!is_array($new_groups)) {
823
		$new_groups = array();
824
	}
825

    
826
	if (!is_array($cur_groups)) {
827
		$cur_groups = array();
828
	}
829

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

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

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

    
866
	/* sync all modified groups */
867
	foreach ($mod_groups as $group) {
868
		local_group_set($group);
869
	}
870
}
871

    
872
function local_group_del_user($user) {
873
	global $config;
874

    
875
	if (!is_array($config['system']['group'])) {
876
		return;
877
	}
878

    
879
	foreach ($config['system']['group'] as $group) {
880
		if (is_array($group['member'])) {
881
			foreach ($group['member'] as $idx => $uid) {
882
				if ($user['uid'] == $uid) {
883
					unset($config['system']['group']['member'][$idx]);
884
				}
885
			}
886
		}
887
	}
888
}
889

    
890
function local_group_set($group, $reset = false) {
891
	global $debug;
892

    
893
	$group_name = $group['name'];
894
	$group_gid = $group['gid'];
895
	$group_members = '';
896

    
897
	if (!$reset && !empty($group['member']) && count($group['member']) > 0) {
898
		$group_members = implode(",", $group['member']);
899
	}
900

    
901
	if (empty($group_name)) {
902
		return;
903
	}
904

    
905
	// If the group is now remote, make sure there is no local group with the same name
906
	if ($group['scope'] == "remote") {
907
		local_group_del($group);
908
		return;
909
	}
910

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

    
918
	/* add or mod group db */
919
	$cmd = "/usr/sbin/pw {$group_op} " .
920
		escapeshellarg($group_name) .
921
		" -g " . escapeshellarg($group_gid) .
922
		" -M " . escapeshellarg($group_members) . " 2>&1";
923

    
924
	if ($debug) {
925
		log_error(sprintf(gettext("Running: %s"), $cmd));
926
	}
927

    
928
	mwexec($cmd);
929
}
930

    
931
function local_group_del($group) {
932
	global $debug;
933

    
934
	/* delete from group db */
935
	$cmd = "/usr/sbin/pw groupdel " . escapeshellarg($group['name']);
936

    
937
	if ($debug) {
938
		log_error(sprintf(gettext("Running: %s"), $cmd));
939
	}
940
	mwexec($cmd);
941
}
942

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

    
959
	/* first check if there is even an LDAP server populated */
960
	if (!$ldapserver) {
961
		return false;
962
	}
963

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

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

    
975
	/* Setup CA environment if needed. */
976
	ldap_setup_caenv($ldap, $authcfg);
977

    
978
	return true;
979
}
980

    
981
function ldap_setup_caenv($ldap, $authcfg) {
982
	global $g;
983
	require_once("certs.inc");
984

    
985
	unset($caref);
986
	if (empty($authcfg['ldap_caref']) || strstr($authcfg['ldap_urltype'], "Standard")) {
987
		ldap_set_option($ldap, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
988
		return;
989
	} elseif ($authcfg['ldap_caref'] == "global") {
990
		ldap_set_option($ldap, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_HARD);
991
		ldap_set_option($ldap, LDAP_OPT_X_TLS_CACERTDIR, "/etc/ssl/");
992
		ldap_set_option($ldap, LDAP_OPT_X_TLS_CACERTFILE, "/etc/ssl/cert.pem");
993
	} else {
994
		$caref = lookup_ca($authcfg['ldap_caref']);
995
		$param = array('caref' => $authcfg['ldap_caref']);
996
		$cachain = ca_chain($param);
997
		if (!$caref) {
998
			log_error(sprintf(gettext("LDAP: Could not lookup CA by reference for host %s."), $authcfg['ldap_caref']));
999
			/* XXX: Prevent for credential leaking since we cannot setup the CA env. Better way? */
1000
			ldap_set_option($ldap, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_HARD);
1001
			return;
1002
		}
1003

    
1004
		$cert_path = "{$g['varrun_path']}/certs";
1005
		safe_mkdir($cert_path);
1006
		unlink_if_exists("{$cert_path}/{$caref['refid']}.ca");
1007
		file_put_contents("{$cert_path}/{$caref['refid']}.ca", $cachain);
1008
		@chmod("{$cert_path}/{$caref['refid']}.ca", 0600);
1009

    
1010
		ldap_set_option($ldap, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_HARD);
1011
		/* XXX: Probably even the hashed link should be created for this? */
1012
		ldap_set_option($ldap, LDAP_OPT_X_TLS_CACERTDIR, $cert_path);
1013
		ldap_set_option($ldap, LDAP_OPT_X_TLS_CACERTFILE, "{$cert_path}/{$caref['refid']}.ca");
1014
	}
1015
}
1016

    
1017
function ldap_test_bind($authcfg) {
1018
	global $debug, $config, $g;
1019

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

    
1045
	/* first check if there is even an LDAP server populated */
1046
	if (!$ldapserver) {
1047
		return false;
1048
	}
1049

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

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

    
1061
	/* Setup CA environment if needed. */
1062
	ldap_setup_caenv($ldap, $authcfg);
1063

    
1064
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1065
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1066
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1067
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1068
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1069

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

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

    
1090
	@ldap_unbind($ldap);
1091

    
1092
	return true;
1093
}
1094

    
1095
function ldap_get_user_ous($show_complete_ou=true, $authcfg) {
1096
	global $debug, $config, $g;
1097

    
1098
	if (!function_exists("ldap_connect")) {
1099
		return;
1100
	}
1101

    
1102
	$ous = array();
1103

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

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

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

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

    
1149
	/* Setup CA environment if needed. */
1150
	ldap_setup_caenv($ldap, $authcfg);
1151

    
1152
	$ldapfilter = "(|(ou=*)(cn=Users))";
1153

    
1154
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1155
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1156
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1157
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1158
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1159

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

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

    
1182
	if ($ldapscope == "one") {
1183
		$ldapfunc = "ldap_list";
1184
	} else {
1185
		$ldapfunc = "ldap_search";
1186
	}
1187

    
1188
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
1189
	$info = @ldap_get_entries($ldap, $search);
1190

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

    
1209
	@ldap_unbind($ldap);
1210

    
1211
	return $ous;
1212
}
1213

    
1214
function ldap_get_groups($username, $authcfg) {
1215
	global $debug, $config;
1216

    
1217
	if (!function_exists("ldap_connect")) {
1218
		return;
1219
	}
1220

    
1221
	if (!$username) {
1222
		return false;
1223
	}
1224

    
1225
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1226
		$username_split = explode("@", $username);
1227
		$username = $username_split[0];
1228
	}
1229

    
1230
	if (stristr($username, "\\")) {
1231
		$username_split = explode("\\", $username);
1232
		$username = $username_split[0];
1233
	}
1234

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

    
1273
	if (isset($authcfg['ldap_rfc2307'])) {
1274
		$ldapdn = $ldapbasedn;
1275
	} else {
1276
		$ldapdn = $_SESSION['ldapdn'];
1277
	}
1278

    
1279
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
1280
	$ldapgroupattribute = strtolower($ldapgroupattribute);
1281
	$memberof = array();
1282

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

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

    
1294
	/* Setup CA environment if needed. */
1295
	ldap_setup_caenv($ldap, $authcfg);
1296

    
1297
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1298
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1299
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1300
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1301
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1302

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

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

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

    
1336
	$search = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
1337
	$info = @ldap_get_entries($ldap, $search);
1338

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

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

    
1352
	/* Time to close LDAP connection */
1353
	@ldap_unbind($ldap);
1354

    
1355
	$groups = print_r($memberof, true);
1356

    
1357
	//log_error("Returning groups ".$groups." for user $username");
1358

    
1359
	return $memberof;
1360
}
1361

    
1362
function ldap_format_host($host) {
1363
	return is_ipaddrv6($host) ? "[$host]" : $host ;
1364
}
1365

    
1366
function ldap_backed($username, $passwd, $authcfg, &$attributes = array()) {
1367
	global $debug, $config;
1368

    
1369
	if (!$username) {
1370
		$attributes['error_message'] = gettext("Invalid Login.");
1371
		return false;
1372
	}
1373

    
1374
	if (!function_exists("ldap_connect")) {
1375
		log_error(gettext("ERROR! unable to find ldap_connect() function."));
1376
		$attributes['error_message'] = gettext("Internal error during authentication.");
1377
		return null;
1378
	}
1379

    
1380
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1381
		$username_split = explode("@", $username);
1382
		$username = $username_split[0];
1383
	}
1384
	if (stristr($username, "\\")) {
1385
		$username_split = explode("\\", $username);
1386
		$username = $username_split[0];
1387
	}
1388

    
1389
	$username = ldap_escape($username, null, LDAP_ESCAPE_FILTER);
1390

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

    
1429
	/* first check if there is even an LDAP server populated */
1430
	if (!$ldapserver) {
1431
		log_error(gettext("ERROR! could not find details of the LDAP server used for authentication."));
1432
		$attributes['error_message'] =  gettext("Internal error during authentication.");
1433
		return null;
1434
	}
1435

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

    
1442
	/* Setup CA environment if needed. */
1443
	ldap_setup_caenv($ldap, $authcfg);
1444

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

    
1451
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1452
		if (!(@ldap_start_tls($ldap))) {
1453
			log_error(sprintf(gettext("ERROR! could not connect to LDAP server %s using STARTTLS."), $ldapname));
1454
			$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1455
			@ldap_close($ldap);
1456
			return null;
1457
		}
1458
	}
1459

    
1460
	if ($error == true) {
1461
		$errormsg = sprintf(gettext("ERROR! Could not connect to server %s."), $ldapname);
1462
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1463
		return null;
1464
	}
1465

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

    
1478
	if ($error == true) {
1479
		@ldap_close($ldap);
1480
		log_error(sprintf(gettext("ERROR! Could not bind to LDAP server %s. Please check the bind credentials."), $ldapname));
1481
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1482
		return null;
1483
	}
1484

    
1485
	/* Get LDAP Authcontainers and split em up. */
1486
	$ldac_splits = explode(";", $ldapauthcont);
1487

    
1488
	/* setup the usercount so we think we haven't found anyone yet */
1489
	$usercount = 0;
1490

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

    
1536
	if ($usercount != 1) {
1537
		@ldap_unbind($ldap);
1538
		if ($debug) {
1539
			if ($usercount === 0) {
1540
				log_error(sprintf(gettext("ERROR! LDAP search failed, no user matching %s was found."), $username));
1541
			} else {
1542
				log_error(sprintf(gettext("ERROR! LDAP search failed, multiple users matching %s were found."), $username));
1543
			}
1544
		}
1545
		$attributes['error_message'] = gettext("Invalid login specified.");
1546
		return false;
1547
	}
1548

    
1549
	/* Now lets bind as the user we found */
1550
	$passwd = isset($authcfg['ldap_utf8']) ? utf8_encode($passwd) : $passwd;
1551
	if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
1552
		if ($debug) {
1553
			log_error(sprintf(gettext('ERROR! Could not login to server %1$s as user %2$s: %3$s'), $ldapname, $username, ldap_error($ldap)));
1554
		}
1555
		@ldap_unbind($ldap);
1556
		return false;
1557
	}
1558

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

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

    
1567
	return true;
1568
}
1569

    
1570
function radius_backed($username, $password, $authcfg, &$attributes = array()) {
1571
	global $debug, $config;
1572
	$ret = false;
1573

    
1574
	require_once("Auth/RADIUS.php");
1575
	require_once("Crypt/CHAP.php");
1576

    
1577
	if ($authcfg) {
1578
		$radiusservers = array();
1579
		$radiusservers[0]['ipaddr'] = $authcfg['host'];
1580
		$radiusservers[0]['port'] = $authcfg['radius_auth_port'];
1581
		$radiusservers[0]['sharedsecret'] = $authcfg['radius_secret'];
1582
		$radiusservers[0]['timeout'] = $authcfg['radius_timeout'];
1583
		if(isset($authcfg['radius_protocol'])) {
1584
			$radius_protocol = $authcfg['radius_protocol'];
1585
		} else {
1586
			$radius_protocol = 'PAP';
1587
		}
1588
	} else {
1589
		log_error(gettext("ERROR! could not find details of the RADIUS server used for authentication."));
1590
		$attributes['error_message'] =  gettext("Internal error during authentication.");
1591
		return null;
1592
	}
1593

    
1594
	// Create our instance
1595
	$classname = 'Auth_RADIUS_' . $radius_protocol;
1596
	$rauth = new $classname($username, $password);
1597

    
1598
	/* Add new servers to our instance */
1599
	foreach ($radiusservers as $radsrv) {
1600
		$timeout = (is_numeric($radsrv['timeout'])) ? $radsrv['timeout'] : 5;
1601
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret'], $timeout);
1602
	}
1603

    
1604
	// Construct data package
1605
	$rauth->username = $username;
1606
	switch ($radius_protocol) {
1607
		case 'CHAP_MD5':
1608
		case 'MSCHAPv1':
1609
			$classname = $radius_protocol == 'MSCHAPv1' ? 'Crypt_CHAP_MSv1' : 'Crypt_CHAP_MD5';
1610
			$crpt = new $classname;
1611
			$crpt->username = $username;
1612
			$crpt->password = $password;
1613
			$rauth->challenge = $crpt->challenge;
1614
			$rauth->chapid = $crpt->chapid;
1615
			$rauth->response = $crpt->challengeResponse();
1616
			$rauth->flags = 1;
1617
			break;
1618

    
1619
		case 'MSCHAPv2':
1620
			$crpt = new Crypt_CHAP_MSv2;
1621
			$crpt->username = $username;
1622
			$crpt->password = $password;
1623
			$rauth->challenge = $crpt->authChallenge;
1624
			$rauth->peerChallenge = $crpt->peerChallenge;
1625
			$rauth->chapid = $crpt->chapid;
1626
			$rauth->response = $crpt->challengeResponse();
1627
			break;
1628

    
1629
		default:
1630
			$rauth->password = $password;
1631
			break;
1632
	}
1633

    
1634
	if (PEAR::isError($rauth->start())) {
1635
		$ret = null;
1636
		log_error(sprintf(gettext("Error during RADIUS authentication : %s"), $rauth->getError()));
1637
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1638
	} else {
1639
		$nasid = $attributes['nas_identifier'];
1640
		$nasip = $authcfg['radius_nasip_attribute'];
1641
		if (empty($nasid)) {
1642
			$nasid = gethostname(); //If no RADIUS NAS-Identifier is given : we use pfsense's hostname as NAS-Identifier
1643
		}
1644
		if (!is_ipaddr($nasip)) {
1645
			$nasip = get_interface_ip($nasip);
1646
			
1647
			if (!is_ipaddr($nasip)) {
1648
				$nasip = get_interface_ip();//We use wan interface IP as fallback for NAS-IP-Address
1649
			}
1650
		}
1651
		$nasmac = get_interface_mac(find_ip_interface($nasip));
1652

    
1653
		$rauth->putAttribute(RADIUS_NAS_IP_ADDRESS, $nasip, "addr");
1654
		$rauth->putAttribute(RADIUS_NAS_IDENTIFIER, $nasid);
1655
		
1656
		if(!empty($attributes['calling_station_id'])) {
1657
			$rauth->putAttribute(RADIUS_CALLING_STATION_ID, $attributes['calling_station_id']);
1658
		}
1659
		// Carefully check that interface has a MAC address
1660
		if(!empty($nasmac)) {
1661
			$nasmac = mac_format($nasmac);
1662
			$rauth->putAttribute(RADIUS_CALLED_STATION_ID, $nasmac.':'.gethostname());
1663
		}
1664
		if(!empty($attributes['nas_port_type'])) {
1665
			$rauth->putAttribute(RADIUS_NAS_PORT_TYPE, $attributes['nas_port_type']);
1666
		}		
1667
		if(!empty($attributes['nas_port'])) {
1668
			$rauth->putAttribute(RADIUS_NAS_PORT, intval($attributes['nas_port']), 'integer');
1669
		}
1670
		if(!empty($attributes['framed_ip']) && is_ipaddr($attributes['framed_ip'])) {
1671
			$rauth->putAttribute(RADIUS_FRAMED_IP_ADDRESS, $attributes['framed_ip'], "addr");
1672
		}
1673
	}
1674

    
1675
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1676

    
1677
	/* Send request */
1678
	$result = $rauth->send();
1679
	if (PEAR::isError($result)) {
1680
		log_error(sprintf(gettext("Error during RADIUS authentication : %s"), $rauth->getError()));
1681
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1682
		$ret = null;
1683
	} else if ($result === true) {
1684
		$ret = true;
1685
	} else {
1686
		$ret = false;
1687
	}
1688

    
1689
	
1690
	// Get attributes, even if auth failed.
1691
	if ($rauth->getAttributes()) {
1692
	$attributes = array_merge($attributes,$rauth->listAttributes());
1693

    
1694
	// We convert the session_terminate_time to unixtimestamp if its set before returning the whole array to our caller
1695
	if (!empty($attributes['session_terminate_time'])) {
1696
			$stt = &$attributes['session_terminate_time'];
1697
			$stt = strtotime(preg_replace("/\+(\d+):(\d+)$/", " +\${1}\${2}", preg_replace("/(\d+)T(\d+)/", "\${1} \${2}",$stt)));
1698
		}
1699
	}
1700
	
1701
	// close OO RADIUS_AUTHENTICATION
1702
	$rauth->close();
1703

    
1704
	return $ret;
1705
}
1706

    
1707
/*
1708
	$attributes must contain a "class" key containing the groups and local
1709
	groups must exist to match.
1710
*/
1711
function radius_get_groups($attributes) {
1712
	$groups = array();
1713
	if (!empty($attributes) && is_array($attributes) && (!empty($attributes['class']) || !empty($attributes['class_int']))) {
1714
		/* Some RADIUS servers return multiple class attributes, so check them all. */
1715
		$groups = array();
1716
		if (!empty($attributes['class']) && is_array($attributes['class'])) {
1717
			foreach ($attributes['class'] as $class) {
1718
				$groups = array_unique(array_merge($groups, explode(";", $class)));
1719
			}
1720
		}
1721

    
1722
		foreach ($groups as & $grp) {
1723
			$grp = trim($grp);
1724
			if (strtolower(substr($grp, 0, 3)) == "ou=") {
1725
				$grp = substr($grp, 3);
1726
			}
1727
		}
1728
	}
1729
	return $groups;
1730
}
1731

    
1732
function get_user_expiration_date($username) {
1733
	$user = getUserEntry($username);
1734
	if ($user['expires']) {
1735
		return $user['expires'];
1736
	}
1737
}
1738

    
1739
function is_account_expired($username) {
1740
	$expirydate = get_user_expiration_date($username);
1741
	if ($expirydate) {
1742
		if (strtotime("-1 day") > strtotime(date("m/d/Y", strtotime($expirydate)))) {
1743
			return true;
1744
		}
1745
	}
1746

    
1747
	return false;
1748
}
1749

    
1750
function is_account_disabled($username) {
1751
	$user = getUserEntry($username);
1752
	if (isset($user['disabled'])) {
1753
		return true;
1754
	}
1755

    
1756
	return false;
1757
}
1758

    
1759
function get_user_settings($username) {
1760
	global $config;
1761
	$settings = array();
1762
	$settings['widgets'] = $config['widgets'];
1763
	$settings['webgui']['dashboardcolumns'] = $config['system']['webgui']['dashboardcolumns'];
1764
	$settings['webgui']['webguihostnamemenu'] = $config['system']['webgui']['webguihostnamemenu'];
1765
	$settings['webgui']['webguicss'] = $config['system']['webgui']['webguicss'];
1766
	$settings['webgui']['logincss'] = $config['system']['webgui']['logincss'];
1767
	$settings['webgui']['interfacessort'] = isset($config['system']['webgui']['interfacessort']);
1768
	$settings['webgui']['dashboardavailablewidgetspanel'] = isset($config['system']['webgui']['dashboardavailablewidgetspanel']);
1769
	$settings['webgui']['webguifixedmenu'] = isset($config['system']['webgui']['webguifixedmenu']);
1770
	$settings['webgui']['webguileftcolumnhyper'] = isset($config['system']['webgui']['webguileftcolumnhyper']);
1771
	$settings['webgui']['disablealiaspopupdetail'] = isset($config['system']['webgui']['disablealiaspopupdetail']);
1772
	$settings['webgui']['systemlogsfilterpanel'] = isset($config['system']['webgui']['systemlogsfilterpanel']);
1773
	$settings['webgui']['systemlogsmanagelogpanel'] = isset($config['system']['webgui']['systemlogsmanagelogpanel']);
1774
	$settings['webgui']['statusmonitoringsettingspanel'] = isset($config['system']['webgui']['statusmonitoringsettingspanel']);
1775
	$settings['webgui']['pagenamefirst'] = isset($config['system']['webgui']['pagenamefirst']);
1776
	$user = getUserEntry($username);
1777
	if (isset($user['customsettings'])) {
1778
		$settings['customsettings'] = true;
1779
		if (isset($user['widgets'])) {
1780
			// This includes the 'sequence', and any widgetname-config per-widget settings.
1781
			$settings['widgets'] = $user['widgets'];
1782
		}
1783
		if (isset($user['dashboardcolumns'])) {
1784
			$settings['webgui']['dashboardcolumns'] = $user['dashboardcolumns'];
1785
		}
1786
		if (isset($user['webguicss'])) {
1787
			$settings['webgui']['webguicss'] = $user['webguicss'];
1788
		}
1789
		if (isset($user['webguihostnamemenu'])) {
1790
			$settings['webgui']['webguihostnamemenu'] = $user['webguihostnamemenu'];
1791
		}
1792
		$settings['webgui']['interfacessort'] = isset($user['interfacessort']);
1793
		$settings['webgui']['dashboardavailablewidgetspanel'] = isset($user['dashboardavailablewidgetspanel']);
1794
		$settings['webgui']['webguifixedmenu'] = isset($user['webguifixedmenu']);
1795
		$settings['webgui']['webguileftcolumnhyper'] = isset($user['webguileftcolumnhyper']);
1796
		$settings['webgui']['disablealiaspopupdetail'] = isset($user['disablealiaspopupdetail']);
1797
		$settings['webgui']['systemlogsfilterpanel'] = isset($user['systemlogsfilterpanel']);
1798
		$settings['webgui']['systemlogsmanagelogpanel'] = isset($user['systemlogsmanagelogpanel']);
1799
		$settings['webgui']['statusmonitoringsettingspanel'] = isset($user['statusmonitoringsettingspanel']);
1800
		$settings['webgui']['pagenamefirst'] = isset($user['pagenamefirst']);
1801
	} else {
1802
		$settings['customsettings'] = false;
1803
	}
1804

    
1805
	if ($settings['webgui']['dashboardcolumns'] < 1) {
1806
		$settings['webgui']['dashboardcolumns'] = 2;
1807
	}
1808

    
1809
	return $settings;
1810
}
1811

    
1812
function save_widget_settings($username, $settings, $message = "") {
1813
	global $config, $userindex;
1814
	$user = getUserEntry($username);
1815

    
1816
	if (strlen($message) > 0) {
1817
		$msgout = $message;
1818
	} else {
1819
		$msgout = gettext("Widget configuration has been changed.");
1820
	}
1821

    
1822
	if (isset($user['customsettings'])) {
1823
		$config['system']['user'][$userindex[$username]]['widgets'] = $settings;
1824
		write_config($msgout . " " . sprintf(gettext("(User %s)"), $username));
1825
	} else {
1826
		$config['widgets'] = $settings;
1827
		write_config($msgout);
1828
	}
1829
}
1830

    
1831
function auth_get_authserver($name) {
1832
	global $config;
1833

    
1834
	if (is_array($config['system']['authserver'])) {
1835
		foreach ($config['system']['authserver'] as $authcfg) {
1836
			if ($authcfg['name'] == $name) {
1837
				return $authcfg;
1838
			}
1839
		}
1840
	}
1841
	if ($name == "Local Database") {
1842
		return array("name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1843
	}
1844
}
1845

    
1846
function auth_get_authserver_list() {
1847
	global $config;
1848

    
1849
	$list = array();
1850

    
1851
	if (is_array($config['system']['authserver'])) {
1852
		foreach ($config['system']['authserver'] as $authcfg) {
1853
			/* Add support for disabled entries? */
1854
			$list[$authcfg['name']] = $authcfg;
1855
		}
1856
	}
1857

    
1858
	$list["Local Database"] = array("name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1859
	return $list;
1860
}
1861

    
1862
function getUserGroups($username, $authcfg, &$attributes = array()) {
1863
	global $config;
1864

    
1865
	$allowed_groups = array();
1866

    
1867
	switch ($authcfg['type']) {
1868
		case 'ldap':
1869
			$allowed_groups = @ldap_get_groups($username, $authcfg);
1870
			break;
1871
		case 'radius':
1872
			$allowed_groups = @radius_get_groups($attributes);
1873
			break;
1874
		default:
1875
			$user = getUserEntry($username);
1876
			$allowed_groups = @local_user_get_groups($user, true);
1877
			break;
1878
	}
1879

    
1880
	$member_groups = array();
1881
	if (is_array($config['system']['group'])) {
1882
		foreach ($config['system']['group'] as $group) {
1883
			if (in_array($group['name'], $allowed_groups)) {
1884
				$member_groups[] = $group['name'];
1885
			}
1886
		}
1887
	}
1888

    
1889
	return $member_groups;
1890
}
1891

    
1892
/*
1893
Possible return values : 
1894
true : authentication worked
1895
false : authentication failed (invalid login/password, not enought permission, etc...)
1896
null : error during authentication process (unable to reach remote server, etc...)
1897
*/
1898
function authenticate_user($username, $password, $authcfg = NULL, &$attributes = array()) {
1899

    
1900
	if (is_array($username) || is_array($password)) {
1901
		return false;
1902
	}
1903

    
1904
	if (!$authcfg) {
1905
		return local_backed($username, $password, $attributes);
1906
	}
1907

    
1908
	$authenticated = false;
1909
	switch ($authcfg['type']) {
1910
		case 'ldap':
1911
			try {
1912
				$authenticated = ldap_backed($username, $password, $authcfg, $attributes);
1913
			} catch (Exception $e) {
1914
				log_error(sprintf(gettext("LDAP authentication error: %s"), $e->getMessage()));
1915
			}
1916
			break;
1917

    
1918
			break;
1919
		case 'radius':
1920
			try {
1921
				$authenticated = radius_backed($username, $password, $authcfg, $attributes);
1922
			} catch (Exception $e) {
1923
				log_error(sprintf(gettext("RADIUS authentication error: %s"), $e->getMessage()));
1924
			}
1925
			break;
1926
		default:
1927
			/* lookup user object by name */
1928
			try {
1929
				$authenticated = local_backed($username, $password, $attributes);
1930
			} catch (Exception $e) {
1931
				log_error(sprintf(gettext("Local authentication error: %s"), $e->getMessage()));
1932
			}
1933
			break;
1934
		}
1935

    
1936
	return $authenticated;
1937
}
1938

    
1939
function session_auth() {
1940
	global $config, $_SESSION, $page;
1941

    
1942
	// Handle HTTPS httponly and secure flags
1943
	$currentCookieParams = session_get_cookie_params();
1944
	session_set_cookie_params(
1945
		$currentCookieParams["lifetime"],
1946
		$currentCookieParams["path"],
1947
		NULL,
1948
		($config['system']['webgui']['protocol'] == "https"),
1949
		true
1950
	);
1951

    
1952
	phpsession_begin();
1953

    
1954
	// Detect protocol change
1955
	if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) {
1956
		phpsession_end();
1957
		return false;
1958
	}
1959

    
1960
	/* Validate incoming login request */
1961
	$attributes = array('nas_identifier' => 'webConfigurator-' . gethostname());
1962
	if (isset($_POST['login']) && !empty($_POST['usernamefld']) && !empty($_POST['passwordfld'])) {
1963
		$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
1964
		$remoteauth = authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg, $attributes);
1965
		if ($remoteauth || authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) {
1966
			// Generate a new id to avoid session fixation
1967
			session_regenerate_id();
1968
			$_SESSION['Logged_In'] = "True";
1969
			$_SESSION['remoteauth'] = $remoteauth;
1970
			if ($remoteauth) {
1971
				if (empty($authcfg['type']) || ($authcfg['type'] == "Local Auth")) {
1972
					$_SESSION['authsource'] = "Local Database";
1973
				} else {
1974
					$_SESSION['authsource'] = strtoupper($authcfg['type']) . "/{$authcfg['name']}";
1975
				}
1976
			} else {
1977
				$_SESSION['authsource'] = 'Local Database Fallback';
1978
			}
1979
			$_SESSION['Username'] = $_POST['usernamefld'];
1980
			$_SESSION['user_radius_attributes'] = $attributes;
1981
			$_SESSION['last_access'] = time();
1982
			$_SESSION['protocol'] = $config['system']['webgui']['protocol'];
1983
			phpsession_end(true);
1984
			if (!isset($config['system']['webgui']['quietlogin'])) {
1985
				log_auth(sprintf(gettext("Successful login for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], get_user_remote_address() . get_user_remote_authsource()));
1986
			}
1987
			if (isset($_POST['postafterlogin'])) {
1988
				return true;
1989
			} else {
1990
				if (empty($page)) {
1991
					$page = "/";
1992
				}
1993
				header("Location: {$page}");
1994
			}
1995
			exit;
1996
		} else {
1997
			/* give the user an error message */
1998
			$_SESSION['Login_Error'] = gettext("Username or Password incorrect");
1999
			log_auth(sprintf(gettext("webConfigurator authentication error for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], get_user_remote_address() . get_user_remote_authsource()));
2000
			if (isAjax()) {
2001
				echo "showajaxmessage('{$_SESSION['Login_Error']}');";
2002
				return;
2003
			}
2004
		}
2005
	}
2006

    
2007
	/* Show login page if they aren't logged in */
2008
	if (empty($_SESSION['Logged_In'])) {
2009
		phpsession_end(true);
2010
		return false;
2011
	}
2012

    
2013
	/* If session timeout isn't set, we don't mark sessions stale */
2014
	if (!isset($config['system']['webgui']['session_timeout'])) {
2015
		/* Default to 4 hour timeout if one is not set */
2016
		if ($_SESSION['last_access'] < (time() - 14400)) {
2017
			$_POST['logout'] = true;
2018
			$_SESSION['Logout'] = true;
2019
		} else {
2020
			$_SESSION['last_access'] = time();
2021
		}
2022
	} else if (intval($config['system']['webgui']['session_timeout']) == 0) {
2023
		/* only update if it wasn't ajax */
2024
		if (!isAjax()) {
2025
			$_SESSION['last_access'] = time();
2026
		}
2027
	} else {
2028
		/* Check for stale session */
2029
		if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
2030
			$_POST['logout'] = true;
2031
			$_SESSION['Logout'] = true;
2032
		} else {
2033
			/* only update if it wasn't ajax */
2034
			if (!isAjax()) {
2035
				$_SESSION['last_access'] = time();
2036
			}
2037
		}
2038
	}
2039

    
2040
	/* user hit the logout button */
2041
	if (isset($_POST['logout'])) {
2042

    
2043
		if ($_SESSION['Logout']) {
2044
			log_error(sprintf(gettext("Session timed out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], get_user_remote_address() . get_user_remote_authsource()));
2045
		} else {
2046
			log_error(sprintf(gettext("User logged out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], get_user_remote_address() . get_user_remote_authsource()));
2047
		}
2048

    
2049
		/* wipe out $_SESSION */
2050
		$_SESSION = array();
2051

    
2052
		if (isset($_COOKIE[session_name()])) {
2053
			setcookie(session_name(), '', time()-42000, '/');
2054
		}
2055

    
2056
		/* and destroy it */
2057
		phpsession_destroy();
2058

    
2059
		$scriptName = explode("/", $_SERVER["SCRIPT_FILENAME"]);
2060
		$scriptElms = count($scriptName);
2061
		$scriptName = $scriptName[$scriptElms-1];
2062

    
2063
		if (isAjax()) {
2064
			return false;
2065
		}
2066

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

    
2070
		return false;
2071
	}
2072

    
2073
	/*
2074
	 * this is for debugging purpose if you do not want to use Ajax
2075
	 * to submit a HTML form. It basically disables the observation
2076
	 * of the submit event and hence does not trigger Ajax.
2077
	 */
2078
	if ($_REQUEST['disable_ajax']) {
2079
		$_SESSION['NO_AJAX'] = "True";
2080
	}
2081

    
2082
	/*
2083
	 * Same to re-enable Ajax.
2084
	 */
2085
	if ($_REQUEST['enable_ajax']) {
2086
		unset($_SESSION['NO_AJAX']);
2087
	}
2088
	phpsession_end(true);
2089
	return true;
2090
}
2091

    
2092
function print_credit() {
2093
	global $g;
2094

    
2095
	return  '<a target="_blank" href="https://pfsense.org">' . $g["product_name"] . '</a>' .
2096
			gettext(' is developed and maintained by ') .
2097
			'<a target="_blank" href="https://netgate.com">Netgate. </a>' . ' &copy; ESF ' . $g["product_copyright_years"] .
2098
			'<a target="_blank" href="https://pfsense.org/license">' .
2099
			gettext(' View license.') . '</a>';
2100
}
2101
function get_user_remote_address() {
2102
	$remote_address = $_SERVER['REMOTE_ADDR'];
2103
	if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
2104
		$remote_address .= "[{$_SERVER['HTTP_CLIENT_IP']}]";
2105
	} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
2106
		$remote_address .= "[{$_SERVER['HTTP_X_FORWARDED_FOR']}]";
2107
	}
2108
	return $remote_address;
2109
}
2110
function get_user_remote_authsource() {
2111
	$authsource = "";
2112
	if (!empty($_SESSION['authsource'])) {
2113
		$authsource .= " ({$_SESSION['authsource']})";
2114
	}
2115
	return $authsource;
2116
}
2117
?>
(2-2/59)