Project

General

Profile

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