Project

General

Profile

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