Project

General

Profile

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

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

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

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

    
43
	/* Fetch the contents of the lockout table. */
44
	exec("/sbin/pfctl -t 'webConfiguratorlockout' -T show", $entries);
45

    
46
	/* If the client is in the lockout table, print an error, kill states, and exit */
47
	if (in_array($_SERVER['REMOTE_ADDR'], array_map('trim', $entries))) {
48
		if (!security_checks_disabled()) {
49
			/* They may never see the error since the connection will be cut off, but try to be nice anyhow. */
50
			display_error_form("501", gettext("Access Denied<br/><br/>Access attempt from a temporarily locked out client address.<br /><br />Try accessing the firewall again after the lockout expires."));
51
			/* If they are locked out, they shouldn't have a state. Disconnect their connections. */
52
			$retval = pfSense_kill_states($_SERVER['REMOTE_ADDR']);
53
			if (is_ipaddrv4($_SERVER['REMOTE_ADDR'])) {
54
				$retval = pfSense_kill_states("0.0.0.0/0", $_SERVER['REMOTE_ADDR']);
55
			} elseif (is_ipaddrv6($_SERVER['REMOTE_ADDR'])) {
56
				$retval = pfSense_kill_states("::", $_SERVER['REMOTE_ADDR']);
57
			}
58
			exit;
59
		}
60
		$security_passed = false;
61
	}
62
}
63

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

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

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

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

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

    
119
	if ($found_host == false) {
120
		if (!security_checks_disabled()) {
121
			display_error_form("501", gettext("Potential DNS Rebind attack detected, see http://en.wikipedia.org/wiki/DNS_rebinding<br />Try accessing the router by IP address instead of by hostname."));
122
			exit;
123
		}
124
		$security_passed = false;
125
	}
