Project

General

Profile

Download (64.3 KB) Statistics
| Branch: | Tag: | Revision:
1 55eb9c44 --global
<?php
2 b37b4034 Phil Davis
/*
3 ac24dc24 Renato Botelho
 * auth.inc
4 995df6c3 Stephen Beaver
 *
5 ac24dc24 Renato Botelho
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2003-2006 Manuel Kasper <mk@neon1.net>
7
 * Copyright (c) 2005-2006 Bill Marquette <bill.marquette@gmail.com>
8
 * Copyright (c) 2006 Paul Taylor <paultaylor@winn-dixie.com>
9 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
		$ldaptype = "";
1275
		$ldapver = $authcfg['ldap_protver'];
1276
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1277
			$ldapanon = true;
1278
		} else {
1279
			$ldapanon = false;
1280
		}
1281
		$ldapname = $authcfg['name'];
1282
		$ldapfallback = false;
1283
		$ldapscope = $authcfg['ldap_scope'];
1284 e8c09a23 Chris Buechler
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1285 1e0b1727 Phil Davis
	} else {
1286 6306b5dd Ermal Lu?i
		return false;
1287 1e0b1727 Phil Davis
	}
1288 c61e4626 Ermal Lu?i
1289 149efbea jim-p
	if (isset($authcfg['ldap_rfc2307'])) {
1290
		$ldapdn = $ldapbasedn;
1291
	} else {
1292
		$ldapdn = $_SESSION['ldapdn'];
1293
	}
1294 c61e4626 Ermal Lu?i
1295 55eb9c44 --global
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
1296
	$ldapgroupattribute = strtolower($ldapgroupattribute);
1297 c61e4626 Ermal Lu?i
	$memberof = array();
1298 55eb9c44 --global
1299 7729c5a1 jim-p
	/* Setup CA environment if needed. */
1300
	ldap_setup_caenv($ldap, $authcfg);
1301
1302 55eb9c44 --global
	/* connect and see if server is up */
1303 c61e4626 Ermal Lu?i
	$error = false;
1304 1e0b1727 Phil Davis
	if (!($ldap = ldap_connect($ldapserver))) {
1305 9f27de6d jim-p
		$error = true;
1306 1e0b1727 Phil Davis
	}
1307 c61e4626 Ermal Lu?i
1308
	if ($error == true) {
1309 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("ERROR! ldap_get_groups() Could not connect to server %s."), $ldapname));
1310 0241b34f Phil Davis
		return $memberof;
1311 1e0b1727 Phil Davis
	}
1312 1180e4f0 Sjon Hortensius
1313 55eb9c44 --global
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1314 3d3081ec Andrew MacIsaac
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1315 c61e4626 Ermal Lu?i
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1316 d6b4dfe3 jim-p
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1317
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1318 55eb9c44 --global
1319 d672403c derelict-pf
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1320 ff500c90 jim-p
		if (!(@ldap_start_tls($ldap))) {
1321 d672403c derelict-pf
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not STARTTLS to server %s."), $ldapname));
1322
			@ldap_close($ldap);
1323
			return false;
1324
		}
1325
	}
1326
1327 55eb9c44 --global
	/* bind as user that has rights to read group attributes */
1328 a5cd1c5a jim-p
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1329
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1330 c61e4626 Ermal Lu?i
	if ($ldapanon == true) {
1331 1e0b1727 Phil Davis
		if (!($res = @ldap_bind($ldap))) {
1332 94021404 Carlos Eduardo Ramos
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind anonymously to server %s."), $ldapname));
1333 6306b5dd Ermal Lu?i
			@ldap_close($ldap);
1334 1e0b1727 Phil Davis
			return false;
1335 6306b5dd Ermal Lu?i
		}
1336 c61e4626 Ermal Lu?i
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1337 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind to server %s."), $ldapname));
1338 6306b5dd Ermal Lu?i
		@ldap_close($ldap);
1339 0241b34f Phil Davis
		return $memberof;
1340 55eb9c44 --global
	}
1341
1342
	/* get groups from DN found */
1343
	/* use ldap_read instead of search so we don't have to do a bunch of extra work */
1344
	/* since we know the DN is in $_SESSION['ldapdn'] */
1345
	//$search    = ldap_read($ldap, $ldapdn, "(objectclass=*)", array($ldapgroupattribute));
1346 1e0b1727 Phil Davis
	if ($ldapscope == "one") {
1347
		$ldapfunc = "ldap_list";
1348
	} else {
1349
		$ldapfunc = "ldap_search";
1350
	}
1351 c61e4626 Ermal Lu?i
1352 e924485c Viktor G
	if (isset($authcfg['ldap_rfc2307'])) {
1353
		if (isset($authcfg['ldap_rfc2307_userdn'])) {
1354
			$ldac_splits = explode(";", $ldapauthcont);
1355
			foreach ($ldac_splits as $i => $ldac_split) {
1356
				$ldac_split = isset($authcfg['ldap_utf8']) ? utf8_encode($ldac_split) : $ldac_split;
1357
				$ldapsearchbasedn = isset($authcfg['ldap_utf8']) ? utf8_encode("{$ldac_split},{$ldapbasedn}") : "{$ldac_split},{$ldapbasedn}";
1358
				$ldapfilter = "({$ldapnameattribute}={$username})";
1359
				if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) {
1360
					$ldapdn = $ldac_split;
1361
				} else {
1362
					$ldapdn = $ldapsearchbasedn;
1363
				}
1364
				$usersearch = @$ldapfunc($ldap, $ldapdn, $ldapfilter);
1365
				$userinfo = @ldap_get_entries($ldap, $usersearch);
1366
			}
1367
			$username = $userinfo[0]['dn'];
1368
		}
1369
		$ldapgroupfilter         = "(&(objectClass={$authcfg['ldap_attr_groupobj']})({$ldapgroupattribute}={$username}))";
1370
	} else {
1371
		$ldapgroupfilter         = "({$ldapnameattribute}={$username})";
1372
	}
1373
1374
	$search = @$ldapfunc($ldap, $ldapdn, $ldapgroupfilter, array($ldapgroupattribute));
1375 1e0b1727 Phil Davis
	$info = @ldap_get_entries($ldap, $search);
1376 55eb9c44 --global
1377 149efbea jim-p
	$gresults = isset($authcfg['ldap_rfc2307']) ? $info : $info[0][$ldapgroupattribute];
