Project

General

Profile

Download (59.6 KB) Statistics
| Branch: | Tag: | Revision:
1 55eb9c44 --global
<?php
2 b37b4034 Phil Davis
/*
3 ac24dc24 Renato Botelho
 * auth.inc
4 995df6c3 Stephen Beaver
 *
5 ac24dc24 Renato Botelho
 * 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 b8f91b7c Luiz Souza
 * Copyright (c) 2004-2018 Rubicon Communications, LLC (Netgate)
10 ac24dc24 Renato Botelho
 * All rights reserved.
11 995df6c3 Stephen Beaver
 *
12 b12ea3fb Renato Botelho
 * 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 995df6c3 Stephen Beaver
 *
16 b12ea3fb Renato Botelho
 * http://www.apache.org/licenses/LICENSE-2.0
17 995df6c3 Stephen Beaver
 *
18 b12ea3fb Renato Botelho
 * 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 995df6c3 Stephen Beaver
 */
24 ac24dc24 Renato Botelho
25 55eb9c44 --global
/*
26
 * NOTE : Portions of the mschapv2 support was based on the BSD licensed CHAP.php
27
 * file courtesy of Michael Retterklieber.
28
 */
29 82cd6022 PiBa-NL
include_once('phpsessionmanager.inc');
30 1e0b1727 Phil Davis
if (!$do_not_include_config_gui_inc) {
31 052e65ef Scott Ullrich
	require_once("config.gui.inc");
32 1e0b1727 Phil Davis
}
33 55eb9c44 --global
34 9ae11a62 Scott Ullrich
// Will be changed to false if security checks fail
35
$security_passed = true;
36
37 1180e4f0 Sjon Hortensius
/* If this function doesn't exist, we're being called from Captive Portal or
38 0321fa1b jim-p
   another internal subsystem which does not include authgui.inc */
39 cc9b0f76 jim-p
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 14eab6fb jim-p
if (function_exists("display_error_form") && !isset($config['system']['webgui']['nodnsrebindcheck'])) {
65 0734024c Chris Buechler
	/* DNS ReBinding attack prevention.  https://redmine.pfsense.org/issues/708 */
66 0321fa1b jim-p
	$found_host = false;
67 209620ea Seth Mos
68 4cf79fdd smos
	/* Either a IPv6 address with or without a alternate port */
69 1e0b1727 Phil Davis
	if (strstr($_SERVER['HTTP_HOST'], "]")) {
70 4cf79fdd smos
		$http_host_port = explode("]", $_SERVER['HTTP_HOST']);
71 209620ea Seth Mos
		/* v6 address has more parts, drop the last part */
72 1e0b1727 Phil Davis
		if (count($http_host_port) > 1) {
73 209620ea Seth Mos
			array_pop($http_host_port);
74
			$http_host = str_replace(array("[", "]"), "", implode(":", $http_host_port));
75
		} else {
76 4cf79fdd smos
			$http_host = str_replace(array("[", "]"), "", implode(":", $http_host_port));
77 209620ea Seth Mos
		}
78 7319dc73 jim-p
	} else {
79 4fcab77b smos
		$http_host = explode(":", $_SERVER['HTTP_HOST']);
80
		$http_host = $http_host[0];
81 7319dc73 jim-p
	}
82 1e0b1727 Phil Davis
	if (is_ipaddr($http_host) or $_SERVER['SERVER_ADDR'] == "127.0.0.1" or
83 46bb8a0b Sjon Hortensius
		strcasecmp($http_host, "localhost") == 0 or $_SERVER['SERVER_ADDR'] == "::1") {
84 9ae11a62 Scott Ullrich
		$found_host = true;
85 1e0b1727 Phil Davis
	}
86
	if (strcasecmp($http_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 or
87 46bb8a0b Sjon Hortensius
		strcasecmp($http_host, $config['system']['hostname']) == 0) {
88 d7bf3178 Erik Fonnesbeck
		$found_host = true;
89 1e0b1727 Phil Davis
	}
90 9ae11a62 Scott Ullrich
91 1e0b1727 Phil Davis
	if (is_array($config['dyndnses']['dyndns']) && !$found_host) {
92
		foreach ($config['dyndnses']['dyndns'] as $dyndns) {
93
			if (strcasecmp($dyndns['host'], $http_host) == 0) {
94 0321fa1b jim-p
				$found_host = true;
95 9ae11a62 Scott Ullrich
				break;
96
			}
97 1e0b1727 Phil Davis
		}
98
	}
99 7319dc73 jim-p
100 1e0b1727 Phil Davis
	if (is_array($config['dnsupdates']['dnsupdate']) && !$found_host) {
101
		foreach ($config['dnsupdates']['dnsupdate'] as $rfc2136) {
102
			if (strcasecmp($rfc2136['host'], $http_host) == 0) {
103 fa087612 jim-p
				$found_host = true;
104
				break;
105
			}
106 1e0b1727 Phil Davis
		}
107
	}
108 fa087612 jim-p
109 1e0b1727 Phil Davis
	if (!empty($config['system']['webgui']['althostnames']) && !$found_host) {
110 86b21903 jim-p
		$althosts = explode(" ", $config['system']['webgui']['althostnames']);
111 1e0b1727 Phil Davis
		foreach ($althosts as $ah) {
112
			if (strcasecmp($ah, $http_host) == 0 or strcasecmp($ah, $_SERVER['SERVER_ADDR']) == 0) {
113 86b21903 jim-p
				$found_host = true;
114 9ae11a62 Scott Ullrich
				break;
115
			}
116 1e0b1727 Phil Davis
		}
117 9b13f84b Scott Ullrich
	}
118 ce46b5da Scott Ullrich
119 1e0b1727 Phil Davis
	if ($found_host == false) {
120
		if (!security_checks_disabled()) {
121 8cd558b6 ayvis
			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 9ae11a62 Scott Ullrich
			exit;
123
		}
124
		$security_passed = false;
125
	}
126
}
127 ef173724 Scott Ullrich
128 9ae11a62 Scott Ullrich
// If the HTTP_REFERER is something other than ourselves then disallow.
129 1e0b1727 Phil Davis
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 9ae11a62 Scott Ullrich
				unlink("{$g['tmp_path']}/setupwizard_lastreferrer");
134
				header("Refresh: 1; url=index.php");
135 1180e4f0 Sjon Hortensius
?>
136
<!DOCTYPE html>
137
<html lang="en">
138
<head>
139 b4738ddc NewEraCracker
	<link rel="stylesheet" href="/css/pfSense.css" />
140 1180e4f0 Sjon Hortensius
	<title><?=gettext("Redirecting..."); ?></title>
141
</head>
142
<body id="error" class="no-menu">
143
	<div id="jumbotron">
144
		<div class="container">
145 c7d61071 Sander van Leeuwen
			<div class="col-sm-offset-3 col-sm-6 col-xs-12">
146
				<p><?=gettext("Redirecting to the dashboard...")?></p>
147
			</div>
148 1180e4f0 Sjon Hortensius
		</div>
149
	</div>
150
</body>
151
</html>
152
<?php
153 9ae11a62 Scott Ullrich
				exit;
154
			}
155
		}
156
		$found_host = false;
157
		$referrer_host = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
158 e6f7e0be smos
		$referrer_host = str_replace(array("[", "]"), "", $referrer_host);
159 1e0b1727 Phil Davis
		if ($referrer_host) {
160 ae52d165 Renato Botelho
			if (strcasecmp($referrer_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 ||
161 4e322e2c Phil Davis
			    strcasecmp($referrer_host, $config['system']['hostname']) == 0) {
162 9ae11a62 Scott Ullrich
				$found_host = true;
163 1e0b1727 Phil Davis
			}
164 9f0bee02 jim-p
165 1e0b1727 Phil Davis
			if (!empty($config['system']['webgui']['althostnames']) && !$found_host) {
166 9ae11a62 Scott Ullrich
				$althosts = explode(" ", $config['system']['webgui']['althostnames']);
167
				foreach ($althosts as $ah) {
168 1e0b1727 Phil Davis
					if (strcasecmp($referrer_host, $ah) == 0) {
169 9ae11a62 Scott Ullrich
						$found_host = true;
170
						break;
171
					}
172
				}
173
			}
174 9f0bee02 jim-p
175 1e0b1727 Phil Davis
			if (is_array($config['dyndnses']['dyndns']) && !$found_host) {
176
				foreach ($config['dyndnses']['dyndns'] as $dyndns) {
177
					if (strcasecmp($dyndns['host'], $referrer_host) == 0) {
178 9f0bee02 jim-p
						$found_host = true;
179
						break;
180
					}
181 1e0b1727 Phil Davis
				}
182
			}
183 9f0bee02 jim-p
184 1e0b1727 Phil Davis
			if (is_array($config['dnsupdates']['dnsupdate']) && !$found_host) {
185
				foreach ($config['dnsupdates']['dnsupdate'] as $rfc2136) {
186
					if (strcasecmp($rfc2136['host'], $referrer_host) == 0) {
187 9f0bee02 jim-p
						$found_host = true;
188
						break;
189
					}
190 1e0b1727 Phil Davis
				}
191
			}
192 9f0bee02 jim-p
193 1e0b1727 Phil Davis
			if (!$found_host) {
194 9ae11a62 Scott Ullrich
				$interface_list_ips = get_configured_ip_addresses();
195 1e0b1727 Phil Davis
				foreach ($interface_list_ips as $ilips) {
196
					if (strcasecmp($referrer_host, $ilips) == 0) {
197 9ae11a62 Scott Ullrich
						$found_host = true;
198
						break;
199
					}
200
				}
201 6a53de6f NewEraCracker
				$interface_list_ipv6s = get_configured_ipv6_addresses(true);
202 1e0b1727 Phil Davis
				foreach ($interface_list_ipv6s as $ilipv6s) {
203 6a53de6f NewEraCracker
					$ilipv6s = explode('%', $ilipv6s)[0];
204 1e0b1727 Phil Davis
					if (strcasecmp($referrer_host, $ilipv6s) == 0) {
205 e6f7e0be smos
						$found_host = true;
206
						break;
207
					}
208
				}
209 1e0b1727 Phil Davis
				if ($referrer_host == "127.0.0.1" || $referrer_host == "localhost") {
210 17dd7ff3 Chris Buechler
					// allow SSH port forwarded connections and links from localhost
211
					$found_host = true;
212
				}
213 9ae11a62 Scott Ullrich
			}
214
		}
215 1e0b1727 Phil Davis
		if ($found_host == false) {
216
			if (!security_checks_disabled()) {
217 530e4707 NOYB
				display_error_form("501", "An HTTP_REFERER was detected other than what is defined in System -> Advanced (" . htmlspecialchars($_SERVER['HTTP_REFERER']) . ").  If not needed, this check can be disabled in System -> Advanced -> Admin.");
218 0f806eca Erik Fonnesbeck
				exit;
219
			}
220 9ae11a62 Scott Ullrich
			$security_passed = false;
221
		}
222 1e0b1727 Phil Davis
	} else {
223 9ae11a62 Scott Ullrich
		$security_passed = false;
224 1e0b1727 Phil Davis
	}