126
}
127

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

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

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

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

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

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

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

    
249
$groupindex = index_groups();
250
$userindex = index_users();
251

    
252
function index_groups() {
253
	global $g, $debug, $config, $groupindex;
254

    
255
	$groupindex = array();
256

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

    
265
	return ($groupindex);
266
}
267

    
268
function index_users() {
269
	global $g, $debug, $config;
270

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

    
279
	return ($userindex);
280
}
281

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

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

    
295
function & getUserEntryByUID($uid) {
296
	global $debug, $config;
297

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

    
306
	return false;
307
}
308

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

    
316
function & getGroupEntryByGID($gid) {
317
	global $debug, $config;
318

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

    
327
	return false;
328
}
329

    
330
function get_user_privileges(& $user) {
331
	global $config, $_SESSION;
332

    
333
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
334
	$allowed_groups = array();
335

    
336
	$privs = $user['priv'];
337
	if (!is_array($privs)) {
338
		$privs = array();
339
	}
340

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

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

    
368
	if (empty($allowed_groups)) {
369
		$allowed_groups = local_user_get_groups($user, true);
370
	}
371

    
372
	if (!is_array($allowed_groups)) {
373
		$allowed_groups = array('all');
374
	} else {
375
		$allowed_groups[] = 'all';
376
	}
377

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

    
385
	return $privs;
386
}
387

    
388
function userHasPrivilege($userent, $privid = false) {
389

    
390
	if (!$privid || !is_array($userent)) {
391
		return false;
392
	}
393

    
394
	$privs = get_user_privileges($userent);
395

    
396
	if (!is_array($privs)) {
397
		return false;
398
	}
399

    
400
	if (!in_array($privid, $privs)) {
401
		return false;
402
	}
403

    
404
	return true;
405
}
406

    
407
function local_backed($username, $passwd) {
408

    
409
	$user = getUserEntry($username);
410
	if (!$user) {
411
		return false;
412
	}
413

    
414
	if (is_account_disabled($username) || is_account_expired($username)) {
415
		return false;
416
	}
417

    
418
	if ($user['bcrypt-hash']) {
419
		if (password_verify($passwd, $user['bcrypt-hash'])) {
420
			return true;
421
		}
422
	}
423

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

    
431
	if ($user['md5-hash']) {
432
		if (md5($passwd) == $user['md5-hash']) {
433
			return true;
434
		}
435
	}
436

    
437
	return false;
438
}
439

    
440
function local_sync_accounts($u2add, $u2del, $g2add, $g2del) {
441
	global $config, $debug;
442

    
443
	if (empty($u2add) && empty($u2del) && empty($g2add) && empty($g2del)) {
444
		/* Nothing to be done here */
445
		return;
446
	}
447

    
448
	foreach($u2del as $user) {
449
		if ($user['uid'] < 2000 || $user['uid'] > 65000) {
450
			continue;
451
		}
452

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

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

    
477
	foreach($g2del as $group) {
478
		if ($group['gid'] < 1999 || $group['gid'] > 65000) {
479
			continue;
480
		}
481

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

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

    
499
	foreach ($u2add as $user) {
500
		log_error("Adding user: {$user['name']}");
501
		$config['system']['user'][] = $user;
502
	}
503

    
504
	foreach ($g2add as $group) {
505
		log_error("Adding group: {$group['name']}");
506
		$config['system']['group'][] = $group;
507
	}
508

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

    
517
	write_config("Sync'd users and groups via XMLRPC");
518

    
519
	/* make sure the all group exists */
520
	$allgrp = getGroupEntryByGID(1998);
521
	local_group_set($allgrp, true);
522

    
523
	foreach ($u2add as $user) {
524
		local_user_set($user);
525
	}
526

    
527
	foreach ($g2add as $group) {
528
		local_group_set($group);
529
	}
530
}
531

    
532
function local_reset_accounts() {
533
	global $debug, $config;
534

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

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

    
589
	/* make sure the all group exists */
590
	$allgrp = getGroupEntryByGID(1998);
591
	local_group_set($allgrp, true);
592

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

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

    
608
function local_user_set(& $user) {
609
	global $g, $debug;
610

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

    
616

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

    
624
	// Ensure $home_base exists and is writable
625
	if (!is_dir($home_base)) {
626
		mkdir($home_base, 0755);
627
	}
628

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

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

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

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

    
677
	$skel_dir = '/etc/skel';
678

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

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

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

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

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

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

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

    
739
}
740

    
741
function local_user_del($user) {
742
	global $debug;
743

    
744
	/* remove all memberships */
745
	local_user_set_groups($user);
746

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

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

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

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

    
766
	if ($debug) {
767
		log_error(sprintf(gettext("Running: %s"), $cmd));
768
	}
769
	mwexec($cmd);
770

    
771
	/* Delete user from groups needs a call to write_config() */
772
	local_group_del_user($user);
773
}
774

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

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

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

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

    
799
	if ($all) {
800
		$groups[] = "all";
801
	}
802

    
803
	sort($groups);
804

    
805
	return $groups;
806

    
807
}
808

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

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

    
816
	$cur_groups = local_user_get_groups($user, true);
817
	$mod_groups = array();
818

    
819
	if (!is_array($new_groups)) {
820
		$new_groups = array();
821
	}
822

    
823
	if (!is_array($cur_groups)) {
824
		$cur_groups = array();
825
	}
826

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

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

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

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

    
869
function local_group_del_user($user) {
870
	global $config;
871

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

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

    
887
function local_group_set($group, $reset = false) {
888
	global $debug;
889

    
890
	$group_name = $group['name'];
891
	$group_gid = $group['gid'];
892
	$group_members = '';
893

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

    
898
	if (empty($group_name)) {
899
		return;
900
	}
901

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

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

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

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

    
925
	mwexec($cmd);
926
}
927

    
928
function local_group_del($group) {
929
	global $debug;
930

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

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

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

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

    
961
	/* Setup CA environment if needed. */
962
	ldap_setup_caenv($authcfg);
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
	return true;
976
}
977

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

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

    
1015
function ldap_test_bind($authcfg) {
1016
	global $debug, $config, $g;
1017

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

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

    
1048
	/* Setup CA environment if needed. */
1049
	ldap_setup_caenv($authcfg);
1050

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

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

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

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

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

    
1088
	@ldap_unbind($ldap);
1089

    
1090
	return true;
1091
}
1092

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

    
1096
	if (!function_exists("ldap_connect")) {
1097
		return;
1098
	}
1099

    
1100
	$ous = array();
1101

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

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

    
1136
	/* Setup CA environment if needed. */
1137
	ldap_setup_caenv($authcfg);
1138

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

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

    
1150
	$ldapfilter = "(|(ou=*)(cn=Users))";
1151

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

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

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

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

    
1186
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
1187
	$info = @ldap_get_entries($ldap, $search);
1188

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

    
1207
	@ldap_unbind($ldap);
1208

    
1209
	return $ous;
1210
}
1211

    
1212
function ldap_get_groups($username, $authcfg) {
1213
	global $debug, $config;
1214

    
1215
	if (!function_exists("ldap_connect")) {
1216
		return;
1217
	}
1218

    
1219
	if (!$username) {
1220
		return false;
1221
	}
1222

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

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

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

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

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

    
1281
	/* Setup CA environment if needed. */
1282
	ldap_setup_caenv($authcfg);
1283

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

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

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

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

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

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

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

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

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

    
1350
	/* Time to close LDAP connection */
1351
	@ldap_unbind($ldap);
1352

    
1353
	$groups = print_r($memberof, true);
1354

    
1355
	//log_error("Returning groups ".$groups." for user $username");
1356

    
1357
	return $memberof;
1358
}
1359

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

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

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

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

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

    
1387
	$username = ldap_escape($username, null, LDAP_ESCAPE_FILTER);
1388

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1565
	return true;
1566
}
1567

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

    
1572
	require_once("Auth/RADIUS.php");
1573
	require_once("Crypt/CHAP.php");
1574

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

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

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

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

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

    
1627
		default:
1628
			$rauth->password = $password;
1629
			break;
1630
	}