1378 1180e4f0 Sjon Hortensius
1379 4e322e2c Phil Davis
	if (is_array($gresults)) {
1380 55eb9c44 --global
		/* Iterate through the groups and throw them into an array */
1381 149efbea jim-p
		foreach ($gresults as $grp) {
1382 4e322e2c Phil Davis
			if (((isset($authcfg['ldap_rfc2307'])) && (stristr($grp["dn"], "CN=") !== false)) ||
1383
			    ((!isset($authcfg['ldap_rfc2307'])) && (stristr($grp, "CN=") !== false))) {
1384 149efbea jim-p
				$grpsplit = isset($authcfg['ldap_rfc2307']) ? explode(",", $grp["dn"]) : explode(",", $grp);
1385
				$memberof[] = preg_replace("/CN=/i", "", $grpsplit[0]);
1386 55eb9c44 --global
			}
1387
		}
1388
	}
1389 1180e4f0 Sjon Hortensius
1390 55eb9c44 --global
	/* Time to close LDAP connection */
1391 6306b5dd Ermal Lu?i
	@ldap_unbind($ldap);
1392 1180e4f0 Sjon Hortensius
1393 4de8f7ba Phil Davis
	$groups = print_r($memberof, true);
1394 1180e4f0 Sjon Hortensius
1395 55eb9c44 --global
	//log_error("Returning groups ".$groups." for user $username");
1396 1180e4f0 Sjon Hortensius
1397 55eb9c44 --global
	return $memberof;
1398
}
1399
1400 83e0d4c8 jim-p
function ldap_format_host($host) {
1401
	return is_ipaddrv6($host) ? "[$host]" : $host ;
1402
}
1403
1404 eb43c5b1 Augustin FL
function ldap_backed($username, $passwd, $authcfg, &$attributes = array()) {
1405 55eb9c44 --global
	global $debug, $config;
1406 1180e4f0 Sjon Hortensius
1407 1e0b1727 Phil Davis
	if (!$username) {
1408 eb43c5b1 Augustin FL
		$attributes['error_message'] = gettext("Invalid Login.");
1409
		return false;
1410 1e0b1727 Phil Davis
	}
1411 55eb9c44 --global
1412 eeceb2ca Augustin-FL
	if (!isset($authcfg['ldap_allow_unauthenticated']) && $passwd == '') {
1413
		$attributes['error_message'] = gettext("Invalid credentials.");
1414
		return false;
1415
	}
1416
1417 1e0b1727 Phil Davis
	if (!function_exists("ldap_connect")) {
1418 eb43c5b1 Augustin FL
		log_error(gettext("ERROR! unable to find ldap_connect() function."));
1419
		$attributes['error_message'] = gettext("Internal error during authentication.");
1420
		return null;
1421 1e0b1727 Phil Davis
	}
1422 55eb9c44 --global
1423 1e0b1727 Phil Davis
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1424 2ce660ad smos
		$username_split = explode("@", $username);
1425 1180e4f0 Sjon Hortensius
		$username = $username_split[0];
1426 55eb9c44 --global
	}
1427 1e0b1727 Phil Davis
	if (stristr($username, "\\")) {
1428 cfbfd941 smos
		$username_split = explode("\\", $username);
1429 1180e4f0 Sjon Hortensius
		$username = $username_split[0];
1430 55eb9c44 --global
	}
1431
1432 f0b0a03b jim-p
	$username = ldap_escape($username, null, LDAP_ESCAPE_FILTER);
1433
1434 c61e4626 Ermal Lu?i
	if ($authcfg) {
1435 d672403c derelict-pf
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1436 c61e4626 Ermal Lu?i
			$ldapproto = "ldaps";
1437 d672403c derelict-pf
		} else {
1438
			$ldapproto = "ldap";
1439 1e0b1727 Phil Davis
		}
1440
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1441
		$ldapport = $authcfg['ldap_port'];
1442
		if (!empty($ldapport)) {
1443 9f27de6d jim-p
			$ldapserver .= ":{$ldapport}";
1444 1e0b1727 Phil Davis
		}
1445
		$ldapbasedn = $authcfg['ldap_basedn'];
1446
		$ldapbindun = $authcfg['ldap_binddn'];
1447
		$ldapbindpw = $authcfg['ldap_bindpw'];
1448
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1449 c61e4626 Ermal Lu?i
			$ldapanon = true;
1450 1e0b1727 Phil Davis
		} else {
1451 c61e4626 Ermal Lu?i
			$ldapanon = false;
1452 1e0b1727 Phil Davis
		}
1453
		$ldapauthcont = $authcfg['ldap_authcn'];
1454
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1455 0a9163aa Steve Powers
		$ldapgroupattribute = $authcfg['ldap_attr_member'];
1456 1e0b1727 Phil Davis
		$ldapextendedqueryenabled = $authcfg['ldap_extended_enabled'];
1457
		$ldapextendedquery = $authcfg['ldap_extended_query'];
1458
		$ldapfilter = "";
1459
		if (!$ldapextendedqueryenabled) {
1460
			$ldapfilter = "({$ldapnameattribute}={$username})";
1461
		} else {
1462 0a9163aa Steve Powers
			if (isset($authcfg['ldap_rfc2307'])) {
1463
				$ldapfilter = "({$ldapnameattribute}={$username})";
1464
				$ldapgroupfilter = "(&({$ldapgroupattribute}={$username})({$ldapextendedquery}))";
1465
			} else {
1466
				$ldapfilter = "(&({$ldapnameattribute}={$username})({$ldapextendedquery}))";
1467
			}
1468 1e0b1727 Phil Davis
		}
1469
		$ldaptype = "";
1470
		$ldapver = $authcfg['ldap_protver'];
1471
		$ldapname = $authcfg['name'];
1472
		$ldapscope = $authcfg['ldap_scope'];
1473 e8c09a23 Chris Buechler
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1474 1e0b1727 Phil Davis
	} else {
1475 eb43c5b1 Augustin FL
		return null;
1476 1e0b1727 Phil Davis
	}
1477 55eb9c44 --global
1478 1180e4f0 Sjon Hortensius
	/* first check if there is even an LDAP server populated */
1479 1e0b1727 Phil Davis
	if (!$ldapserver) {
1480 eb43c5b1 Augustin FL
		log_error(gettext("ERROR! could not find details of the LDAP server used for authentication."));
1481
		$attributes['error_message'] =  gettext("Internal error during authentication.");
1482
		return null;
1483 55eb9c44 --global
	}
1484 1180e4f0 Sjon Hortensius
1485 7729c5a1 jim-p
	/* Setup CA environment if needed. */
1486
	ldap_setup_caenv($ldap, $authcfg);
1487
1488 d672403c derelict-pf
	/* Make sure we can connect to LDAP */
1489
	$error = false;
1490
	if (!($ldap = ldap_connect($ldapserver))) {
1491
		$error = true;
1492
	}