225 4fe9c2dc Scott Ullrich
}
226
227 1e0b1727 Phil Davis
if (function_exists("display_error_form") && $security_passed) {
228 9ae11a62 Scott Ullrich
	/* Security checks passed, so it should be OK to turn them back on */
229
	restore_security_checks();
230 1e0b1727 Phil Davis
}
231 9ae11a62 Scott Ullrich
unset($security_passed);
232
233 55eb9c44 --global
$groupindex = index_groups();
234
$userindex = index_users();
235
236
function index_groups() {
237
	global $g, $debug, $config, $groupindex;
238
239
	$groupindex = array();
240
241 6dcd80af Ermal
	if (is_array($config['system']['group'])) {
242 55eb9c44 --global
		$i = 0;
243 1e0b1727 Phil Davis
		foreach ($config['system']['group'] as $groupent) {
244 55eb9c44 --global
			$groupindex[$groupent['name']] = $i;
245
			$i++;
246
		}
247
	}
248
249
	return ($groupindex);
250
}
251
252
function index_users() {
253
	global $g, $debug, $config;
254
255 6dcd80af Ermal
	if (is_array($config['system']['user'])) {
256 55eb9c44 --global
		$i = 0;
257 1e0b1727 Phil Davis
		foreach ($config['system']['user'] as $userent) {
258 55eb9c44 --global
			$userindex[$userent['name']] = $i;
259
			$i++;
260
		}
261
	}
262
263
	return ($userindex);
264
}
265
266
function & getUserEntry($name) {
267
	global $debug, $config, $userindex;
268 0ef6fddc jim-p
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
269
270 1e0b1727 Phil Davis
	if (isset($userindex[$name])) {
271 55eb9c44 --global
		return $config['system']['user'][$userindex[$name]];
272 0ef6fddc jim-p
	} elseif ($authcfg['type'] != "Local Database") {
273
		$user = array();
274
		$user['name'] = $name;
275
		return $user;
276 1e0b1727 Phil Davis
	}
277 55eb9c44 --global
}
278
279
function & getUserEntryByUID($uid) {
280
	global $debug, $config;
281 84924e76 Ermal
282 1e0b1727 Phil Davis
	if (is_array($config['system']['user'])) {
283
		foreach ($config['system']['user'] as & $user) {
284
			if ($user['uid'] == $uid) {
285 84924e76 Ermal
				return $user;
286 1e0b1727 Phil Davis
			}
287
		}
288
	}
289 55eb9c44 --global
290
	return false;
291
}
292
293
function & getGroupEntry($name) {
294
	global $debug, $config, $groupindex;
295 1e0b1727 Phil Davis
	if (isset($groupindex[$name])) {
296 55eb9c44 --global
		return $config['system']['group'][$groupindex[$name]];
297 1e0b1727 Phil Davis
	}
298 55eb9c44 --global
}
299
300
function & getGroupEntryByGID($gid) {
301
	global $debug, $config;
302 84924e76 Ermal
303 1e0b1727 Phil Davis
	if (is_array($config['system']['group'])) {
304
		foreach ($config['system']['group'] as & $group) {
305
			if ($group['gid'] == $gid) {
306 84924e76 Ermal
				return $group;
307 1e0b1727 Phil Davis
			}
308
		}
309
	}
310 55eb9c44 --global
311
	return false;
312
}
313
314 6dc88d53 Ermal Luci
function get_user_privileges(& $user) {
315 7abc3f99 Phil Davis
	global $config, $_SESSION;
316 0ef6fddc jim-p
317
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
318 7abc3f99 Phil Davis
	$allowed_groups = array();
319 6dc88d53 Ermal Luci
320 1e0b1727 Phil Davis
	$privs = $user['priv'];
321
	if (!is_array($privs)) {
322
		$privs = array();
323
	}
324 6dc88d53 Ermal Luci
325 7abc3f99 Phil Davis
	// cache auth results for a short time to ease load on auth services & logs
326
	if (isset($config['system']['webgui']['auth_refresh_time'])) {
327
		$recheck_time = $config['system']['webgui']['auth_refresh_time'];
328
	} else {
329
		$recheck_time = 30;
330
	}
331
332 0ef6fddc jim-p
	if ($authcfg['type'] == "ldap") {
333 7abc3f99 Phil Davis
		if (isset($_SESSION["ldap_allowed_groups"]) &&
334
		    (time() <= $_SESSION["auth_check_time"] + $recheck_time)) {
335
			$allowed_groups = $_SESSION["ldap_allowed_groups"];
336
		} else {
337
			$allowed_groups = @ldap_get_groups($user['name'], $authcfg);
338
			$_SESSION["ldap_allowed_groups"] = $allowed_groups;
339
			$_SESSION["auth_check_time"] = time();
340
		}
341 0ef6fddc jim-p
	} elseif ($authcfg['type'] == "radius") {
342 7abc3f99 Phil Davis
		if (isset($_SESSION["radius_allowed_groups"]) &&
343
		    (time() <= $_SESSION["auth_check_time"] + $recheck_time)) {
344
			$allowed_groups = $_SESSION["radius_allowed_groups"];
345
		} else {
346
			$allowed_groups = @radius_get_groups($_SESSION['user_radius_attributes']);
347
			$_SESSION["radius_allowed_groups"] = $allowed_groups;
348
			$_SESSION["auth_check_time"] = time();
349
		}
350 0ef6fddc jim-p
	}
351
352 7abc3f99 Phil Davis
	if (empty($allowed_groups)) {
353
		$allowed_groups = local_user_get_groups($user, true);
354 0ef6fddc jim-p
	}
355 6dc88d53 Ermal Luci
356 7abc3f99 Phil Davis
	if (is_array($allowed_groups)) {
357
		foreach ($allowed_groups as $name) {
358
			$group = getGroupEntry($name);
359
			if (is_array($group['priv'])) {
360
				$privs = array_merge($privs, $group['priv']);
361
			}
362 1e0b1727 Phil Davis
		}
363
	}
364 6dc88d53 Ermal Luci
365 1e0b1727 Phil Davis
	return $privs;
366 6dc88d53 Ermal Luci
}
367
368
function userHasPrivilege($userent, $privid = false) {
369
370 1e0b1727 Phil Davis
	if (!$privid || !is_array($userent)) {
371
		return false;
372
	}
373 6dc88d53 Ermal Luci
374 1e0b1727 Phil Davis
	$privs = get_user_privileges($userent);
375 6dc88d53 Ermal Luci
376 1e0b1727 Phil Davis
	if (!is_array($privs)) {
377
		return false;
378
	}
379 6dc88d53 Ermal Luci
380 1e0b1727 Phil Davis
	if (!in_array($privid, $privs)) {
381
		return false;
382
	}
383 6dc88d53 Ermal Luci
384 1e0b1727 Phil Davis
	return true;
385 6dc88d53 Ermal Luci
}
386
387 55eb9c44 --global
function local_backed($username, $passwd) {
388
389
	$user = getUserEntry($username);
390 1e0b1727 Phil Davis
	if (!$user) {
391 55eb9c44 --global
		return false;
392 1e0b1727 Phil Davis
	}
393 55eb9c44 --global
394 1e0b1727 Phil Davis
	if (is_account_disabled($username) || is_account_expired($username)) {
395 a13ce628 Ermal Lu?i
		return false;
396 1e0b1727 Phil Davis
	}
397 a13ce628 Ermal Lu?i
398 9219378b daniel
	if ($user['bcrypt-hash']) {
399
		if (password_verify($passwd, $user['bcrypt-hash'])) {
400
			return true;
401
		}
402
	}
403
404
	//for backwards compatibility
405 1e0b1727 Phil Davis
	if ($user['password']) {
406
		if (crypt($passwd, $user['password']) == $user['password']) {
407 55eb9c44 --global
			return true;
408 1e0b1727 Phil Davis
		}
409 55eb9c44 --global
	}
410
411 1e0b1727 Phil Davis
	if ($user['md5-hash']) {
412
		if (md5($passwd) == $user['md5-hash']) {
413 55eb9c44 --global
			return true;
414 1e0b1727 Phil Davis
		}
415 55eb9c44 --global
	}
416
417
	return false;
418
}
419
420 79f7bc7f Renato Botelho
function local_sync_accounts($u2add, $u2del, $g2add, $g2del) {
421
	global $config, $debug;
422
423
	if (empty($u2add) && empty($u2del) && empty($g2add) && empty($g2del)) {
424
		/* Nothing to be done here */
425
		return;
426
	}
427
428
	foreach($u2del as $user) {
429
		if ($user['uid'] < 2000 || $user['uid'] > 65000) {
430
			continue;
431
		}
432
433
		/*
434
		 * If a crontab was created to user, pw userdel will be
435
		 * interactive and can cause issues. Just remove crontab
436
		 * before run it when necessary
437
		 */
438
		unlink_if_exists("/var/cron/tabs/{$user['name']}");
439
		$cmd = "/usr/sbin/pw userdel -n " .
440
		    escapeshellarg($user['name']);
441
		if ($debug) {
442
			log_error(sprintf(gettext("Running: %s"), $cmd));
443
		}
444
		mwexec($cmd);
445
		local_group_del_user($user);
446
447
		$system_user = $config['system']['user'];
448
		for ($i = 0; $i < count($system_user); $i++) {
449
			if ($system_user[$i]['name'] == $user['name']) {
450 90510875 Renato Botelho
				log_error("Removing user: {$user['name']}");
451 79f7bc7f Renato Botelho
				unset($config['system']['user'][$i]);
452
				break;
453
			}
454
		}
455
	}
456
457
	foreach($g2del as $group) {
458
		if ($group['gid'] < 1999 || $group['gid'] > 65000) {
459
			continue;
460
		}
461
462
		$cmd = "/usr/sbin/pw groupdel -g " .
463
		    escapeshellarg($group['name']);
464
		if ($debug) {
465
			log_error(sprintf(gettext("Running: %s"), $cmd));
466
		}
467
		mwexec($cmd);
468
469
		$system_group = $config['system']['group'];
470
		for ($i = 0; $i < count($system_group); $i++) {
471
			if ($system_group[$i]['name'] == $group['name']) {
472 90510875 Renato Botelho
				log_error("Removing group: {$group['name']}");
473 79f7bc7f Renato Botelho
				unset($config['system']['group'][$i]);
474
				break;
475
			}
476
		}
477
	}
478
479
	foreach ($u2add as $user) {
480 90510875 Renato Botelho
		log_error("Adding user: {$user['name']}");
481 79f7bc7f Renato Botelho
		$config['system']['user'][] = $user;
482
	}
483
484
	foreach ($g2add as $group) {
485 90510875 Renato Botelho
		log_error("Adding group: {$group['name']}");
486 79f7bc7f Renato Botelho
		$config['system']['group'][] = $group;
487
	}
488
489 dc3bc1f8 Renato Botelho
	/* Sort it alphabetically */
490
	usort($config['system']['user'], function($a, $b) {
491
		return strcmp($a['name'], $b['name']);
492
	});
493
	usort($config['system']['group'], function($a, $b) {
494
		return strcmp($a['name'], $b['name']);
495
	});
496
497 79f7bc7f Renato Botelho
	write_config("Sync'd users and groups via XMLRPC");
498
499
	/* make sure the all group exists */
500
	$allgrp = getGroupEntryByGID(1998);
501
	local_group_set($allgrp, true);
502
503
	foreach ($u2add as $user) {
504
		local_user_set($user);
505
	}
506
507
	foreach ($g2add as $group) {
508
		local_group_set($group);
509
	}
510
}
511
512
function local_reset_accounts() {
513 55eb9c44 --global
	global $debug, $config;
514
515
	/* remove local users to avoid uid conflicts */
516
	$fd = popen("/usr/sbin/pw usershow -a", "r");
517
	if ($fd) {
518
		while (!feof($fd)) {
519 4de8f7ba Phil Davis
			$line = explode(":", fgets($fd));
520 3ee1e659 Renato Botelho
			if ($line[0] != "admin") {
521
				if (!strncmp($line[0], "_", 1)) {
522
					continue;
523
				}
524
				if ($line[2] < 2000) {
525
					continue;
526
				}
527
				if ($line[2] > 65000) {
528
					continue;
529
				}
530 1e0b1727 Phil Davis
			}
531 2b41df9c Renato Botelho
			/*
532
			 * If a crontab was created to user, pw userdel will be interactive and
533
			 * can cause issues. Just remove crontab before run it when necessary
534
			 */
535
			unlink_if_exists("/var/cron/tabs/{$line[0]}");
536 0a39f78f jim-p
			$cmd = "/usr/sbin/pw userdel -n " . escapeshellarg($line[0]);
537 1e0b1727 Phil Davis
			if ($debug) {
538 94021404 Carlos Eduardo Ramos
				log_error(sprintf(gettext("Running: %s"), $cmd));
539 1e0b1727 Phil Davis
			}
540 55eb9c44 --global
			mwexec($cmd);
541
		}
542
		pclose($fd);
543
	}
544
545
	/* remove local groups to avoid gid conflicts */
546
	$gids = array();
547
	$fd = popen("/usr/sbin/pw groupshow -a", "r");
548
	if ($fd) {
549
		while (!feof($fd)) {
550 4de8f7ba Phil Davis
			$line = explode(":", fgets($fd));
551 1e0b1727 Phil Davis
			if (!strncmp($line[0], "_", 1)) {
552 55eb9c44 --global
				continue;
553 1e0b1727 Phil Davis
			}
554
			if ($line[2] < 2000) {
555 55eb9c44 --global
				continue;
556 1e0b1727 Phil Davis
			}
557
			if ($line[2] > 65000) {
558 55eb9c44 --global
				continue;
559 1e0b1727 Phil Davis
			}
560 0a39f78f jim-p
			$cmd = "/usr/sbin/pw groupdel -g " . escapeshellarg($line[2]);
561 1e0b1727 Phil Davis
			if ($debug) {
562 94021404 Carlos Eduardo Ramos
				log_error(sprintf(gettext("Running: %s"), $cmd));
563 1e0b1727 Phil Davis
			}
564 55eb9c44 --global
			mwexec($cmd);
565
		}
566
		pclose($fd);
567
	}
568
569
	/* make sure the all group exists */
570
	$allgrp = getGroupEntryByGID(1998);
571
	local_group_set($allgrp, true);
572
573 5af2baf7 jim-p
	/* sync all local users */
574 1e0b1727 Phil Davis
	if (is_array($config['system']['user'])) {
575
		foreach ($config['system']['user'] as $user) {
576 5af2baf7 jim-p
			local_user_set($user);
577 1e0b1727 Phil Davis
		}
578
	}
579 5af2baf7 jim-p
580 f3e0a111 jim-p
	/* sync all local groups */
581 1e0b1727 Phil Davis
	if (is_array($config['system']['group'])) {
582
		foreach ($config['system']['group'] as $group) {
583 f3e0a111 jim-p
			local_group_set($group);
584 1e0b1727 Phil Davis
		}
585
	}
586 55eb9c44 --global
}
587
588
function local_user_set(& $user) {
589
	global $g, $debug;
590
591 9219378b daniel
	if (empty($user['password']) && empty($user['bcrypt-hash'])) {
592 530e4707 NOYB
		log_error("There is something wrong in the config because user {$user['name']} password is missing!");
593 b3c106a0 Ermal
		return;
594
	}
595
596 2bb07efc Scott Ullrich
597 1180e4f0 Sjon Hortensius
	$home_base = "/home/";
598 55eb9c44 --global
	$user_uid = $user['uid'];
599
	$user_name = $user['name'];
600 461df7c0 jim-p
	$user_home = "{$home_base}{$user_name}";
601 55eb9c44 --global
	$user_shell = "/etc/rc.initial";
602
	$user_group = "nobody";
603
604
	// Ensure $home_base exists and is writable
605 1e0b1727 Phil Davis
	if (!is_dir($home_base)) {
606 55eb9c44 --global
		mkdir($home_base, 0755);
607 1e0b1727 Phil Davis
	}
608 55eb9c44 --global
609 df8d74de jim-p
	$lock_account = false;
610 55eb9c44 --global
	/* configure shell type */
611 3e251b12 Erik Fonnesbeck
	/* Cases here should be ordered by most privileged to least privileged. */
612 a137fedd jim-p
	if (userHasPrivilege($user, "user-shell-access") || userHasPrivilege($user, "page-all")) {
613 29293dce jim-p
		$user_shell = "/bin/tcsh";
614 74fd2299 doktornotor
	} elseif (userHasPrivilege($user, "user-copy-files-chroot")) {
615
		$user_shell = "/usr/local/sbin/scponlyc";
616 647db6bb doktornotor
	} elseif (userHasPrivilege($user, "user-copy-files")) {
617
		$user_shell = "/usr/local/bin/scponly";
618 3e251b12 Erik Fonnesbeck
	} elseif (userHasPrivilege($user, "user-ssh-tunnel")) {
619
		$user_shell = "/usr/local/sbin/ssh_tunnel_shell";
620 fbfd675a jim-p
	} elseif (userHasPrivilege($user, "user-ipsec-xauth-dialin")) {
621
		$user_shell = "/sbin/nologin";
622 1ed86bc6 jim-p
	} else {
623
		$user_shell = "/sbin/nologin";
624 df8d74de jim-p
		$lock_account = true;
625
	}
626
627
	/* Lock out disabled or expired users, unless it's root/admin. */
628
	if ((is_account_disabled($user_name) || is_account_expired($user_name)) && ($user_uid != 0)) {
629
		$user_shell = "/sbin/nologin";
630
		$lock_account = true;
631 55eb9c44 --global
	}
632
633
	/* root user special handling */
634
	if ($user_uid == 0) {
635
		$cmd = "/usr/sbin/pw usermod -q -n root -s /bin/sh -H 0";
636 1e0b1727 Phil Davis
		if ($debug) {
637 94021404 Carlos Eduardo Ramos
			log_error(sprintf(gettext("Running: %s"), $cmd));
638 1e0b1727 Phil Davis
		}
639 55eb9c44 --global
		$fd = popen($cmd, "w");
640 9219378b daniel
		if (empty($user['bcrypt-hash'])) {
641
			fwrite($fd, $user['password']);
642 9a7911eb Daniel Vinakovsky
		} else {
643 9219378b daniel
			fwrite($fd, $user['bcrypt-hash']);
644
		}
645 55eb9c44 --global
		pclose($fd);
646
		$user_group = "wheel";
647 2708e399 jim-p
		$user_home = "/root";
648 29293dce jim-p
		$user_shell = "/etc/rc.initial";
649 55eb9c44 --global
	}
650
651
	/* read from pw db */
652 9fd14591 jim-p
	$fd = popen("/usr/sbin/pw usershow -n {$user_name} 2>&1", "r");
653 55eb9c44 --global
	$pwread = fgets($fd);
654
	pclose($fd);
655 9fd14591 jim-p
	$userattrs = explode(":", trim($pwread));
656 55eb9c44 --global
657 13a70e7d Renato Botelho
	$skel_dir = '/etc/skel';
658
659 55eb9c44 --global
	/* determine add or mod */
660 9fd14591 jim-p
	if (($userattrs[0] != $user['name']) || (!strncmp($pwread, "pw:", 3))) {
661 4bf17edc jim-p
		$user_op = "useradd -m -k " . escapeshellarg($skel_dir) . " -o";
662 38564fde smos
	} else {
663 55eb9c44 --global
		$user_op = "usermod";
664 38564fde smos
	}
665 55eb9c44 --global
666 1180e4f0 Sjon Hortensius
	$comment = str_replace(array(":", "!", "@"), " ", $user['descr']);
667 55eb9c44 --global
	/* add or mod pw db */
668 0a39f78f jim-p
	$cmd = "/usr/sbin/pw {$user_op} -q " .
669
			" -u " . escapeshellarg($user_uid) .
670
			" -n " . escapeshellarg($user_name) .
671
			" -g " . escapeshellarg($user_group) .
672
			" -s " . escapeshellarg($user_shell) .
673
			" -d " . escapeshellarg($user_home) .
674
			" -c " . escapeshellarg($comment) .
675
			" -H 0 2>&1";
676 55eb9c44 --global
677 1e0b1727 Phil Davis
	if ($debug) {
678 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("Running: %s"), $cmd));
679 1e0b1727 Phil Davis
	}