1631

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

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

    
1673
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1674

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

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

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

    
1702
	return $ret;
1703
}
1704

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

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

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

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

    
1745
	return false;
1746
}
1747

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

    
1754
	return false;
1755
}
1756

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

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

    
1807
	return $settings;
1808
}
1809

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

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

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

    
1829
function auth_get_authserver($name) {
1830
	global $config;
1831

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

    
1844
function auth_get_authserver_list() {
1845
	global $config;
1846

    
1847
	$list = array();
1848

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

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

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

    
1863
	$allowed_groups = array();
1864

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

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

    
1887
	return $member_groups;
1888
}
1889

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

    
1898
	if (is_array($username) || is_array($password)) {
1899
		return false;
1900
	}
1901

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

    
1906
	$authenticated = false;
1907
	switch ($authcfg['type']) {
1908
		case 'ldap':
1909
			$authenticated = ldap_backed($username, $password, $authcfg, $attributes);
1910
			break;
1911
		case 'radius':
1912
			$authenticated = radius_backed($username, $password, $authcfg, $attributes);
1913
			break;
1914
		default:
1915
			/* lookup user object by name */
1916
			$authenticated = local_backed($username, $password, $attributes);
1917
			break;
1918
		}
1919

    
1920
	return $authenticated;
1921
}
1922

    
1923
function session_auth() {
1924
	global $config, $_SESSION, $page;
1925

    
1926
	// Handle HTTPS httponly and secure flags
1927
	$currentCookieParams = session_get_cookie_params();
1928
	session_set_cookie_params(
1929
		$currentCookieParams["lifetime"],
1930
		$currentCookieParams["path"],
1931
		NULL,
1932
		($config['system']['webgui']['protocol'] == "https"),
1933
		true
1934
	);
1935

    
1936
	phpsession_begin();
1937

    
1938
	// Detect protocol change
1939
	if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) {
1940
		phpsession_end();
1941
		return false;
1942
	}
1943

    
1944
	/* Validate incoming login request */
1945
	$attributes = array();
1946
	if (isset($_POST['login']) && !empty($_POST['usernamefld']) && !empty($_POST['passwordfld'])) {
1947
		$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
1948
		$remoteauth = authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg, $attributes);