1493
1494 906daddc Ermal
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1495 3d3081ec Andrew MacIsaac
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1496 906daddc Ermal
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1497 d6b4dfe3 jim-p
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1498
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1499 906daddc Ermal
1500 d672403c derelict-pf
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1501 b2c7a79c jim-p
		if (!(@ldap_start_tls($ldap))) {
1502 eb43c5b1 Augustin FL
			log_error(sprintf(gettext("ERROR! could not connect to LDAP server %s using STARTTLS."), $ldapname));
1503
			$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1504 d672403c derelict-pf
			@ldap_close($ldap);
1505 eb43c5b1 Augustin FL
			return null;
1506 d672403c derelict-pf
		}
1507 1e0b1727 Phil Davis
	}
1508 c61e4626 Ermal Lu?i
1509
	if ($error == true) {
1510 eb43c5b1 Augustin FL
		$errormsg = sprintf(gettext("ERROR! Could not connect to server %s."), $ldapname);
1511
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1512
		return null;
1513 55eb9c44 --global
	}
1514 c61e4626 Ermal Lu?i
1515 55eb9c44 --global
	/* ok, its up.  now, lets bind as the bind user so we can search it */
1516 c61e4626 Ermal Lu?i
	$error = false;
1517 a5cd1c5a jim-p
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1518
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1519 c61e4626 Ermal Lu?i
	if ($ldapanon == true) {
1520 1e0b1727 Phil Davis
		if (!($res = @ldap_bind($ldap))) {
1521
			$error = true;
1522
		}
1523
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1524 c61e4626 Ermal Lu?i
		$error = true;
1525 1e0b1727 Phil Davis
	}
1526 c61e4626 Ermal Lu?i
1527
	if ($error == true) {
1528 6306b5dd Ermal Lu?i
		@ldap_close($ldap);
1529 eb43c5b1 Augustin FL
		log_error(sprintf(gettext("ERROR! Could not bind to LDAP server %s. Please check the bind credentials."), $ldapname));
1530
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1531
		return null;
1532 55eb9c44 --global
	}
1533 1180e4f0 Sjon Hortensius
1534 55eb9c44 --global
	/* Get LDAP Authcontainers and split em up. */
1535 cfbfd941 smos
	$ldac_splits = explode(";", $ldapauthcont);
1536 1180e4f0 Sjon Hortensius
1537 086cf944 Phil Davis
	/* setup the usercount so we think we haven't found anyone yet */
1538 4de8f7ba Phil Davis
	$usercount = 0;
1539 55eb9c44 --global
1540
	/*****************************************************************/
1541 6990ad35 Phil Davis
	/*  We first find the user based on username and filter          */
1542
	/*  then, once we find the first occurrence of that person       */
1543
	/*  we set session variables to point to the OU and DN of the    */
1544
	/*  person.  To later be used by ldap_get_groups.                */
1545 55eb9c44 --global
	/*  that way we don't have to search twice.                      */
1546
	/*****************************************************************/
1547 1e0b1727 Phil Davis
	if ($debug) {
1548 3ac8324f Ermal
		log_auth(sprintf(gettext("Now Searching for %s in directory."), $username));
1549 1e0b1727 Phil Davis
	}
1550 c61e4626 Ermal Lu?i
	/* Iterate through the user containers for search */
1551
	foreach ($ldac_splits as $i => $ldac_split) {
1552 a5cd1c5a jim-p
		$ldac_split = isset($authcfg['ldap_utf8']) ? utf8_encode($ldac_split) : $ldac_split;
1553
		$ldapfilter = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapfilter) : $ldapfilter;
1554
		$ldapsearchbasedn = isset($authcfg['ldap_utf8']) ? utf8_encode("{$ldac_split},{$ldapbasedn}") : "{$ldac_split},{$ldapbasedn}";
1555 c61e4626 Ermal Lu?i
		/* Make sure we just use the first user we find */
1556 1e0b1727 Phil Davis
		if ($debug) {
1557 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)));
1558 1e0b1727 Phil Davis
		}
1559
		if ($ldapscope == "one") {
1560 c61e4626 Ermal Lu?i
			$ldapfunc = "ldap_list";
1561 1e0b1727 Phil Davis
		} else {
1562 c61e4626 Ermal Lu?i
			$ldapfunc = "ldap_search";
1563 1e0b1727 Phil Davis
		}
1564 c61e4626 Ermal Lu?i
		/* Support legacy auth container specification. */
1565 1e0b1727 Phil Davis
		if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) {
1566 e924485c Viktor G
			$ldapdn = $ldac_split;
1567 1e0b1727 Phil Davis
		} else {
1568 e924485c Viktor G
			$ldapdn = $ldapsearchbasedn;
1569
		}
1570
		$search = @$ldapfunc($ldap, $ldapdn, $ldapfilter);
1571
		$info = ldap_get_entries($ldap, $search);
1572
		if (isset($authcfg['ldap_rfc2307'])) {
1573
			if (isset($authcfg['ldap_rfc2307_userdn'])) {
1574
				$username = $info[0]['dn'];
1575 0a9163aa Steve Powers
			}
1576 e924485c Viktor G
			$ldapgroupfilter = "(&({$ldapgroupattribute}={$username})({$ldapextendedquery}))";
1577
		}
1578
1579
		if (isset($ldapgroupfilter)) {
1580
			$groupsearch = @$ldapfunc($ldap, $ldapdn, $ldapgroupfilter);
1581 0a9163aa Steve Powers
		}
1582
1583
		if (isset($ldapgroupfilter) && !$groupsearch) {
1584
			log_error(sprintf(gettext("Extended group search resulted in error: %s"), ldap_error($ldap)));
1585
			continue;
1586 1e0b1727 Phil Davis
		}
1587 c61e4626 Ermal Lu?i
		if (!$search) {
1588 94021404 Carlos Eduardo Ramos
			log_error(sprintf(gettext("Search resulted in error: %s"), ldap_error($ldap)));
1589 c61e4626 Ermal Lu?i
			continue;
1590 55eb9c44 --global
		}
1591 0a9163aa Steve Powers
		if (isset($groupsearch)) {
1592
			$validgroup = ldap_count_entries($ldap, $groupsearch);
1593
			if ($debug) {
1594
				log_auth(sprintf(gettext("LDAP group search: %s results."), $validgroup));
1595
			}
1596
		}
1597 c61e4626 Ermal Lu?i
		$matches = $info['count'];
1598 1e0b1727 Phil Davis
		if ($matches == 1) {
1599 c61e4626 Ermal Lu?i
			$userdn = $_SESSION['ldapdn'] = $info[0]['dn'];
1600
			$_SESSION['ldapou'] = $ldac_split[$i];
1601
			$_SESSION['ldapon'] = "true";
1602
			$usercount = 1;
1603
			break;
1604 55eb9c44 --global
		}
