Project

General

Profile

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