Project

General

Profile

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