1605
	}
1606
1607 1e0b1727 Phil Davis
	if ($usercount != 1) {
1608 6306b5dd Ermal Lu?i
		@ldap_unbind($ldap);
1609 eb43c5b1 Augustin FL
		if ($debug) {
1610
			if ($usercount === 0) {
1611
				log_error(sprintf(gettext("ERROR! LDAP search failed, no user matching %s was found."), $username));
1612
			} else {
1613
				log_error(sprintf(gettext("ERROR! LDAP search failed, multiple users matching %s were found."), $username));
1614
			}
1615
		}
1616
		$attributes['error_message'] = gettext("Invalid login specified.");
1617 1180e4f0 Sjon Hortensius
		return false;
1618 55eb9c44 --global
	}
1619 c61e4626 Ermal Lu?i
1620 55eb9c44 --global
	/* Now lets bind as the user we found */
1621 a5cd1c5a jim-p
	$passwd = isset($authcfg['ldap_utf8']) ? utf8_encode($passwd) : $passwd;
1622 c61e4626 Ermal Lu?i
	if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
1623 eb43c5b1 Augustin FL
		if ($debug) {
1624
			log_error(sprintf(gettext('ERROR! Could not login to server %1$s as user %2$s: %3$s'), $ldapname, $username, ldap_error($ldap)));
1625
		}
1626 6306b5dd Ermal Lu?i
		@ldap_unbind($ldap);
1627 c61e4626 Ermal Lu?i
		return false;
1628 55eb9c44 --global
	}
1629
1630 a5cd1c5a jim-p
	if ($debug) {
1631
		$userdn = isset($authcfg['ldap_utf8']) ? utf8_decode($userdn) : $userdn;
1632 2004def5 Ermal
		log_auth(sprintf(gettext('Logged in successfully as %1$s via LDAP server %2$s with DN = %3$s.'), $username, $ldapname, $userdn));
1633 a5cd1c5a jim-p
	}
1634 c61e4626 Ermal Lu?i
1635 0a9163aa Steve Powers
	if ($debug && isset($ldapgroupfilter) && $validgroup < 1) {
1636
		log_auth(sprintf(gettext('Logged in successfully as %1$s but did not match any field in extended query.'), $username));
1637
	}
1638
1639 c61e4626 Ermal Lu?i
	/* At this point we are bound to LDAP so the user was auth'd okay. Close connection. */
1640 6306b5dd Ermal Lu?i
	@ldap_unbind($ldap);
1641 55eb9c44 --global
1642 0a9163aa Steve Powers
	if (isset($ldapgroupfilter) && $validgroup < 1) {
1643
		return false;
1644
	}
1645
1646 55eb9c44 --global
	return true;