680 55eb9c44 --global
	$fd = popen($cmd, "w");
681 9219378b daniel
	if (empty($user['bcrypt-hash'])) {
682
		fwrite($fd, $user['password']);
683 9a7911eb Daniel Vinakovsky
	} else {
684 9219378b daniel
		fwrite($fd, $user['bcrypt-hash']);
685
	}
686 55eb9c44 --global
	pclose($fd);
687
688
	/* create user directory if required */
689
	if (!is_dir($user_home)) {
690
		mkdir($user_home, 0700);
691
	}
692 23c652cd Ermal
	@chown($user_home, $user_name);
693
	@chgrp($user_home, $user_group);
694 55eb9c44 --global
695 13a70e7d Renato Botelho
	/* Make sure all users have last version of config files */
696
	foreach (glob("{$skel_dir}/dot.*") as $dot_file) {
697
		$target = $user_home . '/' . substr(basename($dot_file), 3);
698
		@copy($dot_file, $target);
699
		@chown($target, $user_name);
700
		@chgrp($target, $user_group);
701
	}
702
703 55eb9c44 --global
	/* write out ssh authorized key file */
704 1e0b1727 Phil Davis
	if ($user['authorizedkeys']) {
705 a2286360 Ermal Lu?i
		if (!is_dir("{$user_home}/.ssh")) {
706 23c652cd Ermal
			@mkdir("{$user_home}/.ssh", 0700);
707
			@chown("{$user_home}/.ssh", $user_name);
708 a2286360 Ermal Lu?i
		}
709
		$keys = base64_decode($user['authorizedkeys']);
710 23c652cd Ermal
		@file_put_contents("{$user_home}/.ssh/authorized_keys", $keys);
711
		@chown("{$user_home}/.ssh/authorized_keys", $user_name);
712 1e0b1727 Phil Davis
	} else {
713 cdab65cc Erik Fonnesbeck
		unlink_if_exists("{$user_home}/.ssh/authorized_keys");
714 1e0b1727 Phil Davis
	}
715 df8d74de jim-p
716
	$un = $lock_account ? "" : "un";
717 0a39f78f jim-p
	exec("/usr/sbin/pw {$un}lock " . escapeshellarg($user_name) . " -q 2>/dev/null");
718 1180e4f0 Sjon Hortensius
719 55eb9c44 --global
}
720
721
function local_user_del($user) {
722
	global $debug;
723 2bb07efc Scott Ullrich
724 55eb9c44 --global
	/* remove all memberships */
725 019e6c3f jim-p
	local_user_set_groups($user);
726 55eb9c44 --global
727 a39675ec jim-p
	/* Don't remove /root */
728 1e0b1727 Phil Davis
	if ($user['uid'] != 0) {
729 a39675ec jim-p
		$rmhome = "-r";
730 1e0b1727 Phil Davis
	}
731 a39675ec jim-p
732 9fd14591 jim-p
	/* read from pw db */
733
	$fd = popen("/usr/sbin/pw usershow -n {$user['name']} 2>&1", "r");
734
	$pwread = fgets($fd);
735
	pclose($fd);
736
	$userattrs = explode(":", trim($pwread));
737
738
	if ($userattrs[0] != $user['name']) {
739
		log_error("Tried to remove user {$user['name']} but got user {$userattrs[0]} instead. Bailing.");
740
		return;
741
	}
742
743 55eb9c44 --global
	/* delete from pw db */
744 0a39f78f jim-p
	$cmd = "/usr/sbin/pw userdel -n " . escapeshellarg($user['name']) . " " . escapeshellarg($rmhome);
745 55eb9c44 --global
746 1e0b1727 Phil Davis
	if ($debug) {
747 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("Running: %s"), $cmd));
748 1e0b1727 Phil Davis
	}
749 0914b6bb Ermal
	mwexec($cmd);
750 2bb07efc Scott Ullrich
751 0914b6bb Ermal
	/* Delete user from groups needs a call to write_config() */
752
	local_group_del_user($user);
753 55eb9c44 --global
}
754
755 4d9801c2 Jim Thompson
function local_user_set_password(&$user, $password) {
756 33386b07 Daniel Vinakovsky
	unset($user['password']);
757
	unset($user['md5-hash']);
758
	$user['bcrypt-hash'] = password_hash($password, PASSWORD_BCRYPT);
759 55eb9c44 --global
}
760
761
function local_user_get_groups($user, $all = false) {
762
	global $debug, $config;
763
764
	$groups = array();
765 1e0b1727 Phil Davis
	if (!is_array($config['system']['group'])) {
766 55eb9c44 --global
		return $groups;
767 1e0b1727 Phil Davis
	}
768 55eb9c44 --global
769 1e0b1727 Phil Davis
	foreach ($config['system']['group'] as $group) {
770 4de8f7ba Phil Davis
		if ($all || (!$all && ($group['name'] != "all"))) {
771 1e0b1727 Phil Davis
			if (is_array($group['member'])) {
772
				if (in_array($user['uid'], $group['member'])) {
773 55eb9c44 --global
					$groups[] = $group['name'];
774 1e0b1727 Phil Davis
				}
775
			}
776
		}
777
	}
778 55eb9c44 --global
779 1e0b1727 Phil Davis
	if ($all) {
780 b0c231e4 jim-p
		$groups[] = "all";
781 1e0b1727 Phil Davis
	}
782 b0c231e4 jim-p
783 55eb9c44 --global
	sort($groups);
784
785
	return $groups;
786 1180e4f0 Sjon Hortensius
787 55eb9c44 --global
}
788
789 4de8f7ba Phil Davis
function local_user_set_groups($user, $new_groups = NULL) {
790 aa029c93 Renato Botelho
	global $debug, $config, $groupindex, $userindex;
791 4de8f7ba Phil Davis
792 1e0b1727 Phil Davis
	if (!is_array($config['system']['group'])) {
793 55eb9c44 --global
		return;
794 1e0b1727 Phil Davis
	}
795 55eb9c44 --global
796 739c78ac jim-p
	$cur_groups = local_user_get_groups($user, true);
797 55eb9c44 --global
	$mod_groups = array();
798
799 1e0b1727 Phil Davis
	if (!is_array($new_groups)) {
800 55eb9c44 --global
		$new_groups = array();
801 1e0b1727 Phil Davis
	}
802 55eb9c44 --global
803 1e0b1727 Phil Davis
	if (!is_array($cur_groups)) {
804 55eb9c44 --global
		$cur_groups = array();
805 1e0b1727 Phil Davis
	}
806 55eb9c44 --global
807
	/* determine which memberships to add */
808
	foreach ($new_groups as $groupname) {
809 4de8f7ba Phil Davis
		if ($groupname == '' || in_array($groupname, $cur_groups)) {
810 55eb9c44 --global
			continue;
811 1e0b1727 Phil Davis
		}
812 55eb9c44 --global
		$group = & $config['system']['group'][$groupindex[$groupname]];
813
		$group['member'][] = $user['uid'];
814
		$mod_groups[] = $group;
815 aa029c93 Renato Botelho
816
		/*
817
		 * If it's a new user, make sure it is added before try to
818
		 * add it as a member of a group
819
		 */
820
		if (!isset($userindex[$user['uid']])) {
821
			local_user_set($user);
822
		}
823 55eb9c44 --global
	}
824 9ae11a62 Scott Ullrich
	unset($group);
825 55eb9c44 --global
826
	/* determine which memberships to remove */
827
	foreach ($cur_groups as $groupname) {
828 4de8f7ba Phil Davis
		if (in_array($groupname, $new_groups)) {
829 e879fc81 Ermal
			continue;
830 1e0b1727 Phil Davis
		}
831
		if (!isset($config['system']['group'][$groupindex[$groupname]])) {
832 25fec9b3 jim-p
			continue;
833 1e0b1727 Phil Davis
		}
834 55eb9c44 --global
		$group = & $config['system']['group'][$groupindex[$groupname]];
835 7b5c56ea jim-p
		if (is_array($group['member'])) {
836
			$index = array_search($user['uid'], $group['member']);
837
			array_splice($group['member'], $index, 1);
838
			$mod_groups[] = $group;
839
		}
840 55eb9c44 --global
	}
841 9ae11a62 Scott Ullrich
	unset($group);
842 55eb9c44 --global
843
	/* sync all modified groups */
844 1e0b1727 Phil Davis
	foreach ($mod_groups as $group) {
845 55eb9c44 --global
		local_group_set($group);
846 1e0b1727 Phil Davis
	}
847 55eb9c44 --global
}
848
849 0914b6bb Ermal
function local_group_del_user($user) {
850
	global $config;
851
852 1e0b1727 Phil Davis
	if (!is_array($config['system']['group'])) {
853
		return;
854
	}
855 0914b6bb Ermal
856 1e0b1727 Phil Davis
	foreach ($config['system']['group'] as $group) {
857 0914b6bb Ermal
		if (is_array($group['member'])) {
858
			foreach ($group['member'] as $idx => $uid) {
859 1e0b1727 Phil Davis
				if ($user['uid'] == $uid) {
860 0914b6bb Ermal
					unset($config['system']['group']['member'][$idx]);
861 1e0b1727 Phil Davis
				}
862 0914b6bb Ermal
			}
863
		}
864
	}
865
}
866
867 55eb9c44 --global
function local_group_set($group, $reset = false) {
868
	global $debug;
869
870
	$group_name = $group['name'];
871
	$group_gid = $group['gid'];
872 baca968c Ermal
	$group_members = '';
873 64fa4207 Steve Beaver
874 1e0b1727 Phil Davis
	if (!$reset && !empty($group['member']) && count($group['member']) > 0) {
875 4de8f7ba Phil Davis
		$group_members = implode(",", $group['member']);
876 1e0b1727 Phil Davis
	}
877 55eb9c44 --global
878 64fa4207 Steve Beaver
	if (empty($group_name)) {
879
		return;
880
	}
881
882
	// If the group is now remote, make sure there is no local group with the same name
883
	if ($group['scope'] == "remote") {
884
		local_group_del($group);
885 baca968c Ermal
		return;
886 1e0b1727 Phil Davis
	}
887 baca968c Ermal
888 55eb9c44 --global
	/* determine add or mod */
889 0a39f78f jim-p
	if (mwexec("/usr/sbin/pw groupshow -g " . escapeshellarg($group_gid) . " 2>&1", true) == 0) {
890 7cb01159 Chris Buechler
		$group_op = "groupmod -l";
891 1e0b1727 Phil Davis
	} else {
892 7cb01159 Chris Buechler
		$group_op = "groupadd -n";
893 1e0b1727 Phil Davis
	}
894 55eb9c44 --global
895
	/* add or mod group db */
896 0a39f78f jim-p
	$cmd = "/usr/sbin/pw {$group_op} " .
897
		escapeshellarg($group_name) .
898
		" -g " . escapeshellarg($group_gid) .
899
		" -M " . escapeshellarg($group_members) . " 2>&1";
900 55eb9c44 --global
901 1e0b1727 Phil Davis
	if ($debug) {
902 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("Running: %s"), $cmd));
903 1e0b1727 Phil Davis
	}
