Project

General

Profile

Download (62.7 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
	/* Setup CA environment if needed. */
965
	ldap_setup_caenv($ldap, $authcfg);
966

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

    
973
	if ($error == true) {
974
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $authcfg['name']));
975
		return false;
976
	}
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
		putenv('LDAPTLS_REQCERT=never');
988
		return;
989
	} elseif ($authcfg['ldap_caref'] == "global") {
990
		putenv('LDAPTLS_REQCERT=hard');
991
		putenv("LDAPTLS_CACERTDIR=/etc/ssl/");
992
		putenv("LDAPTLS_CACERT=/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
			putenv('LDAPTLS_REQCERT=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
		putenv('LDAPTLS_REQCERT=hard');
1011
		/* XXX: Probably even the hashed link should be created for this? */
1012
		putenv("LDAPTLS_CACERTDIR={$g['varrun_path']}/certs");
1013
		putenv("LDAPTLS_CACERT={$g['varrun_path']}/certs/{$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
	/* Setup CA environment if needed. */
1051
	ldap_setup_caenv($ldap, $authcfg);
1052

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

    
1059
	if ($error == true) {
1060
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1061
		return false;
1062
	}
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
	/* Setup CA environment if needed. */
1139
	ldap_setup_caenv($ldap, $authcfg);
1140

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

    
1147
	if ($error == true) {
1148
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1149
		return $ous;
1150
	}
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
	/* Setup CA environment if needed. */
1284
	ldap_setup_caenv($ldap, $authcfg);
1285

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

    
1292
	if ($error == true) {
1293
		log_error(sprintf(gettext("ERROR! ldap_get_groups() Could not connect to server %s."), $ldapname));
1294
		return $memberof;
1295
	}
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
		$ldapgroupattribute = $authcfg['ldap_attr_member'];
1413
		$ldapextendedqueryenabled = $authcfg['ldap_extended_enabled'];
1414
		$ldapextendedquery = $authcfg['ldap_extended_query'];
1415
		$ldapfilter = "";
1416
		if (!$ldapextendedqueryenabled) {
1417
			$ldapfilter = "({$ldapnameattribute}={$username})";
1418
		} else {
1419
			if (isset($authcfg['ldap_rfc2307'])) {
1420
				$ldapfilter = "({$ldapnameattribute}={$username})";
1421
				$ldapgroupfilter = "(&({$ldapgroupattribute}={$username})({$ldapextendedquery}))";
1422
			} else {
1423
				$ldapfilter = "(&({$ldapnameattribute}={$username})({$ldapextendedquery}))";
1424
			}
1425
		}
1426
		$ldaptype = "";
1427
		$ldapver = $authcfg['ldap_protver'];
1428
		$ldapname = $authcfg['name'];
1429
		$ldapscope = $authcfg['ldap_scope'];
1430
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1431
	} else {
1432
		return null;
1433
	}
1434

    
1435
	/* first check if there is even an LDAP server populated */
1436
	if (!$ldapserver) {
1437
		log_error(gettext("ERROR! could not find details of the LDAP server used for authentication."));
1438
		$attributes['error_message'] =  gettext("Internal error during authentication.");
1439
		return null;
1440
	}
1441

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

    
1445
	/* Make sure we can connect to LDAP */
1446
	$error = false;
1447
	if (!($ldap = ldap_connect($ldapserver))) {
1448
		$error = true;
1449
	}
1450

    
1451
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1452
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1453
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1454
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1455
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1456

    
1457
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1458
		if (!(@ldap_start_tls($ldap))) {
1459
			log_error(sprintf(gettext("ERROR! could not connect to LDAP server %s using STARTTLS."), $ldapname));
1460
			$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1461
			@ldap_close($ldap);
1462
			return null;
1463
		}
1464
	}
1465

    
1466
	if ($error == true) {
1467
		$errormsg = sprintf(gettext("ERROR! Could not connect to server %s."), $ldapname);
1468
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1469
		return null;
1470
	}
1471

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

    
1484
	if ($error == true) {
1485
		@ldap_close($ldap);
1486
		log_error(sprintf(gettext("ERROR! Could not bind to LDAP server %s. Please check the bind credentials."), $ldapname));
1487
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1488
		return null;
1489
	}
1490

    
1491
	/* Get LDAP Authcontainers and split em up. */
1492
	$ldac_splits = explode(";", $ldapauthcont);
1493

    
1494
	/* setup the usercount so we think we haven't found anyone yet */
1495
	$usercount = 0;
1496

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

    
1534
		if (isset($ldapgroupfilter) && !$groupsearch) {
1535
			log_error(sprintf(gettext("Extended group search resulted in error: %s"), ldap_error($ldap)));
1536
			continue;
1537
		}
1538
		if (!$search) {
1539
			log_error(sprintf(gettext("Search resulted in error: %s"), ldap_error($ldap)));
1540
			continue;
1541
		}
1542
		if (isset($groupsearch)) {
1543
			$validgroup = ldap_count_entries($ldap, $groupsearch);
1544
			if ($debug) {
1545
				log_auth(sprintf(gettext("LDAP group search: %s results."), $validgroup));
1546
			}
1547
		}
1548
		$info = ldap_get_entries($ldap, $search);
1549
		$matches = $info['count'];
1550
		if ($matches == 1) {
1551
			$userdn = $_SESSION['ldapdn'] = $info[0]['dn'];
1552
			$_SESSION['ldapou'] = $ldac_split[$i];
1553
			$_SESSION['ldapon'] = "true";
1554
			$usercount = 1;
1555
			break;
1556
		}
1557
	}
1558

    
1559
	if ($usercount != 1) {
1560
		@ldap_unbind($ldap);
1561
		if ($debug) {
1562
			if ($usercount === 0) {
1563
				log_error(sprintf(gettext("ERROR! LDAP search failed, no user matching %s was found."), $username));
1564
			} else {
1565
				log_error(sprintf(gettext("ERROR! LDAP search failed, multiple users matching %s were found."), $username));
1566
			}
1567
		}
1568
		$attributes['error_message'] = gettext("Invalid login specified.");
1569
		return false;
1570
	}
1571

    
1572
	/* Now lets bind as the user we found */
1573
	$passwd = isset($authcfg['ldap_utf8']) ? utf8_encode($passwd) : $passwd;
1574
	if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
1575
		if ($debug) {
1576
			log_error(sprintf(gettext('ERROR! Could not login to server %1$s as user %2$s: %3$s'), $ldapname, $username, ldap_error($ldap)));
1577
		}
1578
		@ldap_unbind($ldap);
1579
		return false;
1580
	}