1647
}
1648
1649 9da4a575 Renato Botelho
function radius_backed($username, $password, $authcfg, &$attributes = array()) {
1650 a13ce628 Ermal Lu?i
	global $debug, $config;
1651 55eb9c44 --global
	$ret = false;
1652
1653 49ec9d91 Renato Botelho
	require_once("Auth/RADIUS.php");
1654 9da4a575 Renato Botelho
	require_once("Crypt/CHAP.php");
1655 868c6826 Ermal
1656 c61e4626 Ermal Lu?i
	if ($authcfg) {
1657
		$radiusservers = array();
1658
		$radiusservers[0]['ipaddr'] = $authcfg['host'];
1659
		$radiusservers[0]['port'] = $authcfg['radius_auth_port'];
1660
		$radiusservers[0]['sharedsecret'] = $authcfg['radius_secret'];
1661 bddd2be8 jim-p
		$radiusservers[0]['timeout'] = $authcfg['radius_timeout'];
1662 9da4a575 Renato Botelho
		if(isset($authcfg['radius_protocol'])) {
1663
			$radius_protocol = $authcfg['radius_protocol'];
1664
		} else {
1665
			$radius_protocol = 'PAP';
1666
		}
1667 1e0b1727 Phil Davis
	} else {
1668 f15fdef3 Augustin FL
		log_error(gettext("ERROR! could not find details of the RADIUS server used for authentication."));
1669
		$attributes['error_message'] =  gettext("Internal error during authentication.");
1670
		return null;
1671 1e0b1727 Phil Davis
	}
1672 c61e4626 Ermal Lu?i
1673 9da4a575 Renato Botelho
	// Create our instance
1674
	$classname = 'Auth_RADIUS_' . $radius_protocol;
1675
	$rauth = new $classname($username, $password);
1676
1677 1e0b1727 Phil Davis
	/* Add new servers to our instance */
1678 bddd2be8 jim-p
	foreach ($radiusservers as $radsrv) {
1679
		$timeout = (is_numeric($radsrv['timeout'])) ? $radsrv['timeout'] : 5;
1680
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret'], $timeout);
1681
	}
1682 55eb9c44 --global
1683 9da4a575 Renato Botelho
	// Construct data package
1684
	$rauth->username = $username;
1685
	switch ($radius_protocol) {
1686
		case 'CHAP_MD5':
1687
		case 'MSCHAPv1':
1688
			$classname = $radius_protocol == 'MSCHAPv1' ? 'Crypt_CHAP_MSv1' : 'Crypt_CHAP_MD5';
1689
			$crpt = new $classname;
1690
			$crpt->username = $username;
1691
			$crpt->password = $password;
1692
			$rauth->challenge = $crpt->challenge;
1693
			$rauth->chapid = $crpt->chapid;
1694
			$rauth->response = $crpt->challengeResponse();
1695
			$rauth->flags = 1;
1696
			break;
1697
1698
		case 'MSCHAPv2':
1699
			$crpt = new Crypt_CHAP_MSv2;
1700
			$crpt->username = $username;
1701
			$crpt->password = $password;
1702
			$rauth->challenge = $crpt->authChallenge;
1703
			$rauth->peerChallenge = $crpt->peerChallenge;
1704
			$rauth->chapid = $crpt->chapid;
1705
			$rauth->response = $crpt->challengeResponse();
1706
			break;
1707
1708
		default:
1709
			$rauth->password = $password;
1710
			break;
1711
	}
1712
1713 6e815096 Ermal
	if (PEAR::isError($rauth->start())) {
1714 f15fdef3 Augustin FL
		$ret = null;
1715
		log_error(sprintf(gettext("Error during RADIUS authentication : %s"), $rauth->getError()));
1716
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1717
	} else {
1718
		$nasid = $attributes['nas_identifier'];
1719
		$nasip = $authcfg['radius_nasip_attribute'];
1720
		if (empty($nasid)) {
1721
			$nasid = gethostname(); //If no RADIUS NAS-Identifier is given : we use pfsense's hostname as NAS-Identifier
1722
		}
1723
		if (!is_ipaddr($nasip)) {
1724
			$nasip = get_interface_ip($nasip);
1725 f3f98e97 Phil Davis
1726 f15fdef3 Augustin FL
			if (!is_ipaddr($nasip)) {
1727
				$nasip = get_interface_ip();//We use wan interface IP as fallback for NAS-IP-Address
1728
			}
1729
		}
1730
		$nasmac = get_interface_mac(find_ip_interface($nasip));
1731
1732
		$rauth->putAttribute(RADIUS_NAS_IP_ADDRESS, $nasip, "addr");
1733
		$rauth->putAttribute(RADIUS_NAS_IDENTIFIER, $nasid);
1734 f3f98e97 Phil Davis
1735 f15fdef3 Augustin FL
		if(!empty($attributes['calling_station_id'])) {
1736
			$rauth->putAttribute(RADIUS_CALLING_STATION_ID, $attributes['calling_station_id']);
1737
		}
1738
		// Carefully check that interface has a MAC address
1739
		if(!empty($nasmac)) {
1740
			$nasmac = mac_format($nasmac);
1741
			$rauth->putAttribute(RADIUS_CALLED_STATION_ID, $nasmac.':'.gethostname());
1742
		}
1743
		if(!empty($attributes['nas_port_type'])) {
1744
			$rauth->putAttribute(RADIUS_NAS_PORT_TYPE, $attributes['nas_port_type']);
1745 f3f98e97 Phil Davis
		}
1746 f15fdef3 Augustin FL
		if(!empty($attributes['nas_port'])) {
1747
			$rauth->putAttribute(RADIUS_NAS_PORT, intval($attributes['nas_port']), 'integer');
1748
		}
1749
		if(!empty($attributes['framed_ip']) && is_ipaddr($attributes['framed_ip'])) {
1750
			$rauth->putAttribute(RADIUS_FRAMED_IP_ADDRESS, $attributes['framed_ip'], "addr");
1751 1e0b1727 Phil Davis
		}
1752 55eb9c44 --global
	}
1753
1754
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1755
1756
	/* Send request */
1757
	$result = $rauth->send();
1758
	if (PEAR::isError($result)) {
1759 f15fdef3 Augustin FL
		log_error(sprintf(gettext("Error during RADIUS authentication : %s"), $rauth->getError()));
1760
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1761
		$ret = null;
1762 55eb9c44 --global
	} else if ($result === true) {
1763
		$ret = true;
1764
	} else {
1765 f15fdef3 Augustin FL
		$ret = false;
1766 55eb9c44 --global
	}
1767
1768 f3f98e97 Phil Davis
1769 f15fdef3 Augustin FL
	// Get attributes, even if auth failed.
1770
	if ($rauth->getAttributes()) {
1771
	$attributes = array_merge($attributes,$rauth->listAttributes());
1772
1773
	// We convert the session_terminate_time to unixtimestamp if its set before returning the whole array to our caller
1774
	if (!empty($attributes['session_terminate_time'])) {
1775
			$stt = &$attributes['session_terminate_time'];
1776
			$stt = strtotime(preg_replace("/\+(\d+):(\d+)$/", " +\${1}\${2}", preg_replace("/(\d+)T(\d+)/", "\${1} \${2}",$stt)));
1777
		}
1778
	}
1779 f3f98e97 Phil Davis
1780 f15fdef3 Augustin FL
	// close OO RADIUS_AUTHENTICATION
1781 55eb9c44 --global
	$rauth->close();
1782
1783
	return $ret;
1784
}
1785
1786 c4a9f99a jim-p
/*
1787
	$attributes must contain a "class" key containing the groups and local
1788
	groups must exist to match.
1789
*/
1790
function radius_get_groups($attributes) {
1791
	$groups = array();
1792 461bae6b jim-p
	if (!empty($attributes) && is_array($attributes) && (!empty($attributes['class']) || !empty($attributes['class_int']))) {
1793
		/* Some RADIUS servers return multiple class attributes, so check them all. */
1794
		$groups = array();
1795
		if (!empty($attributes['class']) && is_array($attributes['class'])) {
1796
			foreach ($attributes['class'] as $class) {
1797
				$groups = array_unique(array_merge($groups, explode(";", $class)));
1798
			}
1799
		}
1800
1801 c4a9f99a jim-p
		foreach ($groups as & $grp) {
1802 916fc1f8 jim-p
			$grp = trim($grp);
1803
			if (strtolower(substr($grp, 0, 3)) == "ou=") {
1804 c4a9f99a jim-p
				$grp = substr($grp, 3);
1805
			}
1806
		}
1807
	}
1808
	return $groups;
1809
}
1810
1811 7dd044f2 sullrich
function get_user_expiration_date($username) {
1812 a13ce628 Ermal Lu?i
	$user = getUserEntry($username);
1813 1e0b1727 Phil Davis
	if ($user['expires']) {
1814 a13ce628 Ermal Lu?i
		return $user['expires'];
1815 1e0b1727 Phil Davis
	}
1816 a13ce628 Ermal Lu?i
}
1817
1818
function is_account_expired($username) {
1819
	$expirydate = get_user_expiration_date($username);
1820
	if ($expirydate) {
1821 4de8f7ba Phil Davis
		if (strtotime("-1 day") > strtotime(date("m/d/Y", strtotime($expirydate)))) {
1822 a13ce628 Ermal Lu?i
			return true;
1823 1e0b1727 Phil Davis
		}
1824 7dd044f2 sullrich
	}
1825 a13ce628 Ermal Lu?i
1826
	return false;
1827 7dd044f2 sullrich
}
1828
1829 b4bfd25d sullrich
function is_account_disabled($username) {
1830 a13ce628 Ermal Lu?i
	$user = getUserEntry($username);
1831 1e0b1727 Phil Davis
	if (isset($user['disabled'])) {
1832 a13ce628 Ermal Lu?i
		return true;
1833 1e0b1727 Phil Davis
	}
1834 a13ce628 Ermal Lu?i
1835 b4bfd25d sullrich
	return false;
1836
}
1837
1838 8bab524e Phil Davis
function get_user_settings($username) {
1839
	global $config;
1840
	$settings = array();
1841
	$settings['widgets'] = $config['widgets'];
1842
	$settings['webgui']['dashboardcolumns'] = $config['system']['webgui']['dashboardcolumns'];
1843
	$settings['webgui']['webguihostnamemenu'] = $config['system']['webgui']['webguihostnamemenu'];
1844
	$settings['webgui']['webguicss'] = $config['system']['webgui']['webguicss'];
1845 e79ff1ee Steve Beaver
	$settings['webgui']['logincss'] = $config['system']['webgui']['logincss'];
1846 1d3510cf Phil Davis
	$settings['webgui']['interfacessort'] = isset($config['system']['webgui']['interfacessort']);
1847 8bab524e Phil Davis
	$settings['webgui']['dashboardavailablewidgetspanel'] = isset($config['system']['webgui']['dashboardavailablewidgetspanel']);
1848
	$settings['webgui']['webguifixedmenu'] = isset($config['system']['webgui']['webguifixedmenu']);
1849
	$settings['webgui']['webguileftcolumnhyper'] = isset($config['system']['webgui']['webguileftcolumnhyper']);
1850 d9058974 Phil Davis
	$settings['webgui']['disablealiaspopupdetail'] = isset($config['system']['webgui']['disablealiaspopupdetail']);
1851 8bab524e Phil Davis
	$settings['webgui']['systemlogsfilterpanel'] = isset($config['system']['webgui']['systemlogsfilterpanel']);
1852
	$settings['webgui']['systemlogsmanagelogpanel'] = isset($config['system']['webgui']['systemlogsmanagelogpanel']);
1853
	$settings['webgui']['statusmonitoringsettingspanel'] = isset($config['system']['webgui']['statusmonitoringsettingspanel']);
1854
	$settings['webgui']['pagenamefirst'] = isset($config['system']['webgui']['pagenamefirst']);
1855
	$user = getUserEntry($username);
1856
	if (isset($user['customsettings'])) {
1857
		$settings['customsettings'] = true;
1858
		if (isset($user['widgets'])) {
1859
			// This includes the 'sequence', and any widgetname-config per-widget settings.
1860
			$settings['widgets'] = $user['widgets'];
1861
		}
1862
		if (isset($user['dashboardcolumns'])) {
1863
			$settings['webgui']['dashboardcolumns'] = $user['dashboardcolumns'];
1864
		}
1865
		if (isset($user['webguicss'])) {
1866
			$settings['webgui']['webguicss'] = $user['webguicss'];
1867
		}
1868
		if (isset($user['webguihostnamemenu'])) {
1869
			$settings['webgui']['webguihostnamemenu'] = $user['webguihostnamemenu'];
1870
		}
1871 1d3510cf Phil Davis
		$settings['webgui']['interfacessort'] = isset($user['interfacessort']);
1872 8bab524e Phil Davis
		$settings['webgui']['dashboardavailablewidgetspanel'] = isset($user['dashboardavailablewidgetspanel']);
1873
		$settings['webgui']['webguifixedmenu'] = isset($user['webguifixedmenu']);
1874
		$settings['webgui']['webguileftcolumnhyper'] = isset($user['webguileftcolumnhyper']);
1875 d9058974 Phil Davis
		$settings['webgui']['disablealiaspopupdetail'] = isset($user['disablealiaspopupdetail']);
1876 8bab524e Phil Davis
		$settings['webgui']['systemlogsfilterpanel'] = isset($user['systemlogsfilterpanel']);
1877
		$settings['webgui']['systemlogsmanagelogpanel'] = isset($user['systemlogsmanagelogpanel']);
1878
		$settings['webgui']['statusmonitoringsettingspanel'] = isset($user['statusmonitoringsettingspanel']);
1879
		$settings['webgui']['pagenamefirst'] = isset($user['pagenamefirst']);
1880
	} else {
1881
		$settings['customsettings'] = false;
1882
	}
1883
1884
	if ($settings['webgui']['dashboardcolumns'] < 1) {
1885
		$settings['webgui']['dashboardcolumns'] = 2;
1886
	}
1887
1888
	return $settings;
1889
}
1890
1891 2b7d0520 Phil Davis
function save_widget_settings($username, $settings, $message = "") {
1892 8bab524e Phil Davis
	global $config, $userindex;
1893
	$user = getUserEntry($username);
1894 2b7d0520 Phil Davis
1895
	if (strlen($message) > 0) {
1896
		$msgout = $message;
1897
	} else {
1898
		$msgout = gettext("Widget configuration has been changed.");
1899
	}
1900
1901 8bab524e Phil Davis
	if (isset($user['customsettings'])) {
1902
		$config['system']['user'][$userindex[$username]]['widgets'] = $settings;
1903 2b7d0520 Phil Davis
		write_config($msgout . " " . sprintf(gettext("(User %s)"), $username));
1904 8bab524e Phil Davis
	} else {
1905
		$config['widgets'] = $settings;
1906 2b7d0520 Phil Davis
		write_config($msgout);
1907 8bab524e Phil Davis
	}
1908
}
1909
1910 c61e4626 Ermal Lu?i
function auth_get_authserver($name) {
1911 1e0b1727 Phil Davis
	global $config;
1912
1913
	if (is_array($config['system']['authserver'])) {
1914
		foreach ($config['system']['authserver'] as $authcfg) {
1915
			if ($authcfg['name'] == $name) {
1916
				return $authcfg;
1917
			}
1918
		}
1919
	}
1920
	if ($name == "Local Database") {
1921 296c16bd Renato Botelho
		return array("name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1922 1e0b1727 Phil Davis
	}
1923 6306b5dd Ermal Lu?i
}
1924
1925
function auth_get_authserver_list() {
1926 1e0b1727 Phil Davis
	global $config;
1927 6306b5dd Ermal Lu?i
1928
	$list = array();
1929
1930 1e0b1727 Phil Davis
	if (is_array($config['system']['authserver'])) {
1931
		foreach ($config['system']['authserver'] as $authcfg) {
1932 6306b5dd Ermal Lu?i
			/* Add support for disabled entries? */
1933
			$list[$authcfg['name']] = $authcfg;
1934 1e0b1727 Phil Davis
		}
1935
	}
1936 6306b5dd Ermal Lu?i
1937 296c16bd Renato Botelho
	$list["Local Database"] = array("name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1938 6306b5dd Ermal Lu?i
	return $list;
1939 c61e4626 Ermal Lu?i
}
1940
1941 c4a9f99a jim-p
function getUserGroups($username, $authcfg, &$attributes = array()) {
1942 fb0f22c0 Ermal Lu?i
	global $config;
1943
1944
	$allowed_groups = array();
1945
1946 1e0b1727 Phil Davis
	switch ($authcfg['type']) {
1947
		case 'ldap':
1948
			$allowed_groups = @ldap_get_groups($username, $authcfg);
1949
			break;
1950
		case 'radius':
1951 c4a9f99a jim-p
			$allowed_groups = @radius_get_groups($attributes);
1952 1e0b1727 Phil Davis
			break;
1953
		default:
1954
			$user = getUserEntry($username);
1955
			$allowed_groups = @local_user_get_groups($user, true);
1956
			break;
1957 fb0f22c0 Ermal Lu?i
	}
1958
1959
	$member_groups = array();
1960 1e0b1727 Phil Davis
	if (is_array($config['system']['group'])) {
1961
		foreach ($config['system']['group'] as $group) {
1962
			if (in_array($group['name'], $allowed_groups)) {
1963 fb0f22c0 Ermal Lu?i
				$member_groups[] = $group['name'];
1964 1e0b1727 Phil Davis
			}
1965
		}
1966 fb0f22c0 Ermal Lu?i
	}
1967
1968
	return $member_groups;
1969
}
1970
1971 eb43c5b1 Augustin FL
/*
1972 f3f98e97 Phil Davis
Possible return values :
1973 eb43c5b1 Augustin FL
true : authentication worked
1974 f3f98e97 Phil Davis
false : authentication failed (invalid login/password, not enough permission, etc...)
1975 eb43c5b1 Augustin FL
null : error during authentication process (unable to reach remote server, etc...)
1976
*/
1977 1492e02c Ermal
function authenticate_user($username, $password, $authcfg = NULL, &$attributes = array()) {
1978 c61e4626 Ermal Lu?i
1979 b7369ff8 NewEraCracker
	if (is_array($username) || is_array($password)) {
1980
		return false;
1981
	}
1982
1983 c61e4626 Ermal Lu?i
	if (!$authcfg) {
1984 eb43c5b1 Augustin FL
		return local_backed($username, $password, $attributes);
1985 c61e4626 Ermal Lu?i
	}
1986
1987
	$authenticated = false;
1988 1e0b1727 Phil Davis
	switch ($authcfg['type']) {
1989
		case 'ldap':
1990 d832b6ce jim-p
			try {
1991
				$authenticated = ldap_backed($username, $password, $authcfg, $attributes);
1992
			} catch (Exception $e) {
1993
				log_error(sprintf(gettext("LDAP authentication error: %s"), $e->getMessage()));
1994
			}
1995
			break;
1996
1997 1e0b1727 Phil Davis
			break;
1998
		case 'radius':
1999 d832b6ce jim-p
			try {
2000
				$authenticated = radius_backed($username, $password, $authcfg, $attributes);
2001
			} catch (Exception $e) {
2002
				log_error(sprintf(gettext("RADIUS authentication error: %s"), $e->getMessage()));
2003
			}
2004 1e0b1727 Phil Davis
			break;
2005
		default:
2006
			/* lookup user object by name */
2007 d832b6ce jim-p
			try {
2008
				$authenticated = local_backed($username, $password, $attributes);
2009
			} catch (Exception $e) {
2010
				log_error(sprintf(gettext("Local authentication error: %s"), $e->getMessage()));
2011
			}
2012 1e0b1727 Phil Davis
			break;
2013
		}
2014 c61e4626 Ermal Lu?i
2015
	return $authenticated;
2016
}
2017
2018 6306b5dd Ermal Lu?i
function session_auth() {
2019 aa205c3b Ermal
	global $config, $_SESSION, $page;
2020 55eb9c44 --global
2021 49ddf9a1 Warren Baker
	// Handle HTTPS httponly and secure flags
2022 16789caa Renato Botelho
	$currentCookieParams = session_get_cookie_params();
2023
	session_set_cookie_params(
2024
		$currentCookieParams["lifetime"],
2025
		$currentCookieParams["path"],
2026
		NULL,
2027
		($config['system']['webgui']['protocol'] == "https"),
2028
		true
2029
	);
2030 49ddf9a1 Warren Baker
2031 82cd6022 PiBa-NL
	phpsession_begin();
2032 55eb9c44 --global
2033 dd030de9 Renato Botelho
	// Detect protocol change
2034 1e0b1727 Phil Davis
	if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) {
2035 82cd6022 PiBa-NL
		phpsession_end();
2036 dd030de9 Renato Botelho
		return false;
2037 1e0b1727 Phil Davis
	}
2038 dd030de9 Renato Botelho
2039 55eb9c44 --global
	/* Validate incoming login request */
2040 5ad5ead1 Shawn Bruce
	$attributes = array('nas_identifier' => 'webConfigurator-' . gethostname());
2041 eeceb2ca Augustin-FL
	if (isset($_POST['login']) && !empty($_POST['usernamefld'])) {
2042 6306b5dd Ermal Lu?i
		$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
2043 b77a6394 PiBa-NL
		$remoteauth = authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg, $attributes);
2044
		if ($remoteauth || authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) {
2045 526f5b11 Renato Botelho
			// Generate a new id to avoid session fixation
2046 8588095f Renato Botelho
			session_regenerate_id();
2047 6306b5dd Ermal Lu?i
			$_SESSION['Logged_In'] = "True";
2048 b77a6394 PiBa-NL
			$_SESSION['remoteauth'] = $remoteauth;
2049 d629601a jim-p
			if ($remoteauth) {
2050 80dbe344 jim-p
				if (empty($authcfg['type']) || ($authcfg['type'] == "Local Auth")) {
2051 296c16bd Renato Botelho
					$_SESSION['authsource'] = "Local Database";
2052 80dbe344 jim-p
				} else {
2053 296c16bd Renato Botelho
					$_SESSION['authsource'] = strtoupper($authcfg['type']) . "/{$authcfg['name']}";
2054 80dbe344 jim-p
				}
2055 d629601a jim-p
			} else {
2056 296c16bd Renato Botelho
				$_SESSION['authsource'] = 'Local Database Fallback';
2057 d629601a jim-p
			}
2058 6306b5dd Ermal Lu?i
			$_SESSION['Username'] = $_POST['usernamefld'];
2059 c4a9f99a jim-p
			$_SESSION['user_radius_attributes'] = $attributes;
2060 6306b5dd Ermal Lu?i
			$_SESSION['last_access'] = time();
2061 dd030de9 Renato Botelho
			$_SESSION['protocol'] = $config['system']['webgui']['protocol'];
2062 82cd6022 PiBa-NL
			phpsession_end(true);
2063 1e0b1727 Phil Davis
			if (!isset($config['system']['webgui']['quietlogin'])) {
2064 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()));
2065 4fc3855f smos
			}
2066 1e0b1727 Phil Davis
			if (isset($_POST['postafterlogin'])) {
2067 92140621 Ermal
				return true;
2068 1e0b1727 Phil Davis
			} else {
2069
				if (empty($page)) {
2070 80b292f3 Ermal
					$page = "/";
2071 1e0b1727 Phil Davis
				}
2072 80b292f3 Ermal
				header("Location: {$page}");
2073
			}
2074 f23e6363 Ermal
			exit;
2075 a13ce628 Ermal Lu?i
		} else {
2076
			/* give the user an error message */
2077 ca44a37c Steve Beaver
			$_SESSION['Login_Error'] = gettext("Username or Password incorrect");
2078 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()));
2079 1e0b1727 Phil Davis
			if (isAjax()) {
2080 a13ce628 Ermal Lu?i
				echo "showajaxmessage('{$_SESSION['Login_Error']}');";
2081
				return;
2082 55eb9c44 --global
			}