904 55eb9c44 --global
905 64fa4207 Steve Beaver
	mwexec($cmd);
906 55eb9c44 --global
}
907
908
function local_group_del($group) {
909
	global $debug;
910
911
	/* delete from group db */
912 0a39f78f jim-p
	$cmd = "/usr/sbin/pw groupdel " . escapeshellarg($group['name']);
913 55eb9c44 --global
914 1e0b1727 Phil Davis
	if ($debug) {
915 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("Running: %s"), $cmd));
916 1e0b1727 Phil Davis
	}
917 0914b6bb Ermal
	mwexec($cmd);
918 55eb9c44 --global
}
919
920 6306b5dd Ermal Lu?i
function ldap_test_connection($authcfg) {
921 c61e4626 Ermal Lu?i
	if ($authcfg) {
922 d672403c derelict-pf
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
923 1e0b1727 Phil Davis
			$ldapproto = "ldaps";
924 d672403c derelict-pf
		} else {
925
			$ldapproto = "ldap";
926 1e0b1727 Phil Davis
		}
927
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
928
		$ldapport = $authcfg['ldap_port'];
929
		if (!empty($ldapport)) {
930 9f27de6d jim-p
			$ldapserver .= ":{$ldapport}";
931 1e0b1727 Phil Davis
		}
932
	} else {
933 6306b5dd Ermal Lu?i
		return false;
934 1e0b1727 Phil Davis
	}
935 55eb9c44 --global
936 1e0b1727 Phil Davis
	/* first check if there is even an LDAP server populated */
937 4de8f7ba Phil Davis
	if (!$ldapserver) {
938 1e0b1727 Phil Davis
		return false;
939
	}
940 c61e4626 Ermal Lu?i
941 1e0b1727 Phil Davis
	/* Setup CA environment if needed. */
942
	ldap_setup_caenv($authcfg);
943 fe2031ab Ermal
944 1e0b1727 Phil Davis
	/* connect and see if server is up */
945
	$error = false;
946
	if (!($ldap = ldap_connect($ldapserver))) {
947 9f27de6d jim-p
		$error = true;
948 1e0b1727 Phil Davis
	}
949 c61e4626 Ermal Lu?i
950 1e0b1727 Phil Davis
	if ($error == true) {
951 34925626 Phil Davis
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $authcfg['name']));
952 1e0b1727 Phil Davis
		return false;
953
	}
954 55eb9c44 --global
955
	return true;
956
}
957
958 fe2031ab Ermal
function ldap_setup_caenv($authcfg) {
959
	global $g;
960 007e59d2 jim-p
	require_once("certs.inc");
961 fe2031ab Ermal
962
	unset($caref);
963 d672403c derelict-pf
	if (empty($authcfg['ldap_caref']) || strstr($authcfg['ldap_urltype'], "Standard")) {
964 fe2031ab Ermal
		putenv('LDAPTLS_REQCERT=never');
965
		return;
966 87c67243 jim-p
	} elseif ($authcfg['ldap_caref'] == "global") {
967
		putenv('LDAPTLS_REQCERT=hard');
968
		putenv("LDAPTLS_CACERTDIR=/etc/ssl/");
969
		putenv("LDAPTLS_CACERT=/etc/ssl/cert.pem");
970 fe2031ab Ermal
	} else {
971 a7702ed5 Ermal
		$caref = lookup_ca($authcfg['ldap_caref']);
972 ff500c90 jim-p
		$param = array('caref' => $authcfg['ldap_caref']);
973
		$cachain = ca_chain($param);
974 fe2031ab Ermal
		if (!$caref) {
975 a7702ed5 Ermal
			log_error(sprintf(gettext("LDAP: Could not lookup CA by reference for host %s."), $authcfg['ldap_caref']));
976 fe2031ab Ermal
			/* XXX: Prevent for credential leaking since we cannot setup the CA env. Better way? */
977
			putenv('LDAPTLS_REQCERT=hard');
978
			return;
979
		}
980 1e0b1727 Phil Davis
		if (!is_dir("{$g['varrun_path']}/certs")) {
981 fe2031ab Ermal
			@mkdir("{$g['varrun_path']}/certs");
982 1e0b1727 Phil Davis
		}
983
		if (file_exists("{$g['varrun_path']}/certs/{$caref['refid']}.ca")) {
984 b2a0a8e9 jim-p
			@unlink("{$g['varrun_path']}/certs/{$caref['refid']}.ca");
985 1e0b1727 Phil Davis
		}
986 ff500c90 jim-p
		file_put_contents("{$g['varrun_path']}/certs/{$caref['refid']}.ca", $cachain);
987 b2a0a8e9 jim-p
		@chmod("{$g['varrun_path']}/certs/{$caref['refid']}.ca", 0600);
988 fe2031ab Ermal
		putenv('LDAPTLS_REQCERT=hard');
989
		/* XXX: Probably even the hashed link should be created for this? */
990 906daddc Ermal
		putenv("LDAPTLS_CACERTDIR={$g['varrun_path']}/certs");
991 b2a0a8e9 jim-p
		putenv("LDAPTLS_CACERT={$g['varrun_path']}/certs/{$caref['refid']}.ca");
992 fe2031ab Ermal
	}
993
}
994
995 6306b5dd Ermal Lu?i
function ldap_test_bind($authcfg) {
996 55eb9c44 --global
	global $debug, $config, $g;
997
998 c61e4626 Ermal Lu?i
	if ($authcfg) {
999 d672403c derelict-pf
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1000 1e0b1727 Phil Davis
			$ldapproto = "ldaps";
1001 d672403c derelict-pf
		} else {
1002
			$ldapproto = "ldap";
1003 1e0b1727 Phil Davis
		}
1004
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1005
		$ldapport = $authcfg['ldap_port'];
1006
		if (!empty($ldapport)) {
1007 9f27de6d jim-p
			$ldapserver .= ":{$ldapport}";
1008 1e0b1727 Phil Davis
		}
1009
		$ldapbasedn = $authcfg['ldap_basedn'];
1010
		$ldapbindun = $authcfg['ldap_binddn'];
1011
		$ldapbindpw = $authcfg['ldap_bindpw'];
1012
		$ldapver = $authcfg['ldap_protver'];
1013 e8c09a23 Chris Buechler
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1014 b310666c Carl P. Corliss
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1015 1e0b1727 Phil Davis
			$ldapanon = true;
1016
		} else {
1017
			$ldapanon = false;
1018
		}
1019
	} else {
1020 6306b5dd Ermal Lu?i
		return false;
1021 1e0b1727 Phil Davis
	}
1022 c61e4626 Ermal Lu?i
1023
	/* first check if there is even an LDAP server populated */
1024 1e0b1727 Phil Davis
	if (!$ldapserver) {
1025
		return false;
1026
	}
1027 c61e4626 Ermal Lu?i
1028 fe2031ab Ermal
	/* Setup CA environment if needed. */
1029
	ldap_setup_caenv($authcfg);
1030
1031 1e0b1727 Phil Davis
	/* connect and see if server is up */
1032
	$error = false;
1033
	if (!($ldap = ldap_connect($ldapserver))) {
1034 9f27de6d jim-p
		$error = true;
1035 1e0b1727 Phil Davis
	}
1036 c61e4626 Ermal Lu?i
1037 1e0b1727 Phil Davis
	if ($error == true) {
1038
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1039
		return false;
1040
	}
1041 55eb9c44 --global
1042
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1043 3d3081ec Andrew MacIsaac
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1044 c61e4626 Ermal Lu?i
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1045 d6b4dfe3 jim-p
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1046
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1047 1180e4f0 Sjon Hortensius
1048 d672403c derelict-pf
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1049 ff500c90 jim-p
		if (!(@ldap_start_tls($ldap))) {
1050 d672403c derelict-pf
			log_error(sprintf(gettext("ERROR! ldap_test_bind() could not STARTTLS to server %s."), $ldapname));
1051
			@ldap_close($ldap);
1052
			return false;
1053
		}
1054
	}
1055
1056 a5cd1c5a jim-p
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1057
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1058 c61e4626 Ermal Lu?i
	if ($ldapanon == true) {
1059 6306b5dd Ermal Lu?i
		if (!($res = @ldap_bind($ldap))) {
1060
			@ldap_close($ldap);
1061 c61e4626 Ermal Lu?i
			return false;
1062 6306b5dd Ermal Lu?i
		}
1063
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1064
		@ldap_close($ldap);
1065 55eb9c44 --global
		return false;
1066 6306b5dd Ermal Lu?i
	}
1067 55eb9c44 --global
1068 6306b5dd Ermal Lu?i
	@ldap_unbind($ldap);
1069 c61e4626 Ermal Lu?i
1070 55eb9c44 --global
	return true;
1071
}
1072
1073 6306b5dd Ermal Lu?i
function ldap_get_user_ous($show_complete_ou=true, $authcfg) {
1074 55eb9c44 --global
	global $debug, $config, $g;
1075
1076 1e0b1727 Phil Davis
	if (!function_exists("ldap_connect")) {
1077 55eb9c44 --global
		return;
1078 1e0b1727 Phil Davis
	}
1079 55eb9c44 --global
1080 7a938f1b Ermal
	$ous = array();
1081
1082 c61e4626 Ermal Lu?i
	if ($authcfg) {
1083 d672403c derelict-pf
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1084 1e0b1727 Phil Davis
			$ldapproto = "ldaps";
1085 d672403c derelict-pf
		} else {
1086
			$ldapproto = "ldap";
1087 1e0b1727 Phil Davis
		}
1088
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1089
		$ldapport = $authcfg['ldap_port'];
1090
		if (!empty($ldapport)) {
1091 9f27de6d jim-p
			$ldapserver .= ":{$ldapport}";
1092 1e0b1727 Phil Davis
		}
1093
		$ldapbasedn = $authcfg['ldap_basedn'];
1094
		$ldapbindun = $authcfg['ldap_binddn'];
1095
		$ldapbindpw = $authcfg['ldap_bindpw'];
1096
		$ldapver = $authcfg['ldap_protver'];
1097
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1098
			$ldapanon = true;
1099
		} else {
1100
			$ldapanon = false;
1101
		}
1102
		$ldapname = $authcfg['name'];
1103
		$ldapfallback = false;
1104
		$ldapscope = $authcfg['ldap_scope'];
