Project

General

Profile

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