2083
		}
2084
	}
2085
2086
	/* Show login page if they aren't logged in */
2087 1e0b1727 Phil Davis
	if (empty($_SESSION['Logged_In'])) {
2088 82cd6022 PiBa-NL
		phpsession_end(true);
2089 55eb9c44 --global
		return false;
2090 1e0b1727 Phil Davis
	}
2091 55eb9c44 --global
2092
	/* If session timeout isn't set, we don't mark sessions stale */
2093 02647583 Ermal
	if (!isset($config['system']['webgui']['session_timeout'])) {
2094 bdadaf3c Chris Buechler
		/* Default to 4 hour timeout if one is not set */
2095
		if ($_SESSION['last_access'] < (time() - 14400)) {
2096 ce437697 Steve Beaver
			$_POST['logout'] = true;
2097 bdadaf3c Chris Buechler
			$_SESSION['Logout'] = true;
2098 1e0b1727 Phil Davis
		} else {
2099 1180e4f0 Sjon Hortensius
			$_SESSION['last_access'] = time();
2100 1e0b1727 Phil Davis
		}
2101 02647583 Ermal
	} else if (intval($config['system']['webgui']['session_timeout']) == 0) {
2102
		/* only update if it wasn't ajax */
2103 1e0b1727 Phil Davis
		if (!isAjax()) {
2104 02647583 Ermal
			$_SESSION['last_access'] = time();
2105 1e0b1727 Phil Davis
		}
2106 bdadaf3c Chris Buechler
	} else {
2107 55eb9c44 --global
		/* Check for stale session */
2108
		if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
2109 ce437697 Steve Beaver
			$_POST['logout'] = true;
2110 55eb9c44 --global
			$_SESSION['Logout'] = true;
2111
		} else {
2112
			/* only update if it wasn't ajax */
2113 1e0b1727 Phil Davis
			if (!isAjax()) {
2114 55eb9c44 --global
				$_SESSION['last_access'] = time();
2115 1e0b1727 Phil Davis
			}
2116 55eb9c44 --global
		}