1105 e8c09a23 Chris Buechler
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1106 1e0b1727 Phil Davis
	} else {
1107 6306b5dd Ermal Lu?i
		return false;
1108 1e0b1727 Phil Davis
	}
1109 55eb9c44 --global
1110 1e0b1727 Phil Davis
	/* first check if there is even an LDAP server populated */
1111
	if (!$ldapserver) {
1112
		log_error(gettext("ERROR!  ldap_get_user_ous() backed selected with no LDAP authentication server defined."));
1113
		return $ous;
1114
	}
1115 c61e4626 Ermal Lu?i
1116 fe2031ab Ermal
	/* Setup CA environment if needed. */
1117
	ldap_setup_caenv($authcfg);
1118
1119 c61e4626 Ermal Lu?i
	/* connect and see if server is up */
1120 1e0b1727 Phil Davis
	$error = false;
1121
	if (!($ldap = ldap_connect($ldapserver))) {
1122 9f27de6d jim-p
		$error = true;
1123 1e0b1727 Phil Davis
	}
1124 c61e4626 Ermal Lu?i
1125 1e0b1727 Phil Davis
	if ($error == true) {
1126
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1127
		return $ous;
1128
	}
1129 c61e4626 Ermal Lu?i
1130
	$ldapfilter = "(|(ou=*)(cn=Users))";
1131 55eb9c44 --global
1132
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1133 3d3081ec Andrew MacIsaac
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1134 c61e4626 Ermal Lu?i
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1135 d6b4dfe3 jim-p
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1136
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1137 55eb9c44 --global
1138 d672403c derelict-pf
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1139 ff500c90 jim-p
		if (!(@ldap_start_tls($ldap))) {
1140 d672403c derelict-pf
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not STARTTLS to server %s."), $ldapname));
1141
			@ldap_close($ldap);
1142
			return false;
1143
		}
1144
	}
1145
1146 a5cd1c5a jim-p
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1147
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1148 c61e4626 Ermal Lu?i
	if ($ldapanon == true) {
1149 1e0b1727 Phil Davis
		if (!($res = @ldap_bind($ldap))) {
1150 94021404 Carlos Eduardo Ramos
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind anonymously to server %s."), $ldapname));
1151 6306b5dd Ermal Lu?i
			@ldap_close($ldap);
1152 1e0b1727 Phil Davis
			return $ous;
1153 c61e4626 Ermal Lu?i
		}
1154
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1155 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind to server %s."), $ldapname));
1156 6306b5dd Ermal Lu?i
		@ldap_close($ldap);
1157 c61e4626 Ermal Lu?i
		return $ous;
1158 55eb9c44 --global
	}
1159
1160 1e0b1727 Phil Davis
	if ($ldapscope == "one") {
1161 c61e4626 Ermal Lu?i
		$ldapfunc = "ldap_list";
1162 1e0b1727 Phil Davis
	} else {
1163 c61e4626 Ermal Lu?i
		$ldapfunc = "ldap_search";
1164 1e0b1727 Phil Davis
	}
1165 55eb9c44 --global
1166 7a938f1b Ermal
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
1167
	$info = @ldap_get_entries($ldap, $search);
1168 55eb9c44 --global
1169
	if (is_array($info)) {
1170
		foreach ($info as $inf) {
1171
			if (!$show_complete_ou) {
1172 cfbfd941 smos
				$inf_split = explode(",", $inf['dn']);
1173 55eb9c44 --global
				$ou = $inf_split[0];
1174 4de8f7ba Phil Davis
				$ou = str_replace("OU=", "", $ou);
1175
				$ou = str_replace("CN=", "", $ou);
1176 1e0b1727 Phil Davis
			} else {
1177
				if ($inf['dn']) {
1178 55eb9c44 --global
					$ou = $inf['dn'];
1179 1e0b1727 Phil Davis
				}
1180
			}
1181
			if ($ou) {
1182 55eb9c44 --global
				$ous[] = $ou;
1183 1e0b1727 Phil Davis
			}
1184 55eb9c44 --global
		}
1185
	}
1186
1187 6306b5dd Ermal Lu?i
	@ldap_unbind($ldap);
1188
1189 55eb9c44 --global
	return $ous;
1190
}
1191
1192 6306b5dd Ermal Lu?i
function ldap_get_groups($username, $authcfg) {
1193 55eb9c44 --global
	global $debug, $config;
1194 1180e4f0 Sjon Hortensius
1195 1e0b1727 Phil Davis
	if (!function_exists("ldap_connect")) {
1196 55eb9c44 --global
		return;
1197 1e0b1727 Phil Davis
	}
1198 1180e4f0 Sjon Hortensius
1199 1e0b1727 Phil Davis
	if (!$username) {
1200 55eb9c44 --global
		return false;
1201 1e0b1727 Phil Davis
	}
1202 55eb9c44 --global
1203 1e0b1727 Phil Davis
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1204 2ce660ad smos
		$username_split = explode("@", $username);
1205 1180e4f0 Sjon Hortensius
		$username = $username_split[0];
1206 55eb9c44 --global
	}
1207
1208 1e0b1727 Phil Davis
	if (stristr($username, "\\")) {
1209 cfbfd941 smos
		$username_split = explode("\\", $username);
1210 1180e4f0 Sjon Hortensius
		$username = $username_split[0];
1211
	}
1212
1213 55eb9c44 --global
	//log_error("Getting LDAP groups for {$username}.");
1214 1e0b1727 Phil Davis
	if ($authcfg) {
1215 d672403c derelict-pf
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1216 1e0b1727 Phil Davis
			$ldapproto = "ldaps";
1217 d672403c derelict-pf
		} else {
1218
			$ldapproto = "ldap";
1219 1e0b1727 Phil Davis
		}
1220
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1221
		$ldapport = $authcfg['ldap_port'];
1222
		if (!empty($ldapport)) {
1223 9f27de6d jim-p
			$ldapserver .= ":{$ldapport}";
1224 1e0b1727 Phil Davis
		}
1225
		$ldapbasedn = $authcfg['ldap_basedn'];
1226
		$ldapbindun = $authcfg['ldap_binddn'];
1227
		$ldapbindpw = $authcfg['ldap_bindpw'];
1228
		$ldapauthcont = $authcfg['ldap_authcn'];
1229
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1230
		$ldapgroupattribute = strtolower($authcfg['ldap_attr_member']);
1231 149efbea jim-p
		if (isset($authcfg['ldap_rfc2307'])) {
1232
			$ldapfilter         = "(&(objectClass={$authcfg['ldap_attr_groupobj']})({$ldapgroupattribute}={$username}))";
1233
		} else {
1234
			$ldapfilter         = "({$ldapnameattribute}={$username})";
1235
		}
1236 1e0b1727 Phil Davis
		$ldaptype = "";
1237
		$ldapver = $authcfg['ldap_protver'];
1238
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1239
			$ldapanon = true;
1240
		} else {
1241
			$ldapanon = false;
1242
		}
1243
		$ldapname = $authcfg['name'];
1244
		$ldapfallback = false;
1245
		$ldapscope = $authcfg['ldap_scope'];
1246 e8c09a23 Chris Buechler
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1247 1e0b1727 Phil Davis
	} else {
1248 6306b5dd Ermal Lu?i
		return false;
1249 1e0b1727 Phil Davis
	}
1250 c61e4626 Ermal Lu?i
1251 149efbea jim-p
	if (isset($authcfg['ldap_rfc2307'])) {
1252
		$ldapdn = $ldapbasedn;
1253
	} else {
1254
		$ldapdn = $_SESSION['ldapdn'];
1255
	}
1256 c61e4626 Ermal Lu?i
1257 55eb9c44 --global
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
1258
	$ldapgroupattribute = strtolower($ldapgroupattribute);
1259 c61e4626 Ermal Lu?i
	$memberof = array();
1260 55eb9c44 --global
1261 1e0b1727 Phil Davis
	/* Setup CA environment if needed. */
1262
	ldap_setup_caenv($authcfg);
1263 fe2031ab Ermal
1264 55eb9c44 --global
	/* connect and see if server is up */
1265 c61e4626 Ermal Lu?i
	$error = false;
1266 1e0b1727 Phil Davis
	if (!($ldap = ldap_connect($ldapserver))) {
1267 9f27de6d jim-p
		$error = true;
1268 1e0b1727 Phil Davis
	}
1269 c61e4626 Ermal Lu?i
1270
	if ($error == true) {
1271 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("ERROR! ldap_get_groups() Could not connect to server %s."), $ldapname));
1272 0241b34f Phil Davis
		return $memberof;
1273 1e0b1727 Phil Davis
	}
1274 1180e4f0 Sjon Hortensius
1275 55eb9c44 --global
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1276 3d3081ec Andrew MacIsaac
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1277 c61e4626 Ermal Lu?i
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1278 d6b4dfe3 jim-p
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1279
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1280 55eb9c44 --global
1281 d672403c derelict-pf
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1282 ff500c90 jim-p
		if (!(@ldap_start_tls($ldap))) {
1283 d672403c derelict-pf
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not STARTTLS to server %s."), $ldapname));
1284
			@ldap_close($ldap);
1285
			return false;
1286
		}
1287
	}
1288
1289 55eb9c44 --global
	/* bind as user that has rights to read group attributes */
1290 a5cd1c5a jim-p
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1291
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1292 c61e4626 Ermal Lu?i
	if ($ldapanon == true) {
1293 1e0b1727 Phil Davis
		if (!($res = @ldap_bind($ldap))) {
1294 94021404 Carlos Eduardo Ramos
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind anonymously to server %s."), $ldapname));
1295 6306b5dd Ermal Lu?i
			@ldap_close($ldap);
1296 1e0b1727 Phil Davis
			return false;
1297 6306b5dd Ermal Lu?i
		}
1298 c61e4626 Ermal Lu?i
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1299 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind to server %s."), $ldapname));
1300 6306b5dd Ermal Lu?i
		@ldap_close($ldap);
1301 0241b34f Phil Davis
		return $memberof;
1302 55eb9c44 --global
	}
1303
1304
	/* get groups from DN found */
1305
	/* use ldap_read instead of search so we don't have to do a bunch of extra work */
1306
	/* since we know the DN is in $_SESSION['ldapdn'] */
1307
	//$search    = ldap_read($ldap, $ldapdn, "(objectclass=*)", array($ldapgroupattribute));
1308 1e0b1727 Phil Davis
	if ($ldapscope == "one") {
1309
		$ldapfunc = "ldap_list";
1310
	} else {
1311
		$ldapfunc = "ldap_search";
1312
	}
1313 c61e4626 Ermal Lu?i
1314 1e0b1727 Phil Davis
	$search = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
1315
	$info = @ldap_get_entries($ldap, $search);
1316 55eb9c44 --global
1317 149efbea jim-p
	$gresults = isset($authcfg['ldap_rfc2307']) ? $info : $info[0][$ldapgroupattribute];
1318 1180e4f0 Sjon Hortensius
1319 4e322e2c Phil Davis
	if (is_array($gresults)) {
1320 55eb9c44 --global
		/* Iterate through the groups and throw them into an array */
1321 149efbea jim-p
		foreach ($gresults as $grp) {
1322 4e322e2c Phil Davis
			if (((isset($authcfg['ldap_rfc2307'])) && (stristr($grp["dn"], "CN=") !== false)) ||
1323
			    ((!isset($authcfg['ldap_rfc2307'])) && (stristr($grp, "CN=") !== false))) {
1324 149efbea jim-p
				$grpsplit = isset($authcfg['ldap_rfc2307']) ? explode(",", $grp["dn"]) : explode(",", $grp);
1325
				$memberof[] = preg_replace("/CN=/i", "", $grpsplit[0]);
1326 55eb9c44 --global
			}
1327
		}
1328
	}
1329 1180e4f0 Sjon Hortensius
1330 55eb9c44 --global
	/* Time to close LDAP connection */
1331 6306b5dd Ermal Lu?i
	@ldap_unbind($ldap);
1332 1180e4f0 Sjon Hortensius
1333 4de8f7ba Phil Davis
	$groups = print_r($memberof, true);
1334 1180e4f0 Sjon Hortensius
1335 55eb9c44 --global
	//log_error("Returning groups ".$groups." for user $username");
1336 1180e4f0 Sjon Hortensius
1337 55eb9c44 --global
	return $memberof;
1338
}
1339
1340 83e0d4c8 jim-p
function ldap_format_host($host) {
1341
	return is_ipaddrv6($host) ? "[$host]" : $host ;
1342
}
1343
1344 eb43c5b1 Augustin FL
function ldap_backed($username, $passwd, $authcfg, &$attributes = array()) {
1345 55eb9c44 --global
	global $debug, $config;
1346 1180e4f0 Sjon Hortensius
1347 1e0b1727 Phil Davis
	if (!$username) {
1348 eb43c5b1 Augustin FL
		$attributes['error_message'] = gettext("Invalid Login.");
1349
		return false;
1350 1e0b1727 Phil Davis
	}
1351 55eb9c44 --global
1352 1e0b1727 Phil Davis
	if (!function_exists("ldap_connect")) {
1353 eb43c5b1 Augustin FL
		log_error(gettext("ERROR! unable to find ldap_connect() function."));
1354
		$attributes['error_message'] = gettext("Internal error during authentication.");
1355
		return null;
1356 1e0b1727 Phil Davis
	}
1357 55eb9c44 --global
1358 1e0b1727 Phil Davis
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1359 2ce660ad smos
		$username_split = explode("@", $username);
1360 1180e4f0 Sjon Hortensius
		$username = $username_split[0];
1361 55eb9c44 --global
	}