1949
		if ($remoteauth || authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) {
1950
			// Generate a new id to avoid session fixation
1951
			session_regenerate_id();
1952
			$_SESSION['Logged_In'] = "True";
1953
			$_SESSION['remoteauth'] = $remoteauth;
1954
			if ($remoteauth) {
1955
				if (empty($authcfg['type']) || ($authcfg['type'] == "Local Auth")) {
1956
					$_SESSION['authsource'] = "Local Database";
1957
				} else {
1958
					$_SESSION['authsource'] = strtoupper($authcfg['type']) . "/{$authcfg['name']}";
1959
				}
1960
			} else {
1961
				$_SESSION['authsource'] = 'Local Database Fallback';
1962
			}
1963
			$_SESSION['Username'] = $_POST['usernamefld'];
1964
			$_SESSION['user_radius_attributes'] = $attributes;
1965
			$_SESSION['last_access'] = time();
1966
			$_SESSION['protocol'] = $config['system']['webgui']['protocol'];
1967
			phpsession_end(true);
1968
			if (!isset($config['system']['webgui']['quietlogin'])) {
1969
				log_auth(sprintf(gettext("Successful login for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], get_user_remote_address() . get_user_remote_authsource()));
1970
			}
1971
			if (isset($_POST['postafterlogin'])) {
1972
				return true;
1973
			} else {
1974
				if (empty($page)) {
1975
					$page = "/";
1976
				}
1977
				header("Location: {$page}");
1978
			}
1979
			exit;
1980
		} else {
1981
			/* give the user an error message */
1982
			$_SESSION['Login_Error'] = gettext("Username or Password incorrect");
1983
			log_auth(sprintf(gettext("webConfigurator authentication error for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], get_user_remote_address() . get_user_remote_authsource()));
1984
			if (isAjax()) {
1985
				echo "showajaxmessage('{$_SESSION['Login_Error']}');";
1986
				return;
1987
			}
1988
		}
1989
	}
1990

    
1991
	/* Show login page if they aren't logged in */
1992
	if (empty($_SESSION['Logged_In'])) {
1993
		phpsession_end(true);
1994
		return false;
1995
	}
1996

    
1997
	/* If session timeout isn't set, we don't mark sessions stale */
1998
	if (!isset($config['system']['webgui']['session_timeout'])) {
1999
		/* Default to 4 hour timeout if one is not set */
2000
		if ($_SESSION['last_access'] < (time() - 14400)) {
2001
			$_POST['logout'] = true;
2002
			$_SESSION['Logout'] = true;
2003
		} else {
2004
			$_SESSION['last_access'] = time();
2005
		}
2006
	} else if (intval($config['system']['webgui']['session_timeout']) == 0) {
2007
		/* only update if it wasn't ajax */
2008
		if (!isAjax()) {
2009
			$_SESSION['last_access'] = time();
2010
		}
2011
	} else {
2012
		/* Check for stale session */
2013
		if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
2014
			$_POST['logout'] = true;
2015
			$_SESSION['Logout'] = true;
2016
		} else {
2017
			/* only update if it wasn't ajax */
2018
			if (!isAjax()) {
2019
				$_SESSION['last_access'] = time();
2020
			}
2021
		}
2022
	}
2023

    
2024
	/* user hit the logout button */
2025
	if (isset($_POST['logout'])) {
2026

    
2027
		if ($_SESSION['Logout']) {
2028
			log_error(sprintf(gettext("Session timed out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], get_user_remote_address() . get_user_remote_authsource()));
2029
		} else {
2030
			log_error(sprintf(gettext("User logged out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], get_user_remote_address() . get_user_remote_authsource()));
2031
		}
2032

    
2033
		/* wipe out $_SESSION */
2034
		$_SESSION = array();
2035

    
2036
		if (isset($_COOKIE[session_name()])) {
2037
			setcookie(session_name(), '', time()-42000, '/');
2038
		}
2039

    
2040
		/* and destroy it */
2041
		phpsession_destroy();
2042

    
2043
		$scriptName = explode("/", $_SERVER["SCRIPT_FILENAME"]);
2044
		$scriptElms = count($scriptName);
2045
		$scriptName = $scriptName[$scriptElms-1];
2046

    
2047
		if (isAjax()) {
2048
			return false;
2049
		}
2050

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

    
2054
		return false;
2055
	}
2056

    
2057
	/*
2058
	 * this is for debugging purpose if you do not want to use Ajax
2059
	 * to submit a HTML form. It basically disables the observation
2060
	 * of the submit event and hence does not trigger Ajax.
2061
	 */
2062
	if ($_REQUEST['disable_ajax']) {
2063
		$_SESSION['NO_AJAX'] = "True";
2064
	}
2065

    
2066
	/*
2067
	 * Same to re-enable Ajax.
2068
	 */
2069
	if ($_REQUEST['enable_ajax']) {
2070
		unset($_SESSION['NO_AJAX']);
2071
	}
2072
	phpsession_end(true);
2073
	return true;
2074
}
2075

    
2076
function print_credit() {
2077
	global $g;
2078

    
2079
	return  '<a target="_blank" href="https://pfsense.org">' . $g["product_name"] . '</a>' .
2080
			gettext(' is developed and maintained by ') .
2081
			'<a target="_blank" href="https://netgate.com">Netgate. </a>' . ' &copy; ESF ' . $g["product_copyright_years"] .
2082
			'<a target="_blank" href="https://pfsense.org/license">' .
2083
			gettext(' View license.') . '</a>';
2084
}
2085
function get_user_remote_address() {
2086
	$remote_address = $_SERVER['REMOTE_ADDR'];
2087
	if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
2088
		$remote_address .= "[{$_SERVER['HTTP_CLIENT_IP']}]";
2089
	} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
2090
		$remote_address .= "[{$_SERVER['HTTP_X_FORWARDED_FOR']}]";
2091
	}
2092
	return $remote_address;
2093
}
2094
function get_user_remote_authsource() {
2095
	$authsource = "";
2096
	if (!empty($_SESSION['authsource'])) {
2097
		$authsource .= " ({$_SESSION['authsource']})";
2098
	}
2099
	return $authsource;
2100
}
2101
?>
(2-2/60)