2117
	}
2118
2119
	/* user hit the logout button */
2120 ce437697 Steve Beaver
	if (isset($_POST['logout'])) {
2121 55eb9c44 --global
2122 1e0b1727 Phil Davis
		if ($_SESSION['Logout']) {
2123 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()));
2124 1e0b1727 Phil Davis
		} else {
2125 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()));
2126 1e0b1727 Phil Davis
		}
2127 55eb9c44 --global
2128
		/* wipe out $_SESSION */
2129
		$_SESSION = array();
2130
2131 1e0b1727 Phil Davis
		if (isset($_COOKIE[session_name()])) {
2132 55eb9c44 --global
			setcookie(session_name(), '', time()-42000, '/');
2133 1e0b1727 Phil Davis
		}
2134 55eb9c44 --global
2135
		/* and destroy it */
2136 82cd6022 PiBa-NL
		phpsession_destroy();
2137 55eb9c44 --global
2138 cfbfd941 smos
		$scriptName = explode("/", $_SERVER["SCRIPT_FILENAME"]);
2139 55eb9c44 --global
		$scriptElms = count($scriptName);
2140
		$scriptName = $scriptName[$scriptElms-1];
2141
2142 1e0b1727 Phil Davis
		if (isAjax()) {
2143 55eb9c44 --global
			return false;
2144 1e0b1727 Phil Davis
		}