1362 1e0b1727 Phil Davis
	if (stristr($username, "\\")) {
1363 cfbfd941 smos
		$username_split = explode("\\", $username);
1364 1180e4f0 Sjon Hortensius
		$username = $username_split[0];
1365 55eb9c44 --global
	}
1366
1367 f0b0a03b jim-p
	$username = ldap_escape($username, null, LDAP_ESCAPE_FILTER);
1368
1369 c61e4626 Ermal Lu?i
	if ($authcfg) {
1370 d672403c derelict-pf
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1371 c61e4626 Ermal Lu?i
			$ldapproto = "ldaps";
1372 d672403c derelict-pf
		} else {
1373
			$ldapproto = "ldap";
1374 1e0b1727 Phil Davis
		}
1375
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1376
		$ldapport = $authcfg['ldap_port'];
1377
		if (!empty($ldapport)) {
1378 9f27de6d jim-p
			$ldapserver .= ":{$ldapport}";
1379 1e0b1727 Phil Davis
		}
1380
		$ldapbasedn = $authcfg['ldap_basedn'];
1381
		$ldapbindun = $authcfg['ldap_binddn'];
1382
		$ldapbindpw = $authcfg['ldap_bindpw'];
1383
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1384 c61e4626 Ermal Lu?i
			$ldapanon = true;
1385 1e0b1727 Phil Davis
		} else {
1386 c61e4626 Ermal Lu?i
			$ldapanon = false;
1387 1e0b1727 Phil Davis
		}
1388
		$ldapauthcont = $authcfg['ldap_authcn'];
1389
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1390
		$ldapextendedqueryenabled = $authcfg['ldap_extended_enabled'];
1391
		$ldapextendedquery = $authcfg['ldap_extended_query'];
1392
		$ldapfilter = "";
1393
		if (!$ldapextendedqueryenabled) {
1394
			$ldapfilter = "({$ldapnameattribute}={$username})";
1395
		} else {
1396
			$ldapfilter = "(&({$ldapnameattribute}={$username})({$ldapextendedquery}))";
1397
		}
1398
		$ldaptype = "";
1399
		$ldapver = $authcfg['ldap_protver'];
1400
		$ldapname = $authcfg['name'];
1401
		$ldapscope = $authcfg['ldap_scope'];
1402 e8c09a23 Chris Buechler
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1403 1e0b1727 Phil Davis
	} else {
1404 eb43c5b1 Augustin FL
		return null;
1405 1e0b1727 Phil Davis
	}
1406 55eb9c44 --global
1407 1180e4f0 Sjon Hortensius
	/* first check if there is even an LDAP server populated */
1408 1e0b1727 Phil Davis
	if (!$ldapserver) {
1409 eb43c5b1 Augustin FL
		log_error(gettext("ERROR! could not find details of the LDAP server used for authentication."));
1410
		$attributes['error_message'] =  gettext("Internal error during authentication.");
1411
		return null;
1412 55eb9c44 --global
	}
1413 1180e4f0 Sjon Hortensius
1414 1e0b1727 Phil Davis
	/* Setup CA environment if needed. */
1415
	ldap_setup_caenv($authcfg);
1416 fe2031ab Ermal
1417 d672403c derelict-pf
	/* Make sure we can connect to LDAP */
1418
	$error = false;
1419
	if (!($ldap = ldap_connect($ldapserver))) {
1420
		$error = true;
1421
	}
1422
1423 906daddc Ermal
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1424 3d3081ec Andrew MacIsaac
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1425 906daddc Ermal
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1426 d6b4dfe3 jim-p
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1427
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1428 906daddc Ermal
1429 d672403c derelict-pf
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1430 b2c7a79c jim-p
		if (!(@ldap_start_tls($ldap))) {
1431 eb43c5b1 Augustin FL
			log_error(sprintf(gettext("ERROR! could not connect to LDAP server %s using STARTTLS."), $ldapname));
1432
			$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1433 d672403c derelict-pf
			@ldap_close($ldap);
1434 eb43c5b1 Augustin FL
			return null;
1435 d672403c derelict-pf
		}
1436 1e0b1727 Phil Davis
	}
1437 c61e4626 Ermal Lu?i
1438
	if ($error == true) {
1439 eb43c5b1 Augustin FL
		$errormsg = sprintf(gettext("ERROR! Could not connect to server %s."), $ldapname);
1440
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1441
		return null;
1442 55eb9c44 --global
	}
1443 c61e4626 Ermal Lu?i
1444 55eb9c44 --global
	/* ok, its up.  now, lets bind as the bind user so we can search it */
1445 c61e4626 Ermal Lu?i
	$error = false;
1446 a5cd1c5a jim-p
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1447
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1448 c61e4626 Ermal Lu?i
	if ($ldapanon == true) {
1449 1e0b1727 Phil Davis
		if (!($res = @ldap_bind($ldap))) {
1450
			$error = true;
1451
		}
1452
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1453 c61e4626 Ermal Lu?i
		$error = true;
1454 1e0b1727 Phil Davis
	}
1455 c61e4626 Ermal Lu?i
1456
	if ($error == true) {
1457 6306b5dd Ermal Lu?i
		@ldap_close($ldap);
1458 eb43c5b1 Augustin FL
		log_error(sprintf(gettext("ERROR! Could not bind to LDAP server %s. Please check the bind credentials."), $ldapname));
1459
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1460
		return null;
1461 55eb9c44 --global
	}
1462 1180e4f0 Sjon Hortensius
1463 55eb9c44 --global
	/* Get LDAP Authcontainers and split em up. */
1464 cfbfd941 smos
	$ldac_splits = explode(";", $ldapauthcont);
1465 1180e4f0 Sjon Hortensius
1466 086cf944 Phil Davis
	/* setup the usercount so we think we haven't found anyone yet */
1467 4de8f7ba Phil Davis
	$usercount = 0;
1468 55eb9c44 --global
1469
	/*****************************************************************/
1470 6990ad35 Phil Davis
	/*  We first find the user based on username and filter          */
1471
	/*  then, once we find the first occurrence of that person       */
1472
	/*  we set session variables to point to the OU and DN of the    */
1473
	/*  person.  To later be used by ldap_get_groups.                */
1474 55eb9c44 --global
	/*  that way we don't have to search twice.                      */
1475
	/*****************************************************************/
1476 1e0b1727 Phil Davis
	if ($debug) {
1477 3ac8324f Ermal
		log_auth(sprintf(gettext("Now Searching for %s in directory."), $username));
1478 1e0b1727 Phil Davis
	}
1479 c61e4626 Ermal Lu?i
	/* Iterate through the user containers for search */
1480
	foreach ($ldac_splits as $i => $ldac_split) {
1481 a5cd1c5a jim-p
		$ldac_split = isset($authcfg['ldap_utf8']) ? utf8_encode($ldac_split) : $ldac_split;
1482
		$ldapfilter = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapfilter) : $ldapfilter;
1483
		$ldapsearchbasedn = isset($authcfg['ldap_utf8']) ? utf8_encode("{$ldac_split},{$ldapbasedn}") : "{$ldac_split},{$ldapbasedn}";
1484 c61e4626 Ermal Lu?i
		/* Make sure we just use the first user we find */
1485 1e0b1727 Phil Davis
		if ($debug) {
1486 a5cd1c5a jim-p
			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)));
1487 1e0b1727 Phil Davis
		}
1488
		if ($ldapscope == "one") {
1489 c61e4626 Ermal Lu?i
			$ldapfunc = "ldap_list";
1490 1e0b1727 Phil Davis
		} else {
1491 c61e4626 Ermal Lu?i
			$ldapfunc = "ldap_search";
1492 1e0b1727 Phil Davis
		}
1493 c61e4626 Ermal Lu?i
		/* Support legacy auth container specification. */
1494 1e0b1727 Phil Davis
		if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) {
1495 6990ad35 Phil Davis
			$search = @$ldapfunc($ldap, $ldac_split, $ldapfilter);
1496 1e0b1727 Phil Davis
		} else {
1497 6990ad35 Phil Davis
			$search = @$ldapfunc($ldap, $ldapsearchbasedn, $ldapfilter);
1498 1e0b1727 Phil Davis
		}
1499 c61e4626 Ermal Lu?i
		if (!$search) {
1500 94021404 Carlos Eduardo Ramos
			log_error(sprintf(gettext("Search resulted in error: %s"), ldap_error($ldap)));
1501 c61e4626 Ermal Lu?i
			continue;
1502 55eb9c44 --global
		}
1503 4de8f7ba Phil Davis
		$info = ldap_get_entries($ldap, $search);
1504 c61e4626 Ermal Lu?i
		$matches = $info['count'];
1505 1e0b1727 Phil Davis
		if ($matches == 1) {
1506 c61e4626 Ermal Lu?i
			$userdn = $_SESSION['ldapdn'] = $info[0]['dn'];
1507
			$_SESSION['ldapou'] = $ldac_split[$i];
1508
			$_SESSION['ldapon'] = "true";
1509
			$usercount = 1;
1510
			break;
1511 55eb9c44 --global
		}
1512
	}
1513
1514 1e0b1727 Phil Davis
	if ($usercount != 1) {
1515 6306b5dd Ermal Lu?i
		@ldap_unbind($ldap);
1516 eb43c5b1 Augustin FL
		if ($debug) {
1517
			if ($usercount === 0) {
1518
				log_error(sprintf(gettext("ERROR! LDAP search failed, no user matching %s was found."), $username));
1519
			} else {
1520
				log_error(sprintf(gettext("ERROR! LDAP search failed, multiple users matching %s were found."), $username));
1521
			}
1522
		}
1523
		$attributes['error_message'] = gettext("Invalid login specified.");
1524 1180e4f0 Sjon Hortensius
		return false;
1525 55eb9c44 --global
	}
1526 c61e4626 Ermal Lu?i
1527 55eb9c44 --global
	/* Now lets bind as the user we found */
1528 a5cd1c5a jim-p
	$passwd = isset($authcfg['ldap_utf8']) ? utf8_encode($passwd) : $passwd;
1529 c61e4626 Ermal Lu?i
	if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
1530 eb43c5b1 Augustin FL
		if ($debug) {
1531
			log_error(sprintf(gettext('ERROR! Could not login to server %1$s as user %2$s: %3$s'), $ldapname, $username, ldap_error($ldap)));
1532
		}
1533 6306b5dd Ermal Lu?i
		@ldap_unbind($ldap);
1534 c61e4626 Ermal Lu?i
		return false;
1535 55eb9c44 --global
	}
1536
1537 a5cd1c5a jim-p
	if ($debug) {
1538
		$userdn = isset($authcfg['ldap_utf8']) ? utf8_decode($userdn) : $userdn;
1539 2004def5 Ermal
		log_auth(sprintf(gettext('Logged in successfully as %1$s via LDAP server %2$s with DN = %3$s.'), $username, $ldapname, $userdn));
1540 a5cd1c5a jim-p
	}
1541 c61e4626 Ermal Lu?i
1542
	/* At this point we are bound to LDAP so the user was auth'd okay. Close connection. */
1543 6306b5dd Ermal Lu?i
	@ldap_unbind($ldap);
1544 55eb9c44 --global
1545
	return true;
