Project

General

Profile

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