2145 55eb9c44 --global
2146
		/* redirect to page the user is on, it'll prompt them to login again */
2147 6f3d2063 Renato Botelho
		header("Location: {$scriptName}");
2148 55eb9c44 --global
2149
		return false;
2150
	}
2151
2152
	/*
2153
	 * this is for debugging purpose if you do not want to use Ajax
2154 1e0b1727 Phil Davis
	 * to submit a HTML form. It basically disables the observation
2155 55eb9c44 --global
	 * of the submit event and hence does not trigger Ajax.
2156
	 */
2157 8d58ebae Steve Beaver
	if ($_REQUEST['disable_ajax']) {
2158 55eb9c44 --global
		$_SESSION['NO_AJAX'] = "True";
2159 1e0b1727 Phil Davis
	}
2160 55eb9c44 --global
2161
	/*
2162
	 * Same to re-enable Ajax.
2163
	 */
2164 8d58ebae Steve Beaver
	if ($_REQUEST['enable_ajax']) {
2165 55eb9c44 --global
		unset($_SESSION['NO_AJAX']);
2166 1e0b1727 Phil Davis
	}
2167 82cd6022 PiBa-NL
	phpsession_end(true);
2168 55eb9c44 --global
	return true;
2169
}
2170
2171 16050763 Steve Beaver
function print_credit() {
2172
	global $g;
2173
2174
	return  '<a target="_blank" href="https://pfsense.org">' . $g["product_name"] . '</a>' .
2175
			gettext(' is developed and maintained by ') .
2176
			'<a target="_blank" href="https://netgate.com">Netgate. </a>' . ' &copy; ESF ' . $g["product_copyright_years"] .
2177
			'<a target="_blank" href="https://pfsense.org/license">' .
2178
			gettext(' View license.') . '</a>';
2179
}
2180 d629601a jim-p
function get_user_remote_address() {
2181
	$remote_address = $_SERVER['REMOTE_ADDR'];
2182
	if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
2183
		$remote_address .= "[{$_SERVER['HTTP_CLIENT_IP']}]";
2184
	} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
2185
		$remote_address .= "[{$_SERVER['HTTP_X_FORWARDED_FOR']}]";
2186
	}
2187
	return $remote_address;
2188
}
2189
function get_user_remote_authsource() {
2190
	$authsource = "";
2191
	if (!empty($_SESSION['authsource'])) {
2192
		$authsource .= " ({$_SESSION['authsource']})";
2193
	}
2194
	return $authsource;
2195
}
2196 88165371 Ermal
?>