1546
}
1547
1548 9da4a575 Renato Botelho
function radius_backed($username, $password, $authcfg, &$attributes = array()) {
1549 a13ce628 Ermal Lu?i
	global $debug, $config;
1550 55eb9c44 --global
	$ret = false;
1551
1552 49ec9d91 Renato Botelho
	require_once("Auth/RADIUS.php");
1553 9da4a575 Renato Botelho
	require_once("Crypt/CHAP.php");
1554 868c6826 Ermal
1555 c61e4626 Ermal Lu?i
	if ($authcfg) {
1556
		$radiusservers = array();
1557
		$radiusservers[0]['ipaddr'] = $authcfg['host'];
1558
		$radiusservers[0]['port'] = $authcfg['radius_auth_port'];
1559
		$radiusservers[0]['sharedsecret'] = $authcfg['radius_secret'];
1560 bddd2be8 jim-p
		$radiusservers[0]['timeout'] = $authcfg['radius_timeout'];
1561 9da4a575 Renato Botelho
		if(isset($authcfg['radius_protocol'])) {
1562
			$radius_protocol = $authcfg['radius_protocol'];
1563
		} else {
1564
			$radius_protocol = 'PAP';
1565
		}
1566 1e0b1727 Phil Davis
	} else {
1567 f15fdef3 Augustin FL
		log_error(gettext("ERROR! could not find details of the RADIUS server used for authentication."));
1568
		$attributes['error_message'] =  gettext("Internal error during authentication.");
1569
		return null;
1570 1e0b1727 Phil Davis
	}
1571 c61e4626 Ermal Lu?i
1572 9da4a575 Renato Botelho
	// Create our instance
1573
	$classname = 'Auth_RADIUS_' . $radius_protocol;
1574
	$rauth = new $classname($username, $password);
1575
1576 1e0b1727 Phil Davis
	/* Add new servers to our instance */
1577 bddd2be8 jim-p
	foreach ($radiusservers as $radsrv) {
1578
		$timeout = (is_numeric($radsrv['timeout'])) ? $radsrv['timeout'] : 5;
1579
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret'], $timeout);
1580
	}
1581 55eb9c44 --global
1582 9da4a575 Renato Botelho
	// Construct data package
1583
	$rauth->username = $username;
1584
	switch ($radius_protocol) {
1585
		case 'CHAP_MD5':
1586
		case 'MSCHAPv1':
1587
			$classname = $radius_protocol == 'MSCHAPv1' ? 'Crypt_CHAP_MSv1' : 'Crypt_CHAP_MD5';
1588
			$crpt = new $classname;
1589
			$crpt->username = $username;
1590
			$crpt->password = $password;
1591
			$rauth->challenge = $crpt->challenge;
1592
			$rauth->chapid = $crpt->chapid;
1593
			$rauth->response = $crpt->challengeResponse();
1594
			$rauth->flags = 1;
1595
			break;
1596
1597
		case 'MSCHAPv2':
1598
			$crpt = new Crypt_CHAP_MSv2;
1599
			$crpt->username = $username;
1600
			$crpt->password = $password;
1601
			$rauth->challenge = $crpt->authChallenge;
1602
			$rauth->peerChallenge = $crpt->peerChallenge;
1603
			$rauth->chapid = $crpt->chapid;
1604
			$rauth->response = $crpt->challengeResponse();
1605
			break;
1606
1607
		default:
1608
			$rauth->password = $password;
1609
			break;
1610
	}
1611
1612 6e815096 Ermal
	if (PEAR::isError($rauth->start())) {
1613 f15fdef3 Augustin FL
		$ret = null;
1614
		log_error(sprintf(gettext("Error during RADIUS authentication : %s"), $rauth->getError()));
1615
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1616
	} else {
1617
		$nasid = $attributes['nas_identifier'];
1618
		$nasip = $authcfg['radius_nasip_attribute'];
1619
		if (empty($nasid)) {
1620
			$nasid = gethostname(); //If no RADIUS NAS-Identifier is given : we use pfsense's hostname as NAS-Identifier
1621
		}
1622
		if (!is_ipaddr($nasip)) {
1623
			$nasip = get_interface_ip($nasip);
1624
			
1625
			if (!is_ipaddr($nasip)) {
1626
				$nasip = get_interface_ip();//We use wan interface IP as fallback for NAS-IP-Address
1627
			}
1628
		}
1629
		$nasmac = get_interface_mac(find_ip_interface($nasip));
1630
1631
		$rauth->putAttribute(RADIUS_NAS_IP_ADDRESS, $nasip, "addr");
1632
		$rauth->putAttribute(RADIUS_NAS_IDENTIFIER, $nasid);
1633
		
1634
		if(!empty($attributes['calling_station_id'])) {
1635
			$rauth->putAttribute(RADIUS_CALLING_STATION_ID, $attributes['calling_station_id']);
1636
		}
1637
		// Carefully check that interface has a MAC address
1638
		if(!empty($nasmac)) {
1639
			$nasmac = mac_format($nasmac);
1640
			$rauth->putAttribute(RADIUS_CALLED_STATION_ID, $nasmac.':'.gethostname());
1641
		}
1642
		if(!empty($attributes['nas_port_type'])) {
1643
			$rauth->putAttribute(RADIUS_NAS_PORT_TYPE, $attributes['nas_port_type']);
1644
		}		
1645
		if(!empty($attributes['nas_port'])) {
1646
			$rauth->putAttribute(RADIUS_NAS_PORT, intval($attributes['nas_port']), 'integer');
1647
		}
1648
		if(!empty($attributes['framed_ip']) && is_ipaddr($attributes['framed_ip'])) {
1649
			$rauth->putAttribute(RADIUS_FRAMED_IP_ADDRESS, $attributes['framed_ip'], "addr");
1650 1e0b1727 Phil Davis
		}
1651 55eb9c44 --global
	}
1652
1653
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1654
1655
	/* Send request */
1656
	$result = $rauth->send();
1657
	if (PEAR::isError($result)) {
1658 f15fdef3 Augustin FL
		log_error(sprintf(gettext("Error during RADIUS authentication : %s"), $rauth->getError()));
1659
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1660
		$ret = null;
1661 55eb9c44 --global
	} else if ($result === true) {
1662
		$ret = true;
1663
	} else {
1664 f15fdef3 Augustin FL
		$ret = false;
1665 55eb9c44 --global
	}
1666
1667 f15fdef3 Augustin FL
	
1668
	// Get attributes, even if auth failed.
1669
	if ($rauth->getAttributes()) {
1670
	$attributes = array_merge($attributes,$rauth->listAttributes());
1671
1672
	// We convert the session_terminate_time to unixtimestamp if its set before returning the whole array to our caller
1673
	if (!empty($attributes['session_terminate_time'])) {
1674
			$stt = &$attributes['session_terminate_time'];
1675
			$stt = strtotime(preg_replace("/\+(\d+):(\d+)$/", " +\${1}\${2}", preg_replace("/(\d+)T(\d+)/", "\${1} \${2}",$stt)));
1676
		}
1677
	}
1678
	
1679
	// close OO RADIUS_AUTHENTICATION
1680 55eb9c44 --global
	$rauth->close();
1681
1682
	return $ret;
1683
}
1684
1685 c4a9f99a jim-p
/*
1686
	$attributes must contain a "class" key containing the groups and local
1687
	groups must exist to match.
1688
*/
1689
function radius_get_groups($attributes) {
1690
	$groups = array();
1691 461bae6b jim-p
	if (!empty($attributes) && is_array($attributes) && (!empty($attributes['class']) || !empty($attributes['class_int']))) {
1692
		/* Some RADIUS servers return multiple class attributes, so check them all. */
1693
		$groups = array();
1694
		if (!empty($attributes['class']) && is_array($attributes['class'])) {
1695
			foreach ($attributes['class'] as $class) {
1696
				$groups = array_unique(array_merge($groups, explode(";", $class)));
1697
			}
1698
		}
1699
1700 c4a9f99a jim-p
		foreach ($groups as & $grp) {
1701 916fc1f8 jim-p
			$grp = trim($grp);
1702
			if (strtolower(substr($grp, 0, 3)) == "ou=") {
1703 c4a9f99a jim-p
				$grp = substr($grp, 3);
1704
			}
1705
		}
1706
	}
1707
	return $groups;
1708
}
1709
1710 7dd044f2 sullrich
function get_user_expiration_date($username) {
1711 a13ce628 Ermal Lu?i
	$user = getUserEntry($username);
1712 1e0b1727 Phil Davis
	if ($user['expires']) {
1713 a13ce628 Ermal Lu?i
		return $user['expires'];
1714 1e0b1727 Phil Davis
	}
1715 a13ce628 Ermal Lu?i
}
1716
1717
function is_account_expired($username) {
1718
	$expirydate = get_user_expiration_date($username);
1719
	if ($expirydate) {
1720 4de8f7ba Phil Davis
		if (strtotime("-1 day") > strtotime(date("m/d/Y", strtotime($expirydate)))) {
1721 a13ce628 Ermal Lu?i
			return true;
1722 1e0b1727 Phil Davis
		}
1723 7dd044f2 sullrich
	}
1724 a13ce628 Ermal Lu?i
1725
	return false;
1726 7dd044f2 sullrich
}
1727
1728 b4bfd25d sullrich
function is_account_disabled($username) {
1729 a13ce628 Ermal Lu?i
	$user = getUserEntry($username);
1730 1e0b1727 Phil Davis
	if (isset($user['disabled'])) {
1731 a13ce628 Ermal Lu?i
		return true;
1732 1e0b1727 Phil Davis
	}
1733 a13ce628 Ermal Lu?i
1734 b4bfd25d sullrich
	return false;
1735
}
1736
1737 8bab524e Phil Davis
function get_user_settings($username) {
1738
	global $config;
1739
	$settings = array();
1740
	$settings['widgets'] = $config['widgets'];
1741
	$settings['webgui']['dashboardcolumns'] = $config['system']['webgui']['dashboardcolumns'];
1742
	$settings['webgui']['webguihostnamemenu'] = $config['system']['webgui']['webguihostnamemenu'];
1743
	$settings['webgui']['webguicss'] = $config['system']['webgui']['webguicss'];
1744 e79ff1ee Steve Beaver
	$settings['webgui']['logincss'] = $config['system']['webgui']['logincss'];
1745 1d3510cf Phil Davis
	$settings['webgui']['interfacessort'] = isset($config['system']['webgui']['interfacessort']);
1746 8bab524e Phil Davis
	$settings['webgui']['dashboardavailablewidgetspanel'] = isset($config['system']['webgui']['dashboardavailablewidgetspanel']);
1747
	$settings['webgui']['webguifixedmenu'] = isset($config['system']['webgui']['webguifixedmenu']);
1748
	$settings['webgui']['webguileftcolumnhyper'] = isset($config['system']['webgui']['webguileftcolumnhyper']);
1749 d9058974 Phil Davis
	$settings['webgui']['disablealiaspopupdetail'] = isset($config['system']['webgui']['disablealiaspopupdetail']);
1750 8bab524e Phil Davis
	$settings['webgui']['systemlogsfilterpanel'] = isset($config['system']['webgui']['systemlogsfilterpanel']);
1751
	$settings['webgui']['systemlogsmanagelogpanel'] = isset($config['system']['webgui']['systemlogsmanagelogpanel']);
1752
	$settings['webgui']['statusmonitoringsettingspanel'] = isset($config['system']['webgui']['statusmonitoringsettingspanel']);
1753
	$settings['webgui']['pagenamefirst'] = isset($config['system']['webgui']['pagenamefirst']);
1754
	$user = getUserEntry($username);
1755
	if (isset($user['customsettings'])) {
1756
		$settings['customsettings'] = true;
1757
		if (isset($user['widgets'])) {
1758
			// This includes the 'sequence', and any widgetname-config per-widget settings.
1759
			$settings['widgets'] = $user['widgets'];
1760
		}
1761
		if (isset($user['dashboardcolumns'])) {
1762
			$settings['webgui']['dashboardcolumns'] = $user['dashboardcolumns'];
1763
		}
1764
		if (isset($user['webguicss'])) {
1765
			$settings['webgui']['webguicss'] = $user['webguicss'];
1766
		}
1767
		if (isset($user['webguihostnamemenu'])) {
1768
			$settings['webgui']['webguihostnamemenu'] = $user['webguihostnamemenu'];
1769
		}
1770 1d3510cf Phil Davis
		$settings['webgui']['interfacessort'] = isset($user['interfacessort']);
1771 8bab524e Phil Davis
		$settings['webgui']['dashboardavailablewidgetspanel'] = isset($user['dashboardavailablewidgetspanel']);
1772
		$settings['webgui']['webguifixedmenu'] = isset($user['webguifixedmenu']);
1773
		$settings['webgui']['webguileftcolumnhyper'] = isset($user['webguileftcolumnhyper']);
1774 d9058974 Phil Davis
		$settings['webgui']['disablealiaspopupdetail'] = isset($user['disablealiaspopupdetail']);
1775 8bab524e Phil Davis
		$settings['webgui']['systemlogsfilterpanel'] = isset($user['systemlogsfilterpanel']);
1776
		$settings['webgui']['systemlogsmanagelogpanel'] = isset($user['systemlogsmanagelogpanel']);
1777
		$settings['webgui']['statusmonitoringsettingspanel'] = isset($user['statusmonitoringsettingspanel']);
1778
		$settings['webgui']['pagenamefirst'] = isset($user['pagenamefirst']);
1779
	} else {
1780
		$settings['customsettings'] = false;
1781
	}
1782
1783
	if ($settings['webgui']['dashboardcolumns'] < 1) {
1784
		$settings['webgui']['dashboardcolumns'] = 2;
1785
	}
1786
1787
	return $settings;
1788
}
1789
1790 2b7d0520 Phil Davis
function save_widget_settings($username, $settings, $message = "") {
1791 8bab524e Phil Davis
	global $config, $userindex;
1792
	$user = getUserEntry($username);
1793 2b7d0520 Phil Davis
1794
	if (strlen($message) > 0) {
1795
		$msgout = $message;
1796
	} else {
1797
		$msgout = gettext("Widget configuration has been changed.");
1798
	}
1799
1800 8bab524e Phil Davis
	if (isset($user['customsettings'])) {
1801
		$config['system']['user'][$userindex[$username]]['widgets'] = $settings;
1802 2b7d0520 Phil Davis
		write_config($msgout . " " . sprintf(gettext("(User %s)"), $username));
1803 8bab524e Phil Davis
	} else {
1804
		$config['widgets'] = $settings;
1805 2b7d0520 Phil Davis
		write_config($msgout);
1806 8bab524e Phil Davis
	}
1807
}
1808
1809 c61e4626 Ermal Lu?i
function auth_get_authserver($name) {
1810 1e0b1727 Phil Davis
	global $config;
1811
1812
	if (is_array($config['system']['authserver'])) {
1813
		foreach ($config['system']['authserver'] as $authcfg) {
1814
			if ($authcfg['name'] == $name) {
1815
				return $authcfg;
1816
			}
1817
		}
1818
	}
1819
	if ($name == "Local Database") {
1820 96568521 Vinicius Coque
		return array("name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']);
1821 1e0b1727 Phil Davis
	}
1822 6306b5dd Ermal Lu?i
}
1823
1824
function auth_get_authserver_list() {
1825 1e0b1727 Phil Davis
	global $config;
1826 6306b5dd Ermal Lu?i
1827
	$list = array();
1828
1829 1e0b1727 Phil Davis
	if (is_array($config['system']['authserver'])) {
1830
		foreach ($config['system']['authserver'] as $authcfg) {
1831 6306b5dd Ermal Lu?i
			/* Add support for disabled entries? */
1832
			$list[$authcfg['name']] = $authcfg;
1833 1e0b1727 Phil Davis
		}
1834
	}
1835 6306b5dd Ermal Lu?i
1836 4de8f7ba Phil Davis
	$list["Local Database"] = array("name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']);
1837 6306b5dd Ermal Lu?i
	return $list;
1838 c61e4626 Ermal Lu?i
}
1839
1840 c4a9f99a jim-p
function getUserGroups($username, $authcfg, &$attributes = array()) {
1841 fb0f22c0 Ermal Lu?i
	global $config;
1842
1843
	$allowed_groups = array();
1844
1845 1e0b1727 Phil Davis
	switch ($authcfg['type']) {
1846
		case 'ldap':
1847
			$allowed_groups = @ldap_get_groups($username, $authcfg);
1848
			break;
1849
		case 'radius':
1850 c4a9f99a jim-p
			$allowed_groups = @radius_get_groups($attributes);
1851 1e0b1727 Phil Davis
			break;
1852
		default:
1853
			$user = getUserEntry($username);
1854
			$allowed_groups = @local_user_get_groups($user, true);
1855
			break;
1856 fb0f22c0 Ermal Lu?i
	}
1857
1858
	$member_groups = array();
1859 1e0b1727 Phil Davis
	if (is_array($config['system']['group'])) {
1860
		foreach ($config['system']['group'] as $group) {
1861
			if (in_array($group['name'], $allowed_groups)) {
1862 fb0f22c0 Ermal Lu?i
				$member_groups[] = $group['name'];
1863 1e0b1727 Phil Davis
			}
1864
		}
1865 fb0f22c0 Ermal Lu?i
	}
1866
1867
	return $member_groups;
1868
}
1869
1870 eb43c5b1 Augustin FL
/*
1871
Possible return values : 
1872
true : authentication worked
1873
false : authentication failed (invalid login/password, not enought permission, etc...)
1874
null : error during authentication process (unable to reach remote server, etc...)
1875
*/
1876 1492e02c Ermal
function authenticate_user($username, $password, $authcfg = NULL, &$attributes = array()) {
1877 c61e4626 Ermal Lu?i
1878 b7369ff8 NewEraCracker
	if (is_array($username) || is_array($password)) {
1879
		return false;
1880
	}
1881
1882 c61e4626 Ermal Lu?i
	if (!$authcfg) {
1883 eb43c5b1 Augustin FL
		return local_backed($username, $password, $attributes);
1884 c61e4626 Ermal Lu?i
	}
1885
1886
	$authenticated = false;
1887 1e0b1727 Phil Davis
	switch ($authcfg['type']) {
1888
		case 'ldap':
1889 eb43c5b1 Augustin FL
			$authenticated = ldap_backed($username, $password, $authcfg, $attributes);
1890 1e0b1727 Phil Davis
			break;
1891
		case 'radius':
1892 eb43c5b1 Augustin FL
			$authenticated = radius_backed($username, $password, $authcfg, $attributes);
1893 1e0b1727 Phil Davis
			break;
1894
		default:
1895
			/* lookup user object by name */
1896 eb43c5b1 Augustin FL
			$authenticated = local_backed($username, $password, $attributes);
1897 1e0b1727 Phil Davis
			break;
1898
		}
1899 c61e4626 Ermal Lu?i
1900
	return $authenticated;
1901
}
1902
1903 6306b5dd Ermal Lu?i
function session_auth() {
1904 aa205c3b Ermal
	global $config, $_SESSION, $page;
1905 55eb9c44 --global
1906 49ddf9a1 Warren Baker
	// Handle HTTPS httponly and secure flags
1907 16789caa Renato Botelho
	$currentCookieParams = session_get_cookie_params();
1908
	session_set_cookie_params(
1909
		$currentCookieParams["lifetime"],
1910
		$currentCookieParams["path"],
1911
		NULL,
1912
		($config['system']['webgui']['protocol'] == "https"),
1913
		true
1914
	);
1915 49ddf9a1 Warren Baker
1916 82cd6022 PiBa-NL
	phpsession_begin();
1917 55eb9c44 --global
1918 dd030de9 Renato Botelho
	// Detect protocol change
1919 1e0b1727 Phil Davis
	if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) {
1920 82cd6022 PiBa-NL
		phpsession_end();
1921 dd030de9 Renato Botelho
		return false;
1922 1e0b1727 Phil Davis
	}
1923 dd030de9 Renato Botelho
1924 55eb9c44 --global
	/* Validate incoming login request */
1925 c4a9f99a jim-p
	$attributes = array();
1926 88165371 Ermal
	if (isset($_POST['login']) && !empty($_POST['usernamefld']) && !empty($_POST['passwordfld'])) {
1927 6306b5dd Ermal Lu?i
		$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
1928 b77a6394 PiBa-NL
		$remoteauth = authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg, $attributes);
1929
		if ($remoteauth || authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) {
1930 526f5b11 Renato Botelho
			// Generate a new id to avoid session fixation
1931 8588095f Renato Botelho
			session_regenerate_id();
1932 6306b5dd Ermal Lu?i
			$_SESSION['Logged_In'] = "True";
1933 b77a6394 PiBa-NL
			$_SESSION['remoteauth'] = $remoteauth;
1934 6306b5dd Ermal Lu?i
			$_SESSION['Username'] = $_POST['usernamefld'];
1935 c4a9f99a jim-p
			$_SESSION['user_radius_attributes'] = $attributes;
1936 6306b5dd Ermal Lu?i
			$_SESSION['last_access'] = time();
1937 dd030de9 Renato Botelho
			$_SESSION['protocol'] = $config['system']['webgui']['protocol'];
1938 82cd6022 PiBa-NL
			phpsession_end(true);
1939 1e0b1727 Phil Davis
			if (!isset($config['system']['webgui']['quietlogin'])) {
1940 54bdff75 Vinicius Coque
				log_auth(sprintf(gettext("Successful login for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], $_SERVER['REMOTE_ADDR']));
1941 4fc3855f smos
			}
1942 1e0b1727 Phil Davis
			if (isset($_POST['postafterlogin'])) {
1943 92140621 Ermal
				return true;
1944 1e0b1727 Phil Davis
			} else {
1945
				if (empty($page)) {
1946 80b292f3 Ermal
					$page = "/";
1947 1e0b1727 Phil Davis
				}
1948 80b292f3 Ermal
				header("Location: {$page}");
1949
			}
1950 f23e6363 Ermal
			exit;
1951 a13ce628 Ermal Lu?i
		} else {
1952
			/* give the user an error message */
1953 ca44a37c Steve Beaver
			$_SESSION['Login_Error'] = gettext("Username or Password incorrect");
1954 65f7fba8 Scott Ullrich
			log_auth("webConfigurator authentication error for '{$_POST['usernamefld']}' from {$_SERVER['REMOTE_ADDR']}");
1955 1e0b1727 Phil Davis
			if (isAjax()) {
1956 a13ce628 Ermal Lu?i
				echo "showajaxmessage('{$_SESSION['Login_Error']}');";
1957
				return;
1958 55eb9c44 --global
			}
1959
		}
1960
	}
1961
1962
	/* Show login page if they aren't logged in */
1963 1e0b1727 Phil Davis
	if (empty($_SESSION['Logged_In'])) {
1964 82cd6022 PiBa-NL
		phpsession_end(true);
1965 55eb9c44 --global
		return false;
1966 1e0b1727 Phil Davis
	}
1967 55eb9c44 --global
1968
	/* If session timeout isn't set, we don't mark sessions stale */
1969 02647583 Ermal
	if (!isset($config['system']['webgui']['session_timeout'])) {
1970 bdadaf3c Chris Buechler
		/* Default to 4 hour timeout if one is not set */
1971
		if ($_SESSION['last_access'] < (time() - 14400)) {
1972 ce437697 Steve Beaver
			$_POST['logout'] = true;
1973 bdadaf3c Chris Buechler
			$_SESSION['Logout'] = true;
1974 1e0b1727 Phil Davis
		} else {
1975 1180e4f0 Sjon Hortensius
			$_SESSION['last_access'] = time();
1976 1e0b1727 Phil Davis
		}
1977 02647583 Ermal
	} else if (intval($config['system']['webgui']['session_timeout']) == 0) {
1978
		/* only update if it wasn't ajax */
1979 1e0b1727 Phil Davis
		if (!isAjax()) {
1980 02647583 Ermal
			$_SESSION['last_access'] = time();
1981 1e0b1727 Phil Davis
		}
1982 bdadaf3c Chris Buechler
	} else {
1983 55eb9c44 --global
		/* Check for stale session */
1984
		if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
1985 ce437697 Steve Beaver
			$_POST['logout'] = true;
1986 55eb9c44 --global
			$_SESSION['Logout'] = true;
1987
		} else {
1988
			/* only update if it wasn't ajax */
1989 1e0b1727 Phil Davis
			if (!isAjax()) {
1990 55eb9c44 --global
				$_SESSION['last_access'] = time();
1991 1e0b1727 Phil Davis
			}
1992 55eb9c44 --global
		}
1993
	}
1994
1995
	/* user hit the logout button */
1996 ce437697 Steve Beaver
	if (isset($_POST['logout'])) {
1997 55eb9c44 --global
1998 1e0b1727 Phil Davis
		if ($_SESSION['Logout']) {
1999 addc0439 Renato Botelho
			log_error(sprintf(gettext("Session timed out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR']));
2000 1e0b1727 Phil Davis
		} else {
2001 addc0439 Renato Botelho
			log_error(sprintf(gettext("User logged out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR']));
2002 1e0b1727 Phil Davis
		}
2003 55eb9c44 --global
2004
		/* wipe out $_SESSION */
2005
		$_SESSION = array();
2006
2007 1e0b1727 Phil Davis
		if (isset($_COOKIE[session_name()])) {
2008 55eb9c44 --global
			setcookie(session_name(), '', time()-42000, '/');
2009 1e0b1727 Phil Davis
		}
2010 55eb9c44 --global
2011
		/* and destroy it */
2012 82cd6022 PiBa-NL
		phpsession_destroy();
2013 55eb9c44 --global
2014 cfbfd941 smos
		$scriptName = explode("/", $_SERVER["SCRIPT_FILENAME"]);
2015 55eb9c44 --global
		$scriptElms = count($scriptName);
2016
		$scriptName = $scriptName[$scriptElms-1];
2017
2018 1e0b1727 Phil Davis
		if (isAjax()) {
2019 55eb9c44 --global
			return false;
2020 1e0b1727 Phil Davis
		}
2021 55eb9c44 --global
2022
		/* redirect to page the user is on, it'll prompt them to login again */
2023 6f3d2063 Renato Botelho
		header("Location: {$scriptName}");
2024 55eb9c44 --global
2025
		return false;
2026
	}
2027
2028
	/*
2029
	 * this is for debugging purpose if you do not want to use Ajax
2030 1e0b1727 Phil Davis
	 * to submit a HTML form. It basically disables the observation
2031 55eb9c44 --global
	 * of the submit event and hence does not trigger Ajax.
2032
	 */
2033 8d58ebae Steve Beaver
	if ($_REQUEST['disable_ajax']) {
2034 55eb9c44 --global
		$_SESSION['NO_AJAX'] = "True";
2035 1e0b1727 Phil Davis
	}
2036 55eb9c44 --global
2037
	/*
2038
	 * Same to re-enable Ajax.
2039
	 */
2040 8d58ebae Steve Beaver
	if ($_REQUEST['enable_ajax']) {
2041 55eb9c44 --global
		unset($_SESSION['NO_AJAX']);
2042 1e0b1727 Phil Davis
	}
2043 82cd6022 PiBa-NL
	phpsession_end(true);
2044 55eb9c44 --global
	return true;
2045
}
2046
2047 16050763 Steve Beaver
function print_credit() {
2048
	global $g;
2049
2050
	return  '<a target="_blank" href="https://pfsense.org">' . $g["product_name"] . '</a>' .
2051
			gettext(' is developed and maintained by ') .
2052
			'<a target="_blank" href="https://netgate.com">Netgate. </a>' . ' &copy; ESF ' . $g["product_copyright_years"] .
2053
			'<a target="_blank" href="https://pfsense.org/license">' .
2054
			gettext(' View license.') . '</a>';
2055
}
2056 88165371 Ermal
?>