1581

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

    
1587
	if ($debug && isset($ldapgroupfilter) && $validgroup < 1) {
1588
		log_auth(sprintf(gettext('Logged in successfully as %1$s but did not match any field in extended query.'), $username));
1589
	}
1590

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

    
1594
	if (isset($ldapgroupfilter) && $validgroup < 1) {
1595
		return false;
1596
	}
1597

    
1598
	return true;
1599
}
1600

    
1601
function radius_backed($username, $password, $authcfg, &$attributes = array()) {
1602
	global $debug, $config;
1603
	$ret = false;
1604

    
1605
	require_once("Auth/RADIUS.php");
1606
	require_once("Crypt/CHAP.php");
1607

    
1608
	if ($authcfg) {
1609
		$radiusservers = array();
1610
		$radiusservers[0]['ipaddr'] = $authcfg['host'];
1611
		$radiusservers[0]['port'] = $authcfg['radius_auth_port'];
1612
		$radiusservers[0]['sharedsecret'] = $authcfg['radius_secret'];
1613
		$radiusservers[0]['timeout'] = $authcfg['radius_timeout'];
1614
		if(isset($authcfg['radius_protocol'])) {
1615
			$radius_protocol = $authcfg['radius_protocol'];
1616
		} else {
1617
			$radius_protocol = 'PAP';
1618
		}
1619
	} else {
1620
		log_error(gettext("ERROR! could not find details of the RADIUS server used for authentication."));
1621
		$attributes['error_message'] =  gettext("Internal error during authentication.");
1622
		return null;
1623
	}
1624

    
1625
	// Create our instance
1626
	$classname = 'Auth_RADIUS_' . $radius_protocol;
1627
	$rauth = new $classname($username, $password);
1628

    
1629
	/* Add new servers to our instance */
1630
	foreach ($radiusservers as $radsrv) {
1631
		$timeout = (is_numeric($radsrv['timeout'])) ? $radsrv['timeout'] : 5;
1632
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret'], $timeout);
1633
	}
1634

    
1635
	// Construct data package
1636
	$rauth->username = $username;
1637
	switch ($radius_protocol) {
1638
		case 'CHAP_MD5':
1639
		case 'MSCHAPv1':
1640
			$classname = $radius_protocol == 'MSCHAPv1' ? 'Crypt_CHAP_MSv1' : 'Crypt_CHAP_MD5';
1641
			$crpt = new $classname;
1642
			$crpt->username = $username;
1643
			$crpt->password = $password;
1644
			$rauth->challenge = $crpt->challenge;
1645
			$rauth->chapid = $crpt->chapid;
1646
			$rauth->response = $crpt->challengeResponse();
1647
			$rauth->flags = 1;
1648
			break;
1649

    
1650
		case 'MSCHAPv2':
1651
			$crpt = new Crypt_CHAP_MSv2;
1652
			$crpt->username = $username;
1653
			$crpt->password = $password;
1654
			$rauth->challenge = $crpt->authChallenge;
1655
			$rauth->peerChallenge = $crpt->peerChallenge;
1656
			$rauth->chapid = $crpt->chapid;
1657
			$rauth->response = $crpt->challengeResponse();
1658
			break;
1659

    
1660
		default:
1661
			$rauth->password = $password;
1662
			break;
1663
	}
1664

    
1665
	if (PEAR::isError($rauth->start())) {
1666
		$ret = null;
1667
		log_error(sprintf(gettext("Error during RADIUS authentication : %s"), $rauth->getError()));
1668
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1669
	} else {
1670
		$nasid = $attributes['nas_identifier'];
1671
		$nasip = $authcfg['radius_nasip_attribute'];
1672
		if (empty($nasid)) {
1673
			$nasid = gethostname(); //If no RADIUS NAS-Identifier is given : we use pfsense's hostname as NAS-Identifier
1674
		}
1675
		if (!is_ipaddr($nasip)) {
1676
			$nasip = get_interface_ip($nasip);
1677

    
1678
			if (!is_ipaddr($nasip)) {
1679
				$nasip = get_interface_ip();//We use wan interface IP as fallback for NAS-IP-Address
1680
			}
1681
		}
1682
		$nasmac = get_interface_mac(find_ip_interface($nasip));
1683

    
1684
		$rauth->putAttribute(RADIUS_NAS_IP_ADDRESS, $nasip, "addr");
1685
		$rauth->putAttribute(RADIUS_NAS_IDENTIFIER, $nasid);
1686

    
1687
		if(!empty($attributes['calling_station_id'])) {
1688
			$rauth->putAttribute(RADIUS_CALLING_STATION_ID, $attributes['calling_station_id']);
1689
		}
1690
		// Carefully check that interface has a MAC address
1691
		if(!empty($nasmac)) {
1692
			$nasmac = mac_format($nasmac);
1693
			$rauth->putAttribute(RADIUS_CALLED_STATION_ID, $nasmac.':'.gethostname());
1694
		}
1695
		if(!empty($attributes['nas_port_type'])) {
1696
			$rauth->putAttribute(RADIUS_NAS_PORT_TYPE, $attributes['nas_port_type']);
1697
		}
1698
		if(!empty($attributes['nas_port'])) {
1699
			$rauth->putAttribute(RADIUS_NAS_PORT, intval($attributes['nas_port']), 'integer');
1700
		}
1701
		if(!empty($attributes['framed_ip']) && is_ipaddr($attributes['framed_ip'])) {
1702
			$rauth->putAttribute(RADIUS_FRAMED_IP_ADDRESS, $attributes['framed_ip'], "addr");
1703
		}
1704
	}
1705

    
1706
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1707

    
1708
	/* Send request */
1709
	$result = $rauth->send();
1710
	if (PEAR::isError($result)) {
1711
		log_error(sprintf(gettext("Error during RADIUS authentication : %s"), $rauth->getError()));
1712
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1713
		$ret = null;
1714
	} else if ($result === true) {
1715
		$ret = true;
1716
	} else {
1717
		$ret = false;
1718
	}
1719

    
1720

    
1721
	// Get attributes, even if auth failed.
1722
	if ($rauth->getAttributes()) {
1723
	$attributes = array_merge($attributes,$rauth->listAttributes());
1724

    
1725
	// We convert the session_terminate_time to unixtimestamp if its set before returning the whole array to our caller
1726
	if (!empty($attributes['session_terminate_time'])) {
1727
			$stt = &$attributes['session_terminate_time'];
1728
			$stt = strtotime(preg_replace("/\+(\d+):(\d+)$/", " +\${1}\${2}", preg_replace("/(\d+)T(\d+)/", "\${1} \${2}",$stt)));
1729
		}
1730
	}
1731

    
1732
	// close OO RADIUS_AUTHENTICATION
1733
	$rauth->close();
1734

    
1735
	return $ret;
1736
}
1737

    
1738
/*
1739
	$attributes must contain a "class" key containing the groups and local
1740
	groups must exist to match.
1741
*/
1742
function radius_get_groups($attributes) {
1743
	$groups = array();
1744
	if (!empty($attributes) && is_array($attributes) && (!empty($attributes['class']) || !empty($attributes['class_int']))) {
1745
		/* Some RADIUS servers return multiple class attributes, so check them all. */
1746
		$groups = array();
1747
		if (!empty($attributes['class']) && is_array($attributes['class'])) {
1748
			foreach ($attributes['class'] as $class) {
1749
				$groups = array_unique(array_merge($groups, explode(";", $class)));
1750
			}
1751
		}
1752

    
1753
		foreach ($groups as & $grp) {
1754
			$grp = trim($grp);
1755
			if (strtolower(substr($grp, 0, 3)) == "ou=") {
1756
				$grp = substr($grp, 3);
1757
			}
1758
		}
1759
	}
1760
	return $groups;
1761
}
1762

    
1763
function get_user_expiration_date($username) {
1764
	$user = getUserEntry($username);
1765
	if ($user['expires']) {
1766
		return $user['expires'];
1767
	}
1768
}
1769

    
1770
function is_account_expired($username) {
1771
	$expirydate = get_user_expiration_date($username);
1772
	if ($expirydate) {
1773
		if (strtotime("-1 day") > strtotime(date("m/d/Y", strtotime($expirydate)))) {
1774
			return true;
1775
		}
1776
	}
1777

    
1778
	return false;
1779
}
1780

    
1781
function is_account_disabled($username) {
1782
	$user = getUserEntry($username);
1783
	if (isset($user['disabled'])) {
1784
		return true;
1785
	}
1786

    
1787
	return false;
1788
}
1789

    
1790
function get_user_settings($username) {
1791
	global $config;
1792
	$settings = array();
1793
	$settings['widgets'] = $config['widgets'];
1794
	$settings['webgui']['dashboardcolumns'] = $config['system']['webgui']['dashboardcolumns'];
1795
	$settings['webgui']['webguihostnamemenu'] = $config['system']['webgui']['webguihostnamemenu'];
1796
	$settings['webgui']['webguicss'] = $config['system']['webgui']['webguicss'];
1797
	$settings['webgui']['logincss'] = $config['system']['webgui']['logincss'];
1798
	$settings['webgui']['interfacessort'] = isset($config['system']['webgui']['interfacessort']);
1799
	$settings['webgui']['dashboardavailablewidgetspanel'] = isset($config['system']['webgui']['dashboardavailablewidgetspanel']);
1800
	$settings['webgui']['webguifixedmenu'] = isset($config['system']['webgui']['webguifixedmenu']);
1801
	$settings['webgui']['webguileftcolumnhyper'] = isset($config['system']['webgui']['webguileftcolumnhyper']);
1802
	$settings['webgui']['disablealiaspopupdetail'] = isset($config['system']['webgui']['disablealiaspopupdetail']);
1803
	$settings['webgui']['systemlogsfilterpanel'] = isset($config['system']['webgui']['systemlogsfilterpanel']);
1804
	$settings['webgui']['systemlogsmanagelogpanel'] = isset($config['system']['webgui']['systemlogsmanagelogpanel']);
1805
	$settings['webgui']['statusmonitoringsettingspanel'] = isset($config['system']['webgui']['statusmonitoringsettingspanel']);
1806
	$settings['webgui']['pagenamefirst'] = isset($config['system']['webgui']['pagenamefirst']);
1807
	$user = getUserEntry($username);
1808
	if (isset($user['customsettings'])) {
1809
		$settings['customsettings'] = true;
1810
		if (isset($user['widgets'])) {
1811
			// This includes the 'sequence', and any widgetname-config per-widget settings.
1812
			$settings['widgets'] = $user['widgets'];
1813
		}
1814
		if (isset($user['dashboardcolumns'])) {
1815
			$settings['webgui']['dashboardcolumns'] = $user['dashboardcolumns'];
1816
		}
1817
		if (isset($user['webguicss'])) {
1818
			$settings['webgui']['webguicss'] = $user['webguicss'];
1819
		}
1820
		if (isset($user['webguihostnamemenu'])) {
1821
			$settings['webgui']['webguihostnamemenu'] = $user['webguihostnamemenu'];
1822
		}
1823
		$settings['webgui']['interfacessort'] = isset($user['interfacessort']);
1824
		$settings['webgui']['dashboardavailablewidgetspanel'] = isset($user['dashboardavailablewidgetspanel']);
1825
		$settings['webgui']['webguifixedmenu'] = isset($user['webguifixedmenu']);
1826
		$settings['webgui']['webguileftcolumnhyper'] = isset($user['webguileftcolumnhyper']);
1827
		$settings['webgui']['disablealiaspopupdetail'] = isset($user['disablealiaspopupdetail']);
1828
		$settings['webgui']['systemlogsfilterpanel'] = isset($user['systemlogsfilterpanel']);
1829
		$settings['webgui']['systemlogsmanagelogpanel'] = isset($user['systemlogsmanagelogpanel']);
1830
		$settings['webgui']['statusmonitoringsettingspanel'] = isset($user['statusmonitoringsettingspanel']);
1831
		$settings['webgui']['pagenamefirst'] = isset($user['pagenamefirst']);
1832
	} else {
1833
		$settings['customsettings'] = false;
1834
	}
1835

    
1836
	if ($settings['webgui']['dashboardcolumns'] < 1) {
1837
		$settings['webgui']['dashboardcolumns'] = 2;
1838
	}
1839

    
1840
	return $settings;
1841
}
1842

    
1843
function save_widget_settings($username, $settings, $message = "") {
1844
	global $config, $userindex;
1845
	$user = getUserEntry($username);
1846

    
1847
	if (strlen($message) > 0) {
1848
		$msgout = $message;
1849
	} else {
1850
		$msgout = gettext("Widget configuration has been changed.");
1851
	}
1852

    
1853
	if (isset($user['customsettings'])) {
1854
		$config['system']['user'][$userindex[$username]]['widgets'] = $settings;
1855
		write_config($msgout . " " . sprintf(gettext("(User %s)"), $username));
1856
	} else {
1857
		$config['widgets'] = $settings;
1858
		write_config($msgout);
1859
	}
1860
}
1861

    
1862
function auth_get_authserver($name) {
1863
	global $config;
1864

    
1865
	if (is_array($config['system']['authserver'])) {
1866
		foreach ($config['system']['authserver'] as $authcfg) {
1867
			if ($authcfg['name'] == $name) {
1868
				return $authcfg;
1869
			}
1870
		}
1871
	}
1872
	if ($name == "Local Database") {
1873
		return array("name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1874
	}
1875
}
1876

    
1877
function auth_get_authserver_list() {
1878
	global $config;
1879

    
1880
	$list = array();
1881

    
1882
	if (is_array($config['system']['authserver'])) {
1883
		foreach ($config['system']['authserver'] as $authcfg) {
1884
			/* Add support for disabled entries? */
1885
			$list[$authcfg['name']] = $authcfg;
1886
		}
1887
	}
1888

    
1889
	$list["Local Database"] = array("name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1890
	return $list;
1891
}
1892

    
1893
function getUserGroups($username, $authcfg, &$attributes = array()) {
1894
	global $config;
1895

    
1896
	$allowed_groups = array();
1897

    
1898
	switch ($authcfg['type']) {
1899
		case 'ldap':
1900
			$allowed_groups = @ldap_get_groups($username, $authcfg);
1901
			break;
1902
		case 'radius':
1903
			$allowed_groups = @radius_get_groups($attributes);
1904
			break;
1905
		default:
1906
			$user = getUserEntry($username);
1907
			$allowed_groups = @local_user_get_groups($user, true);
1908
			break;
1909
	}
1910

    
1911
	$member_groups = array();
1912
	if (is_array($config['system']['group'])) {
1913
		foreach ($config['system']['group'] as $group) {
1914
			if (in_array($group['name'], $allowed_groups)) {
1915
				$member_groups[] = $group['name'];
1916
			}
1917
		}
1918
	}
1919

    
1920
	return $member_groups;
1921
}
1922

    
1923
/*
1924
Possible return values :
1925
true : authentication worked
1926
false : authentication failed (invalid login/password, not enough permission, etc...)
1927
null : error during authentication process (unable to reach remote server, etc...)
1928
*/
1929
function authenticate_user($username, $password, $authcfg = NULL, &$attributes = array()) {
1930

    
1931
	if (is_array($username) || is_array($password)) {
1932
		return false;
1933
	}
1934

    
1935
	if (!$authcfg) {
1936
		return local_backed($username, $password, $attributes);
1937
	}
1938

    
1939
	$authenticated = false;
1940
	switch ($authcfg['type']) {
1941
		case 'ldap':
1942
			try {
1943
				$authenticated = ldap_backed($username, $password, $authcfg, $attributes);
1944
			} catch (Exception $e) {
1945
				log_error(sprintf(gettext("LDAP authentication error: %s"), $e->getMessage()));
1946
			}
1947
			break;
1948

    
1949
			break;
1950
		case 'radius':
1951
			try {
1952
				$authenticated = radius_backed($username, $password, $authcfg, $attributes);
1953
			} catch (Exception $e) {
1954
				log_error(sprintf(gettext("RADIUS authentication error: %s"), $e->getMessage()));
1955
			}
1956
			break;
1957
		default:
1958
			/* lookup user object by name */
1959
			try {
1960
				$authenticated = local_backed($username, $password, $attributes);
1961
			} catch (Exception $e) {
1962
				log_error(sprintf(gettext("Local authentication error: %s"), $e->getMessage()));
1963
			}
1964
			break;
1965
		}
1966

    
1967
	return $authenticated;
1968
}
1969

    
1970
function session_auth() {
1971
	global $config, $_SESSION, $page;
1972

    
1973
	// Handle HTTPS httponly and secure flags
1974
	$currentCookieParams = session_get_cookie_params();
1975
	session_set_cookie_params(
1976
		$currentCookieParams["lifetime"],
1977
		$currentCookieParams["path"],
1978
		NULL,
1979
		($config['system']['webgui']['protocol'] == "https"),
1980
		true
1981
	);
1982

    
1983
	phpsession_begin();
1984

    
1985
	// Detect protocol change
1986
	if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) {
1987
		phpsession_end();
1988
		return false;
1989
	}
1990

    
1991
	/* Validate incoming login request */
1992
	$attributes = array('nas_identifier' => 'webConfigurator-' . gethostname());
1993
	if (isset($_POST['login']) && !empty($_POST['usernamefld']) && !empty($_POST['passwordfld'])) {
1994
		$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
1995
		$remoteauth = authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg, $attributes);
1996
		if ($remoteauth || authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) {
1997
			// Generate a new id to avoid session fixation
1998
			session_regenerate_id();
1999
			$_SESSION['Logged_In'] = "True";
2000
			$_SESSION['remoteauth'] = $remoteauth;
2001
			if ($remoteauth) {
2002
				if (empty($authcfg['type']) || ($authcfg['type'] == "Local Auth")) {
2003
					$_SESSION['authsource'] = "Local Database";
2004
				} else {
2005
					$_SESSION['authsource'] = strtoupper($authcfg['type']) . "/{$authcfg['name']}";
2006
				}
2007
			} else {
2008
				$_SESSION['authsource'] = 'Local Database Fallback';
2009
			}
2010
			$_SESSION['Username'] = $_POST['usernamefld'];
2011
			$_SESSION['user_radius_attributes'] = $attributes;
2012
			$_SESSION['last_access'] = time();
2013
			$_SESSION['protocol'] = $config['system']['webgui']['protocol'];
2014
			phpsession_end(true);
2015
			if (!isset($config['system']['webgui']['quietlogin'])) {
2016
				log_auth(sprintf(gettext("Successful login for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], get_user_remote_address() . get_user_remote_authsource()));
2017
			}
2018
			if (isset($_POST['postafterlogin'])) {
2019
				return true;
2020
			} else {
2021
				if (empty($page)) {
2022
					$page = "/";
2023
				}
2024
				header("Location: {$page}");
2025
			}
2026
			exit;
2027
		} else {
2028
			/* give the user an error message */
2029
			$_SESSION['Login_Error'] = gettext("Username or Password incorrect");
2030
			log_auth(sprintf(gettext("webConfigurator authentication error for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], get_user_remote_address() . get_user_remote_authsource()));
2031
			if (isAjax()) {
2032
				echo "showajaxmessage('{$_SESSION['Login_Error']}');";
2033
				return;
2034
			}
2035
		}
2036
	}
2037

    
2038
	/* Show login page if they aren't logged in */
2039
	if (empty($_SESSION['Logged_In'])) {
2040
		phpsession_end(true);
2041
		return false;
2042
	}
2043

    
2044
	/* If session timeout isn't set, we don't mark sessions stale */
2045
	if (!isset($config['system']['webgui']['session_timeout'])) {
2046
		/* Default to 4 hour timeout if one is not set */
2047
		if ($_SESSION['last_access'] < (time() - 14400)) {
2048
			$_POST['logout'] = true;
2049
			$_SESSION['Logout'] = true;
2050
		} else {
2051
			$_SESSION['last_access'] = time();
2052
		}
2053
	} else if (intval($config['system']['webgui']['session_timeout']) == 0) {
2054
		/* only update if it wasn't ajax */
2055
		if (!isAjax()) {
2056
			$_SESSION['last_access'] = time();
2057
		}
2058
	} else {
2059
		/* Check for stale session */
2060
		if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
2061
			$_POST['logout'] = true;
2062
			$_SESSION['Logout'] = true;
2063
		} else {
2064
			/* only update if it wasn't ajax */
2065
			if (!isAjax()) {
2066
				$_SESSION['last_access'] = time();
2067
			}
2068
		}
2069
	}
2070

    
2071
	/* user hit the logout button */
2072
	if (isset($_POST['logout'])) {
2073

    
2074
		if ($_SESSION['Logout']) {
2075
			log_error(sprintf(gettext("Session timed out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], get_user_remote_address() . get_user_remote_authsource()));
2076
		} else {
2077
			log_error(sprintf(gettext("User logged out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], get_user_remote_address() . get_user_remote_authsource()));
2078
		}
2079

    
2080
		/* wipe out $_SESSION */
2081
		$_SESSION = array();
2082

    
2083
		if (isset($_COOKIE[session_name()])) {
2084
			setcookie(session_name(), '', time()-42000, '/');
2085
		}
2086

    
2087
		/* and destroy it */
2088
		phpsession_destroy();
2089

    
2090
		$scriptName = explode("/", $_SERVER["SCRIPT_FILENAME"]);
2091
		$scriptElms = count($scriptName);
2092
		$scriptName = $scriptName[$scriptElms-1];
2093

    
2094
		if (isAjax()) {
2095
			return false;
2096
		}
2097

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

    
2101
		return false;
2102
	}
2103

    
2104
	/*
2105
	 * this is for debugging purpose if you do not want to use Ajax
2106
	 * to submit a HTML form. It basically disables the observation
2107
	 * of the submit event and hence does not trigger Ajax.
2108
	 */
2109
	if ($_REQUEST['disable_ajax']) {
2110
		$_SESSION['NO_AJAX'] = "True";
2111
	}
2112

    
2113
	/*
2114
	 * Same to re-enable Ajax.
2115
	 */
2116
	if ($_REQUEST['enable_ajax']) {
2117
		unset($_SESSION['NO_AJAX']);
2118
	}
2119
	phpsession_end(true);
2120
	return true;
2121
}
2122

    
2123
function print_credit() {
2124
	global $g;
2125

    
2126
	return  '<a target="_blank" href="https://pfsense.org">' . $g["product_name"] . '</a>' .
2127
			gettext(' is developed and maintained by ') .
2128
			'<a target="_blank" href="https://netgate.com">Netgate. </a>' . ' &copy; ESF ' . $g["product_copyright_years"] .
2129
			'<a target="_blank" href="https://pfsense.org/license">' .
2130
			gettext(' View license.') . '</a>';
2131
}
2132
function get_user_remote_address() {
2133
	$remote_address = $_SERVER['REMOTE_ADDR'];
2134
	if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
2135
		$remote_address .= "[{$_SERVER['HTTP_CLIENT_IP']}]";
2136
	} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
2137
		$remote_address .= "[{$_SERVER['HTTP_X_FORWARDED_FOR']}]";
2138
	}
2139
	return $remote_address;
2140
}
2141
function get_user_remote_authsource() {
2142
	$authsource = "";
2143
	if (!empty($_SESSION['authsource'])) {
2144
		$authsource .= " ({$_SESSION['authsource']})";
2145
	}
2146
	return $authsource;
2147
}
2148
?>
(2-2/60)