Project

General

Profile

Download (52 KB) Statistics
| Branch: | Tag: | Revision:
1 55eb9c44 --global
<?php
2 b37b4034 Phil Davis
/*
3 8acd654a Renato Botelho
 * auth.inc
4 995df6c3 Stephen Beaver
 *
5 8acd654a 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 2a2396a6 Renato Botelho
 * Copyright (c) 2004-2016 Rubicon Communications, LLC (Netgate)
10 8acd654a Renato Botelho
 * All rights reserved.
11 995df6c3 Stephen Beaver
 *
12 8acd654a Renato Botelho
 * Redistribution and use in source and binary forms, with or without
13
 * modification, are permitted provided that the following conditions are met:
14 995df6c3 Stephen Beaver
 *
15 8acd654a Renato Botelho
 * 1. Redistributions of source code must retain the above copyright notice,
16
 *    this list of conditions and the following disclaimer.
17 995df6c3 Stephen Beaver
 *
18 8acd654a Renato Botelho
 * 2. Redistributions in binary form must reproduce the above copyright
19
 *    notice, this list of conditions and the following disclaimer in
20
 *    the documentation and/or other materials provided with the
21
 *    distribution.
22 995df6c3 Stephen Beaver
 *
23 8acd654a Renato Botelho
 * 3. All advertising materials mentioning features or use of this software
24
 *    must display the following acknowledgment:
25
 *    "This product includes software developed by the pfSense Project
26
 *    for use in the pfSense® software distribution. (http://www.pfsense.org/).
27 995df6c3 Stephen Beaver
 *
28 8acd654a Renato Botelho
 * 4. The names "pfSense" and "pfSense Project" must not be used to
29
 *    endorse or promote products derived from this software without
30
 *    prior written permission. For written permission, please contact
31
 *    coreteam@pfsense.org.
32 995df6c3 Stephen Beaver
 *
33 8acd654a Renato Botelho
 * 5. Products derived from this software may not be called "pfSense"
34
 *    nor may "pfSense" appear in their names without prior written
35
 *    permission of the Electric Sheep Fencing, LLC.
36 995df6c3 Stephen Beaver
 *
37 8acd654a Renato Botelho
 * 6. Redistributions of any form whatsoever must retain the following
38
 *    acknowledgment:
39 995df6c3 Stephen Beaver
 *
40 8acd654a Renato Botelho
 * "This product includes software developed by the pfSense Project
41
 * for use in the pfSense software distribution (http://www.pfsense.org/).
42 995df6c3 Stephen Beaver
 *
43 8acd654a Renato Botelho
 * THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
44
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
46
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE pfSense PROJECT OR
47
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
48
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
49
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
50
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
51
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
52
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
53
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
54
 * OF THE POSSIBILITY OF SUCH DAMAGE.
55 995df6c3 Stephen Beaver
 */
56 8acd654a Renato Botelho
57 55eb9c44 --global
/*
58
 * NOTE : Portions of the mschapv2 support was based on the BSD licensed CHAP.php
59
 * file courtesy of Michael Retterklieber.
60
 */
61 1e0b1727 Phil Davis
if (!$do_not_include_config_gui_inc) {
62 052e65ef Scott Ullrich
	require_once("config.gui.inc");
63 1e0b1727 Phil Davis
}
64 55eb9c44 --global
65 9ae11a62 Scott Ullrich
// Will be changed to false if security checks fail
66
$security_passed = true;
67
68 1180e4f0 Sjon Hortensius
/* If this function doesn't exist, we're being called from Captive Portal or
69 0321fa1b jim-p
   another internal subsystem which does not include authgui.inc */
70 14eab6fb jim-p
if (function_exists("display_error_form") && !isset($config['system']['webgui']['nodnsrebindcheck'])) {
71 0734024c Chris Buechler
	/* DNS ReBinding attack prevention.  https://redmine.pfsense.org/issues/708 */
72 0321fa1b jim-p
	$found_host = false;
73 209620ea Seth Mos
74 4cf79fdd smos
	/* Either a IPv6 address with or without a alternate port */
75 1e0b1727 Phil Davis
	if (strstr($_SERVER['HTTP_HOST'], "]")) {
76 4cf79fdd smos
		$http_host_port = explode("]", $_SERVER['HTTP_HOST']);
77 209620ea Seth Mos
		/* v6 address has more parts, drop the last part */
78 1e0b1727 Phil Davis
		if (count($http_host_port) > 1) {
79 209620ea Seth Mos
			array_pop($http_host_port);
80
			$http_host = str_replace(array("[", "]"), "", implode(":", $http_host_port));
81
		} else {
82 4cf79fdd smos
			$http_host = str_replace(array("[", "]"), "", implode(":", $http_host_port));
83 209620ea Seth Mos
		}
84 7319dc73 jim-p
	} else {
85 4fcab77b smos
		$http_host = explode(":", $_SERVER['HTTP_HOST']);
86
		$http_host = $http_host[0];
87 7319dc73 jim-p
	}
88 1e0b1727 Phil Davis
	if (is_ipaddr($http_host) or $_SERVER['SERVER_ADDR'] == "127.0.0.1" or
89 46bb8a0b Sjon Hortensius
		strcasecmp($http_host, "localhost") == 0 or $_SERVER['SERVER_ADDR'] == "::1") {
90 9ae11a62 Scott Ullrich
		$found_host = true;
91 1e0b1727 Phil Davis
	}
92
	if (strcasecmp($http_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 or
93 46bb8a0b Sjon Hortensius
		strcasecmp($http_host, $config['system']['hostname']) == 0) {
94 d7bf3178 Erik Fonnesbeck
		$found_host = true;
95 1e0b1727 Phil Davis
	}
96 9ae11a62 Scott Ullrich
97 1e0b1727 Phil Davis
	if (is_array($config['dyndnses']['dyndns']) && !$found_host) {
98
		foreach ($config['dyndnses']['dyndns'] as $dyndns) {
99
			if (strcasecmp($dyndns['host'], $http_host) == 0) {
100 0321fa1b jim-p
				$found_host = true;
101 9ae11a62 Scott Ullrich
				break;
102
			}
103 1e0b1727 Phil Davis
		}
104
	}
105 7319dc73 jim-p
106 1e0b1727 Phil Davis
	if (is_array($config['dnsupdates']['dnsupdate']) && !$found_host) {
107
		foreach ($config['dnsupdates']['dnsupdate'] as $rfc2136) {
108
			if (strcasecmp($rfc2136['host'], $http_host) == 0) {
109 fa087612 jim-p
				$found_host = true;
110
				break;
111
			}
112 1e0b1727 Phil Davis
		}
113
	}
114 fa087612 jim-p
115 1e0b1727 Phil Davis
	if (!empty($config['system']['webgui']['althostnames']) && !$found_host) {
116 86b21903 jim-p
		$althosts = explode(" ", $config['system']['webgui']['althostnames']);
117 1e0b1727 Phil Davis
		foreach ($althosts as $ah) {
118
			if (strcasecmp($ah, $http_host) == 0 or strcasecmp($ah, $_SERVER['SERVER_ADDR']) == 0) {
119 86b21903 jim-p
				$found_host = true;
120 9ae11a62 Scott Ullrich
				break;
121
			}
122 1e0b1727 Phil Davis
		}
123 9b13f84b Scott Ullrich
	}
124 ce46b5da Scott Ullrich
125 1e0b1727 Phil Davis
	if ($found_host == false) {
126
		if (!security_checks_disabled()) {
127 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."));
128 9ae11a62 Scott Ullrich
			exit;
129
		}
130
		$security_passed = false;
131
	}
132
}
133 ef173724 Scott Ullrich
134 9ae11a62 Scott Ullrich
// If the HTTP_REFERER is something other than ourselves then disallow.
135 1e0b1727 Phil Davis
if (function_exists("display_error_form") && !isset($config['system']['webgui']['nohttpreferercheck'])) {
136
	if ($_SERVER['HTTP_REFERER']) {
137
		if (file_exists("{$g['tmp_path']}/setupwizard_lastreferrer")) {
138
			if ($_SERVER['HTTP_REFERER'] == file_get_contents("{$g['tmp_path']}/setupwizard_lastreferrer")) {
139 9ae11a62 Scott Ullrich
				unlink("{$g['tmp_path']}/setupwizard_lastreferrer");
140
				header("Refresh: 1; url=index.php");
141 1180e4f0 Sjon Hortensius
?>
142
<!DOCTYPE html>
143
<html lang="en">
144
<head>
145 b4738ddc NewEraCracker
	<link rel="stylesheet" href="/css/pfSense.css" />
146 1180e4f0 Sjon Hortensius
	<title><?=gettext("Redirecting..."); ?></title>
147
</head>
148
<body id="error" class="no-menu">
149
	<div id="jumbotron">
150
		<div class="container">
151 c7d61071 Sander van Leeuwen
			<div class="col-sm-offset-3 col-sm-6 col-xs-12">
152
				<p><?=gettext("Redirecting to the dashboard...")?></p>
153
			</div>
154 1180e4f0 Sjon Hortensius
		</div>
155
	</div>
156
</body>
157
</html>
158
<?php
159 9ae11a62 Scott Ullrich
				exit;
160
			}
161
		}
162
		$found_host = false;
163
		$referrer_host = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
164 e6f7e0be smos
		$referrer_host = str_replace(array("[", "]"), "", $referrer_host);
165 1e0b1727 Phil Davis
		if ($referrer_host) {
166 ae52d165 Renato Botelho
			if (strcasecmp($referrer_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 ||
167 4e322e2c Phil Davis
			    strcasecmp($referrer_host, $config['system']['hostname']) == 0) {
168 9ae11a62 Scott Ullrich
				$found_host = true;
169 1e0b1727 Phil Davis
			}
170 9f0bee02 jim-p
171 1e0b1727 Phil Davis
			if (!empty($config['system']['webgui']['althostnames']) && !$found_host) {
172 9ae11a62 Scott Ullrich
				$althosts = explode(" ", $config['system']['webgui']['althostnames']);
173
				foreach ($althosts as $ah) {
174 1e0b1727 Phil Davis
					if (strcasecmp($referrer_host, $ah) == 0) {
175 9ae11a62 Scott Ullrich
						$found_host = true;
176
						break;
177
					}
178
				}
179
			}
180 9f0bee02 jim-p
181 1e0b1727 Phil Davis
			if (is_array($config['dyndnses']['dyndns']) && !$found_host) {
182
				foreach ($config['dyndnses']['dyndns'] as $dyndns) {
183
					if (strcasecmp($dyndns['host'], $referrer_host) == 0) {
184 9f0bee02 jim-p
						$found_host = true;
185
						break;
186
					}
187 1e0b1727 Phil Davis
				}
188
			}
189 9f0bee02 jim-p
190 1e0b1727 Phil Davis
			if (is_array($config['dnsupdates']['dnsupdate']) && !$found_host) {
191
				foreach ($config['dnsupdates']['dnsupdate'] as $rfc2136) {
192
					if (strcasecmp($rfc2136['host'], $referrer_host) == 0) {
193 9f0bee02 jim-p
						$found_host = true;
194
						break;
195
					}
196 1e0b1727 Phil Davis
				}
197
			}
198 9f0bee02 jim-p
199 1e0b1727 Phil Davis
			if (!$found_host) {
200 9ae11a62 Scott Ullrich
				$interface_list_ips = get_configured_ip_addresses();
201 1e0b1727 Phil Davis
				foreach ($interface_list_ips as $ilips) {
202
					if (strcasecmp($referrer_host, $ilips) == 0) {
203 9ae11a62 Scott Ullrich
						$found_host = true;
204
						break;
205
					}
206
				}
207 337f8296 NewEraCracker
				$interface_list_ipv6s = get_configured_ipv6_addresses(true);
208 1e0b1727 Phil Davis
				foreach ($interface_list_ipv6s as $ilipv6s) {
209 337f8296 NewEraCracker
					$ilipv6s = explode('%', $ilipv6s)[0];
210 1e0b1727 Phil Davis
					if (strcasecmp($referrer_host, $ilipv6s) == 0) {
211 e6f7e0be smos
						$found_host = true;
212
						break;
213
					}
214
				}
215 1e0b1727 Phil Davis
				if ($referrer_host == "127.0.0.1" || $referrer_host == "localhost") {
216 17dd7ff3 Chris Buechler
					// allow SSH port forwarded connections and links from localhost
217
					$found_host = true;
218
				}
219 9ae11a62 Scott Ullrich
			}
220
		}
221 1e0b1727 Phil Davis
		if ($found_host == false) {
222
			if (!security_checks_disabled()) {
223 1c92c5b1 Stephen Beaver
				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.");
224 0f806eca Erik Fonnesbeck
				exit;
225
			}
226 9ae11a62 Scott Ullrich
			$security_passed = false;
227
		}
228 1e0b1727 Phil Davis
	} else {
229 9ae11a62 Scott Ullrich
		$security_passed = false;
230 1e0b1727 Phil Davis
	}
231 4fe9c2dc Scott Ullrich
}
232
233 1e0b1727 Phil Davis
if (function_exists("display_error_form") && $security_passed) {
234 9ae11a62 Scott Ullrich
	/* Security checks passed, so it should be OK to turn them back on */
235
	restore_security_checks();
236 1e0b1727 Phil Davis
}
237 9ae11a62 Scott Ullrich
unset($security_passed);
238
239 55eb9c44 --global
$groupindex = index_groups();
240
$userindex = index_users();
241
242
function index_groups() {
243
	global $g, $debug, $config, $groupindex;
244
245
	$groupindex = array();
246
247 6dcd80af Ermal
	if (is_array($config['system']['group'])) {
248 55eb9c44 --global
		$i = 0;
249 1e0b1727 Phil Davis
		foreach ($config['system']['group'] as $groupent) {
250 55eb9c44 --global
			$groupindex[$groupent['name']] = $i;
251
			$i++;
252
		}
253
	}
254
255
	return ($groupindex);
256
}
257
258
function index_users() {
259
	global $g, $debug, $config;
260
261 6dcd80af Ermal
	if (is_array($config['system']['user'])) {
262 55eb9c44 --global
		$i = 0;
263 1e0b1727 Phil Davis
		foreach ($config['system']['user'] as $userent) {
264 55eb9c44 --global
			$userindex[$userent['name']] = $i;
265
			$i++;
266
		}
267
	}
268
269
	return ($userindex);
270
}
271
272
function & getUserEntry($name) {
273
	global $debug, $config, $userindex;
274 100d0f77 jim-p
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
275
276 1e0b1727 Phil Davis
	if (isset($userindex[$name])) {
277 55eb9c44 --global
		return $config['system']['user'][$userindex[$name]];
278 100d0f77 jim-p
	} elseif ($authcfg['type'] != "Local Database") {
279
		$user = array();
280
		$user['name'] = $name;
281
		return $user;
282 1e0b1727 Phil Davis
	}
283 55eb9c44 --global
}
284
285
function & getUserEntryByUID($uid) {
286
	global $debug, $config;
287 84924e76 Ermal
288 1e0b1727 Phil Davis
	if (is_array($config['system']['user'])) {
289
		foreach ($config['system']['user'] as & $user) {
290
			if ($user['uid'] == $uid) {
291 84924e76 Ermal
				return $user;
292 1e0b1727 Phil Davis
			}
293
		}
294
	}
295 55eb9c44 --global
296
	return false;
297
}
298
299
function & getGroupEntry($name) {
300
	global $debug, $config, $groupindex;
301 1e0b1727 Phil Davis
	if (isset($groupindex[$name])) {
302 55eb9c44 --global
		return $config['system']['group'][$groupindex[$name]];
303 1e0b1727 Phil Davis
	}
304 55eb9c44 --global
}
305
306
function & getGroupEntryByGID($gid) {
307
	global $debug, $config;
308 84924e76 Ermal
309 1e0b1727 Phil Davis
	if (is_array($config['system']['group'])) {
310
		foreach ($config['system']['group'] as & $group) {
311
			if ($group['gid'] == $gid) {
312 84924e76 Ermal
				return $group;
313 1e0b1727 Phil Davis
			}
314
		}
315
	}
316 55eb9c44 --global
317
	return false;
318
}
319
320 6dc88d53 Ermal Luci
function get_user_privileges(& $user) {
321 990c00c4 Renato Botelho
	global $config;
322 100d0f77 jim-p
323
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
324 990c00c4 Renato Botelho
	$names = array();
325 6dc88d53 Ermal Luci
326 1e0b1727 Phil Davis
	$privs = $user['priv'];
327
	if (!is_array($privs)) {
328
		$privs = array();
329
	}
330 6dc88d53 Ermal Luci
331 100d0f77 jim-p
	if ($authcfg['type'] == "ldap") {
332 990c00c4 Renato Botelho
		$names = @ldap_get_groups($user['name'], $authcfg);
333 100d0f77 jim-p
	} elseif ($authcfg['type'] == "radius") {
334 990c00c4 Renato Botelho
		$names = @radius_get_groups($_SESSION['user_radius_attributes']);
335 100d0f77 jim-p
	}
336
337 990c00c4 Renato Botelho
	if (empty($names)) {
338
		$names = local_user_get_groups($user, true);
339 100d0f77 jim-p
	}
340 6dc88d53 Ermal Luci
341 990c00c4 Renato Botelho
	foreach ($names as $name) {
342
		$group = getGroupEntry($name);
343
		if (is_array($group['priv'])) {
344
			$privs = array_merge($privs, $group['priv']);
345 1e0b1727 Phil Davis
		}
346
	}
347 6dc88d53 Ermal Luci
348 1e0b1727 Phil Davis
	return $privs;
349 6dc88d53 Ermal Luci
}
350
351
function userHasPrivilege($userent, $privid = false) {
352
353 1e0b1727 Phil Davis
	if (!$privid || !is_array($userent)) {
354
		return false;
355
	}
356 6dc88d53 Ermal Luci
357 1e0b1727 Phil Davis
	$privs = get_user_privileges($userent);
358 6dc88d53 Ermal Luci
359 1e0b1727 Phil Davis
	if (!is_array($privs)) {
360
		return false;
361
	}
362 6dc88d53 Ermal Luci
363 1e0b1727 Phil Davis
	if (!in_array($privid, $privs)) {
364
		return false;
365
	}
366 6dc88d53 Ermal Luci
367 1e0b1727 Phil Davis
	return true;
368 6dc88d53 Ermal Luci
}
369
370 55eb9c44 --global
function local_backed($username, $passwd) {
371
372
	$user = getUserEntry($username);
373 1e0b1727 Phil Davis
	if (!$user) {
374 55eb9c44 --global
		return false;
375 1e0b1727 Phil Davis
	}
376 55eb9c44 --global
377 1e0b1727 Phil Davis
	if (is_account_disabled($username) || is_account_expired($username)) {
378 a13ce628 Ermal Lu?i
		return false;
379 1e0b1727 Phil Davis
	}
380 a13ce628 Ermal Lu?i
381 9219378b daniel
	if ($user['bcrypt-hash']) {
382
		if (password_verify($passwd, $user['bcrypt-hash'])) {
383
			return true;
384
		}
385
	}
386
387
	//for backwards compatibility
388 1e0b1727 Phil Davis
	if ($user['password']) {
389
		if (crypt($passwd, $user['password']) == $user['password']) {
390 55eb9c44 --global
			return true;
391 1e0b1727 Phil Davis
		}
392 55eb9c44 --global
	}
393
394 1e0b1727 Phil Davis
	if ($user['md5-hash']) {
395
		if (md5($passwd) == $user['md5-hash']) {
396 55eb9c44 --global
			return true;
397 1e0b1727 Phil Davis
		}
398 55eb9c44 --global
	}
399
400
	return false;
401
}
402
403
function local_sync_accounts() {
404
	global $debug, $config;
405
	conf_mount_rw();
406
407
	/* remove local users to avoid uid conflicts */
408
	$fd = popen("/usr/sbin/pw usershow -a", "r");
409
	if ($fd) {
410
		while (!feof($fd)) {
411 4de8f7ba Phil Davis
			$line = explode(":", fgets($fd));
412 237e70c2 Renato Botelho
			if ($line[0] != "admin") {
413
				if (!strncmp($line[0], "_", 1)) {
414
					continue;
415
				}
416
				if ($line[2] < 2000) {
417
					continue;
418
				}
419
				if ($line[2] > 65000) {
420
					continue;
421
				}
422 1e0b1727 Phil Davis
			}
423 2b41df9c Renato Botelho
			/*
424
			 * If a crontab was created to user, pw userdel will be interactive and
425
			 * can cause issues. Just remove crontab before run it when necessary
426
			 */
427
			unlink_if_exists("/var/cron/tabs/{$line[0]}");
428 1929acf1 jim-p
			$cmd = "/usr/sbin/pw userdel -n " . escapeshellarg($line[0]);
429 1e0b1727 Phil Davis
			if ($debug) {
430 94021404 Carlos Eduardo Ramos
				log_error(sprintf(gettext("Running: %s"), $cmd));
431 1e0b1727 Phil Davis
			}
432 55eb9c44 --global
			mwexec($cmd);
433
		}
434
		pclose($fd);
435
	}
436
437
	/* remove local groups to avoid gid conflicts */
438
	$gids = array();
439
	$fd = popen("/usr/sbin/pw groupshow -a", "r");
440
	if ($fd) {
441
		while (!feof($fd)) {
442 4de8f7ba Phil Davis
			$line = explode(":", fgets($fd));
443 1e0b1727 Phil Davis
			if (!strncmp($line[0], "_", 1)) {
444 55eb9c44 --global
				continue;
445 1e0b1727 Phil Davis
			}
446
			if ($line[2] < 2000) {
447 55eb9c44 --global
				continue;
448 1e0b1727 Phil Davis
			}
449
			if ($line[2] > 65000) {
450 55eb9c44 --global
				continue;
451 1e0b1727 Phil Davis
			}
452 1929acf1 jim-p
			$cmd = "/usr/sbin/pw groupdel -g " . escapeshellarg($line[2]);
453 1e0b1727 Phil Davis
			if ($debug) {
454 94021404 Carlos Eduardo Ramos
				log_error(sprintf(gettext("Running: %s"), $cmd));
455 1e0b1727 Phil Davis
			}
456 55eb9c44 --global
			mwexec($cmd);
457
		}
458
		pclose($fd);
459
	}
460
461
	/* make sure the all group exists */
462
	$allgrp = getGroupEntryByGID(1998);
463
	local_group_set($allgrp, true);
464
465 5af2baf7 jim-p
	/* sync all local users */
466 1e0b1727 Phil Davis
	if (is_array($config['system']['user'])) {
467
		foreach ($config['system']['user'] as $user) {
468 5af2baf7 jim-p
			local_user_set($user);
469 1e0b1727 Phil Davis
		}
470
	}
471 5af2baf7 jim-p
472 f3e0a111 jim-p
	/* sync all local groups */
473 1e0b1727 Phil Davis
	if (is_array($config['system']['group'])) {
474
		foreach ($config['system']['group'] as $group) {
475 f3e0a111 jim-p
			local_group_set($group);
476 1e0b1727 Phil Davis
		}
477
	}
478 f3e0a111 jim-p
479 55eb9c44 --global
	conf_mount_ro();
480
481
}
482
483
function local_user_set(& $user) {
484
	global $g, $debug;
485
486 9219378b daniel
	if (empty($user['password']) && empty($user['bcrypt-hash'])) {
487 1c92c5b1 Stephen Beaver
		log_error("There is something wrong in the config because user {$user['name']} password is missing!");
488 b3c106a0 Ermal
		return;
489
	}
490
491 2bb07efc Scott Ullrich
	conf_mount_rw();
492
493 1180e4f0 Sjon Hortensius
	$home_base = "/home/";
494 55eb9c44 --global
	$user_uid = $user['uid'];
495
	$user_name = $user['name'];
496 461df7c0 jim-p
	$user_home = "{$home_base}{$user_name}";
497 55eb9c44 --global
	$user_shell = "/etc/rc.initial";
498
	$user_group = "nobody";
499
500
	// Ensure $home_base exists and is writable
501 1e0b1727 Phil Davis
	if (!is_dir($home_base)) {
502 55eb9c44 --global
		mkdir($home_base, 0755);
503 1e0b1727 Phil Davis
	}
504 55eb9c44 --global
505 df8d74de jim-p
	$lock_account = false;
506 55eb9c44 --global
	/* configure shell type */
507 3e251b12 Erik Fonnesbeck
	/* Cases here should be ordered by most privileged to least privileged. */
508 a137fedd jim-p
	if (userHasPrivilege($user, "user-shell-access") || userHasPrivilege($user, "page-all")) {
509 29293dce jim-p
		$user_shell = "/bin/tcsh";
510 1ed86bc6 jim-p
	} elseif (userHasPrivilege($user, "user-copy-files")) {
511 a137fedd jim-p
		$user_shell = "/usr/local/bin/scponly";
512 3e251b12 Erik Fonnesbeck
	} elseif (userHasPrivilege($user, "user-ssh-tunnel")) {
513
		$user_shell = "/usr/local/sbin/ssh_tunnel_shell";
514 fbfd675a jim-p
	} elseif (userHasPrivilege($user, "user-ipsec-xauth-dialin")) {
515
		$user_shell = "/sbin/nologin";
516 1ed86bc6 jim-p
	} else {
517
		$user_shell = "/sbin/nologin";
518 df8d74de jim-p
		$lock_account = true;
519
	}
520
521
	/* Lock out disabled or expired users, unless it's root/admin. */
522
	if ((is_account_disabled($user_name) || is_account_expired($user_name)) && ($user_uid != 0)) {
523
		$user_shell = "/sbin/nologin";
524
		$lock_account = true;
525 55eb9c44 --global
	}
526
527
	/* root user special handling */
528
	if ($user_uid == 0) {
529
		$cmd = "/usr/sbin/pw usermod -q -n root -s /bin/sh -H 0";
530 1e0b1727 Phil Davis
		if ($debug) {
531 94021404 Carlos Eduardo Ramos
			log_error(sprintf(gettext("Running: %s"), $cmd));
532 1e0b1727 Phil Davis
		}
533 55eb9c44 --global
		$fd = popen($cmd, "w");
534 9219378b daniel
		if (empty($user['bcrypt-hash'])) {
535
			fwrite($fd, $user['password']);
536 9a7911eb Daniel Vinakovsky
		} else {
537 9219378b daniel
			fwrite($fd, $user['bcrypt-hash']);
538
		}
539 55eb9c44 --global
		pclose($fd);
540
		$user_group = "wheel";
541 2708e399 jim-p
		$user_home = "/root";
542 29293dce jim-p
		$user_shell = "/etc/rc.initial";
543 55eb9c44 --global
	}
544
545
	/* read from pw db */
546 9fd14591 jim-p
	$fd = popen("/usr/sbin/pw usershow -n {$user_name} 2>&1", "r");
547 55eb9c44 --global
	$pwread = fgets($fd);
548
	pclose($fd);
549 9fd14591 jim-p
	$userattrs = explode(":", trim($pwread));
550 55eb9c44 --global
551
	/* determine add or mod */
552 9fd14591 jim-p
	if (($userattrs[0] != $user['name']) || (!strncmp($pwread, "pw:", 3))) {
553 4b49a8a9 jim-p
		$user_op = "useradd -m -k /etc/skel -o";
554 38564fde smos
	} else {
555 55eb9c44 --global
		$user_op = "usermod";
556 38564fde smos
	}
557 55eb9c44 --global
558 1180e4f0 Sjon Hortensius
	$comment = str_replace(array(":", "!", "@"), " ", $user['descr']);
559 55eb9c44 --global
	/* add or mod pw db */
560 1929acf1 jim-p
	$cmd = "/usr/sbin/pw {$user_op} -q " .
561
			" -u " . escapeshellarg($user_uid) .
562
			" -n " . escapeshellarg($user_name) .
563
			" -g " . escapeshellarg($user_group) .
564
			" -s " . escapeshellarg($user_shell) .
565
			" -d " . escapeshellarg($user_home) .
566
			" -c " . escapeshellarg($comment) .
567
			" -H 0 2>&1";
568 55eb9c44 --global
569 1e0b1727 Phil Davis
	if ($debug) {
570 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("Running: %s"), $cmd));
571 1e0b1727 Phil Davis
	}
572 55eb9c44 --global
	$fd = popen($cmd, "w");
573 9219378b daniel
	if (empty($user['bcrypt-hash'])) {
574
		fwrite($fd, $user['password']);
575 9a7911eb Daniel Vinakovsky
	} else {
576 9219378b daniel
		fwrite($fd, $user['bcrypt-hash']);
577
	}
578 55eb9c44 --global
	pclose($fd);
579
580
	/* create user directory if required */
581
	if (!is_dir($user_home)) {
582
		mkdir($user_home, 0700);
583
	}
584 23c652cd Ermal
	@chown($user_home, $user_name);
585
	@chgrp($user_home, $user_group);
586 55eb9c44 --global
587
	/* write out ssh authorized key file */
588 1e0b1727 Phil Davis
	if ($user['authorizedkeys']) {
589 a2286360 Ermal Lu?i
		if (!is_dir("{$user_home}/.ssh")) {
590 23c652cd Ermal
			@mkdir("{$user_home}/.ssh", 0700);
591
			@chown("{$user_home}/.ssh", $user_name);
592 a2286360 Ermal Lu?i
		}
593
		$keys = base64_decode($user['authorizedkeys']);
594 23c652cd Ermal
		@file_put_contents("{$user_home}/.ssh/authorized_keys", $keys);
595
		@chown("{$user_home}/.ssh/authorized_keys", $user_name);
596 1e0b1727 Phil Davis
	} else {
597 cdab65cc Erik Fonnesbeck
		unlink_if_exists("{$user_home}/.ssh/authorized_keys");
598 1e0b1727 Phil Davis
	}
599 df8d74de jim-p
600
	$un = $lock_account ? "" : "un";
601 1929acf1 jim-p
	exec("/usr/sbin/pw {$un}lock " . escapeshellarg($user_name) . " -q 2>/dev/null");
602 1180e4f0 Sjon Hortensius
603 2bb07efc Scott Ullrich
	conf_mount_ro();
604 55eb9c44 --global
}
605
606
function local_user_del($user) {
607
	global $debug;
608 2bb07efc Scott Ullrich
609 55eb9c44 --global
	/* remove all memberships */
610 019e6c3f jim-p
	local_user_set_groups($user);
611 55eb9c44 --global
612 a39675ec jim-p
	/* Don't remove /root */
613 1e0b1727 Phil Davis
	if ($user['uid'] != 0) {
614 a39675ec jim-p
		$rmhome = "-r";
615 1e0b1727 Phil Davis
	}
616 a39675ec jim-p
617 9fd14591 jim-p
	/* read from pw db */
618
	$fd = popen("/usr/sbin/pw usershow -n {$user['name']} 2>&1", "r");
619
	$pwread = fgets($fd);
620
	pclose($fd);
621
	$userattrs = explode(":", trim($pwread));
622
623
	if ($userattrs[0] != $user['name']) {
624
		log_error("Tried to remove user {$user['name']} but got user {$userattrs[0]} instead. Bailing.");
625
		return;
626
	}
627
628 55eb9c44 --global
	/* delete from pw db */
629 1929acf1 jim-p
	$cmd = "/usr/sbin/pw userdel -n " . escapeshellarg($user['name']) . " " . escapeshellarg($rmhome);
630 55eb9c44 --global
631 1e0b1727 Phil Davis
	if ($debug) {
632 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("Running: %s"), $cmd));
633 1e0b1727 Phil Davis
	}
634 0914b6bb Ermal
	mwexec($cmd);
635 2bb07efc Scott Ullrich
636 0914b6bb Ermal
	/* Delete user from groups needs a call to write_config() */
637
	local_group_del_user($user);
638 55eb9c44 --global
}
639
640 4d9801c2 Jim Thompson
function local_user_set_password(&$user, $password) {
641 55eb9c44 --global
642 33386b07 Daniel Vinakovsky
	unset($user['password']);
643
	unset($user['md5-hash']);
644
	$user['bcrypt-hash'] = password_hash($password, PASSWORD_BCRYPT);
645 55eb9c44 --global
646 4d4e9a11 Daniel Vinakovsky
	/* Maintain compatibility with FreeBSD - change $2y$ prefix to $2b$
647
	 * https://reviews.freebsd.org/D2742
648 6fadbf9b Dan Vinakovsky
	 * XXX: Can be removed as soon as r284483 is MFC'd.
649 4d4e9a11 Daniel Vinakovsky
	 */
650 4b737f6e Daniel Vinakovsky
	if ($user['bcrypt-hash'][2] == "y") {
651
		$user['bcrypt-hash'][2] = "b";
652
	}
653
654 55eb9c44 --global
	// Converts ascii to unicode.
655
	$astr = (string) $password;
656
	$ustr = '';
657
	for ($i = 0; $i < strlen($astr); $i++) {
658
		$a = ord($astr{$i}) << 8;
659 4de8f7ba Phil Davis
		$ustr .= sprintf("%X", $a);
660 55eb9c44 --global
	}
661
662
}
663
664
function local_user_get_groups($user, $all = false) {
665
	global $debug, $config;
666
667
	$groups = array();
668 1e0b1727 Phil Davis
	if (!is_array($config['system']['group'])) {
669 55eb9c44 --global
		return $groups;
670 1e0b1727 Phil Davis
	}
671 55eb9c44 --global
672 1e0b1727 Phil Davis
	foreach ($config['system']['group'] as $group) {
673 4de8f7ba Phil Davis
		if ($all || (!$all && ($group['name'] != "all"))) {
674 1e0b1727 Phil Davis
			if (is_array($group['member'])) {
675
				if (in_array($user['uid'], $group['member'])) {
676 55eb9c44 --global
					$groups[] = $group['name'];
677 1e0b1727 Phil Davis
				}
678
			}
679
		}
680
	}
681 55eb9c44 --global
682 1e0b1727 Phil Davis
	if ($all) {
683 b0c231e4 jim-p
		$groups[] = "all";
684 1e0b1727 Phil Davis
	}
685 b0c231e4 jim-p
686 55eb9c44 --global
	sort($groups);
687
688
	return $groups;
689 1180e4f0 Sjon Hortensius
690 55eb9c44 --global
}
691
692 4de8f7ba Phil Davis
function local_user_set_groups($user, $new_groups = NULL) {
693 55eb9c44 --global
	global $debug, $config, $groupindex;
694 4de8f7ba Phil Davis
695 1e0b1727 Phil Davis
	if (!is_array($config['system']['group'])) {
696 55eb9c44 --global
		return;
697 1e0b1727 Phil Davis
	}
698 55eb9c44 --global
699 739c78ac jim-p
	$cur_groups = local_user_get_groups($user, true);
700 55eb9c44 --global
	$mod_groups = array();
701
702 1e0b1727 Phil Davis
	if (!is_array($new_groups)) {
703 55eb9c44 --global
		$new_groups = array();
704 1e0b1727 Phil Davis
	}
705 55eb9c44 --global
706 1e0b1727 Phil Davis
	if (!is_array($cur_groups)) {
707 55eb9c44 --global
		$cur_groups = array();
708 1e0b1727 Phil Davis
	}
709 55eb9c44 --global
710
	/* determine which memberships to add */
711
	foreach ($new_groups as $groupname) {
712 4de8f7ba Phil Davis
		if ($groupname == '' || in_array($groupname, $cur_groups)) {
713 55eb9c44 --global
			continue;
714 1e0b1727 Phil Davis
		}
715 55eb9c44 --global
		$group = & $config['system']['group'][$groupindex[$groupname]];
716
		$group['member'][] = $user['uid'];
717
		$mod_groups[] = $group;
718
	}
719 9ae11a62 Scott Ullrich
	unset($group);
720 55eb9c44 --global
721
	/* determine which memberships to remove */
722
	foreach ($cur_groups as $groupname) {
723 4de8f7ba Phil Davis
		if (in_array($groupname, $new_groups)) {
724 e879fc81 Ermal
			continue;
725 1e0b1727 Phil Davis
		}
726
		if (!isset($config['system']['group'][$groupindex[$groupname]])) {
727 25fec9b3 jim-p
			continue;
728 1e0b1727 Phil Davis
		}
729 55eb9c44 --global
		$group = & $config['system']['group'][$groupindex[$groupname]];
730 7b5c56ea jim-p
		if (is_array($group['member'])) {
731
			$index = array_search($user['uid'], $group['member']);
732
			array_splice($group['member'], $index, 1);
733
			$mod_groups[] = $group;
734
		}
735 55eb9c44 --global
	}
736 9ae11a62 Scott Ullrich
	unset($group);
737 55eb9c44 --global
738
	/* sync all modified groups */
739 1e0b1727 Phil Davis
	foreach ($mod_groups as $group) {
740 55eb9c44 --global
		local_group_set($group);
741 1e0b1727 Phil Davis
	}
742 55eb9c44 --global
}
743
744 0914b6bb Ermal
function local_group_del_user($user) {
745
	global $config;
746
747 1e0b1727 Phil Davis
	if (!is_array($config['system']['group'])) {
748
		return;
749
	}
750 0914b6bb Ermal
751 1e0b1727 Phil Davis
	foreach ($config['system']['group'] as $group) {
752 0914b6bb Ermal
		if (is_array($group['member'])) {
753
			foreach ($group['member'] as $idx => $uid) {
754 1e0b1727 Phil Davis
				if ($user['uid'] == $uid) {
755 0914b6bb Ermal
					unset($config['system']['group']['member'][$idx]);
756 1e0b1727 Phil Davis
				}
757 0914b6bb Ermal
			}
758
		}
759
	}
760
}
761
762 55eb9c44 --global
function local_group_set($group, $reset = false) {
763
	global $debug;
764
765
	$group_name = $group['name'];
766
	$group_gid = $group['gid'];
767 baca968c Ermal
	$group_members = '';
768 1e0b1727 Phil Davis
	if (!$reset && !empty($group['member']) && count($group['member']) > 0) {
769 4de8f7ba Phil Davis
		$group_members = implode(",", $group['member']);
770 1e0b1727 Phil Davis
	}
771 55eb9c44 --global
772 792adb45 Chris Buechler
	if (empty($group_name) || $group['scope'] == "remote") {
773 baca968c Ermal
		return;
774 1e0b1727 Phil Davis
	}
775 baca968c Ermal
776 55eb9c44 --global
	/* determine add or mod */
777 1929acf1 jim-p
	if (mwexec("/usr/sbin/pw groupshow -g " . escapeshellarg($group_gid) . " 2>&1", true) == 0) {
778 7cb01159 Chris Buechler
		$group_op = "groupmod -l";
779 1e0b1727 Phil Davis
	} else {
780 7cb01159 Chris Buechler
		$group_op = "groupadd -n";
781 1e0b1727 Phil Davis
	}
782 55eb9c44 --global
783
	/* add or mod group db */
784 1929acf1 jim-p
	$cmd = "/usr/sbin/pw {$group_op} " .
785
		escapeshellarg($group_name) .
786
		" -g " . escapeshellarg($group_gid) .
787
		" -M " . escapeshellarg($group_members) . " 2>&1";
788 55eb9c44 --global
789 1e0b1727 Phil Davis
	if ($debug) {
790 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("Running: %s"), $cmd));
791 1e0b1727 Phil Davis
	}
792 0914b6bb Ermal
	mwexec($cmd);
793 55eb9c44 --global
794
}
795
796
function local_group_del($group) {
797
	global $debug;
798
799
	/* delete from group db */
800 1929acf1 jim-p
	$cmd = "/usr/sbin/pw groupdel " . escapeshellarg($group['name']);
801 55eb9c44 --global
802 1e0b1727 Phil Davis
	if ($debug) {
803 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("Running: %s"), $cmd));
804 1e0b1727 Phil Davis
	}
805 0914b6bb Ermal
	mwexec($cmd);
806 55eb9c44 --global
}
807
808 6306b5dd Ermal Lu?i
function ldap_test_connection($authcfg) {
809 55eb9c44 --global
	global $debug, $config, $g;
810
811 c61e4626 Ermal Lu?i
	if ($authcfg) {
812 836c858f derelict-pf
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
813 1e0b1727 Phil Davis
			$ldapproto = "ldaps";
814 836c858f derelict-pf
		} else {
815
			$ldapproto = "ldap";
816 1e0b1727 Phil Davis
		}
817
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
818
		$ldapport = $authcfg['ldap_port'];
819
		if (!empty($ldapport)) {
820 9f27de6d jim-p
			$ldapserver .= ":{$ldapport}";
821 1e0b1727 Phil Davis
		}
822
		$ldapbasedn = $authcfg['ldap_basedn'];
823
		$ldapbindun = $authcfg['ldap_binddn'];
824
		$ldapbindpw = $authcfg['ldap_bindpw'];
825
	} else {
826 6306b5dd Ermal Lu?i
		return false;
827 1e0b1727 Phil Davis
	}
828 55eb9c44 --global
829 1e0b1727 Phil Davis
	/* first check if there is even an LDAP server populated */
830 4de8f7ba Phil Davis
	if (!$ldapserver) {
831 1e0b1727 Phil Davis
		return false;
832
	}
833 c61e4626 Ermal Lu?i
834 1e0b1727 Phil Davis
	/* Setup CA environment if needed. */
835
	ldap_setup_caenv($authcfg);
836 fe2031ab Ermal
837 1e0b1727 Phil Davis
	/* connect and see if server is up */
838
	$error = false;
839
	if (!($ldap = ldap_connect($ldapserver))) {
840 9f27de6d jim-p
		$error = true;
841 1e0b1727 Phil Davis
	}
842 c61e4626 Ermal Lu?i
843 1e0b1727 Phil Davis
	if ($error == true) {
844
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
845
		return false;
846
	}
847 55eb9c44 --global
848
	return true;
849
}
850
851 fe2031ab Ermal
function ldap_setup_caenv($authcfg) {
852
	global $g;
853 007e59d2 jim-p
	require_once("certs.inc");
854 fe2031ab Ermal
855
	unset($caref);
856 836c858f derelict-pf
	if (empty($authcfg['ldap_caref']) || strstr($authcfg['ldap_urltype'], "Standard")) {
857 fe2031ab Ermal
		putenv('LDAPTLS_REQCERT=never');
858
		return;
859
	} else {
860 a7702ed5 Ermal
		$caref = lookup_ca($authcfg['ldap_caref']);
861 fe2031ab Ermal
		if (!$caref) {
862 a7702ed5 Ermal
			log_error(sprintf(gettext("LDAP: Could not lookup CA by reference for host %s."), $authcfg['ldap_caref']));
863 fe2031ab Ermal
			/* XXX: Prevent for credential leaking since we cannot setup the CA env. Better way? */
864
			putenv('LDAPTLS_REQCERT=hard');
865
			return;
866
		}
867 1e0b1727 Phil Davis
		if (!is_dir("{$g['varrun_path']}/certs")) {
868 fe2031ab Ermal
			@mkdir("{$g['varrun_path']}/certs");
869 1e0b1727 Phil Davis
		}
870
		if (file_exists("{$g['varrun_path']}/certs/{$caref['refid']}.ca")) {
871 b2a0a8e9 jim-p
			@unlink("{$g['varrun_path']}/certs/{$caref['refid']}.ca");
872 1e0b1727 Phil Davis
		}
873 b2a0a8e9 jim-p
		file_put_contents("{$g['varrun_path']}/certs/{$caref['refid']}.ca", base64_decode($caref['crt']));
874
		@chmod("{$g['varrun_path']}/certs/{$caref['refid']}.ca", 0600);
875 fe2031ab Ermal
		putenv('LDAPTLS_REQCERT=hard');
876
		/* XXX: Probably even the hashed link should be created for this? */
877 906daddc Ermal
		putenv("LDAPTLS_CACERTDIR={$g['varrun_path']}/certs");
878 b2a0a8e9 jim-p
		putenv("LDAPTLS_CACERT={$g['varrun_path']}/certs/{$caref['refid']}.ca");
879 fe2031ab Ermal
	}
880
}
881
882 6306b5dd Ermal Lu?i
function ldap_test_bind($authcfg) {
883 55eb9c44 --global
	global $debug, $config, $g;
884
885 c61e4626 Ermal Lu?i
	if ($authcfg) {
886 836c858f derelict-pf
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
887 1e0b1727 Phil Davis
			$ldapproto = "ldaps";
888 836c858f derelict-pf
		} else {
889
			$ldapproto = "ldap";
890 1e0b1727 Phil Davis
		}
891
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
892
		$ldapport = $authcfg['ldap_port'];
893
		if (!empty($ldapport)) {
894 9f27de6d jim-p
			$ldapserver .= ":{$ldapport}";
895 1e0b1727 Phil Davis
		}
896
		$ldapbasedn = $authcfg['ldap_basedn'];
897
		$ldapbindun = $authcfg['ldap_binddn'];
898
		$ldapbindpw = $authcfg['ldap_bindpw'];
899
		$ldapver = $authcfg['ldap_protver'];
900 45859aae Chris Buechler
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
901 1e0b1727 Phil Davis
		if (empty($ldapbndun) || empty($ldapbindpw)) {
902
			$ldapanon = true;
903
		} else {
904
			$ldapanon = false;
905
		}
906
	} else {
907 6306b5dd Ermal Lu?i
		return false;
908 1e0b1727 Phil Davis
	}
909 c61e4626 Ermal Lu?i
910
	/* first check if there is even an LDAP server populated */
911 1e0b1727 Phil Davis
	if (!$ldapserver) {
912
		return false;
913
	}
914 c61e4626 Ermal Lu?i
915 fe2031ab Ermal
	/* Setup CA environment if needed. */
916
	ldap_setup_caenv($authcfg);
917
918 1e0b1727 Phil Davis
	/* connect and see if server is up */
919
	$error = false;
920
	if (!($ldap = ldap_connect($ldapserver))) {
921 9f27de6d jim-p
		$error = true;
922 1e0b1727 Phil Davis
	}
923 c61e4626 Ermal Lu?i
924 1e0b1727 Phil Davis
	if ($error == true) {
925
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
926
		return false;
927
	}
928 55eb9c44 --global
929
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
930 3d3081ec Andrew MacIsaac
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
931 c61e4626 Ermal Lu?i
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
932 d6b4dfe3 jim-p
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
933
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
934 1180e4f0 Sjon Hortensius
935 836c858f derelict-pf
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
936
		if (!(ldap_start_tls($ldap))) {
937
			log_error(sprintf(gettext("ERROR! ldap_test_bind() could not STARTTLS to server %s."), $ldapname));
938
			@ldap_close($ldap);
939
			return false;
940
		}
941
	}
942
943 a5cd1c5a jim-p
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
944
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
945 c61e4626 Ermal Lu?i
	if ($ldapanon == true) {
946 6306b5dd Ermal Lu?i
		if (!($res = @ldap_bind($ldap))) {
947
			@ldap_close($ldap);
948 c61e4626 Ermal Lu?i
			return false;
949 6306b5dd Ermal Lu?i
		}
950
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
951
		@ldap_close($ldap);
952 55eb9c44 --global
		return false;
953 6306b5dd Ermal Lu?i
	}
954 55eb9c44 --global
955 6306b5dd Ermal Lu?i
	@ldap_unbind($ldap);
956 c61e4626 Ermal Lu?i
957 55eb9c44 --global
	return true;
958
}
959
960 6306b5dd Ermal Lu?i
function ldap_get_user_ous($show_complete_ou=true, $authcfg) {
961 55eb9c44 --global
	global $debug, $config, $g;
962
963 1e0b1727 Phil Davis
	if (!function_exists("ldap_connect")) {
964 55eb9c44 --global
		return;
965 1e0b1727 Phil Davis
	}
966 55eb9c44 --global
967 7a938f1b Ermal
	$ous = array();
968
969 c61e4626 Ermal Lu?i
	if ($authcfg) {
970 836c858f derelict-pf
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
971 1e0b1727 Phil Davis
			$ldapproto = "ldaps";
972 836c858f derelict-pf
		} else {
973
			$ldapproto = "ldap";
974 1e0b1727 Phil Davis
		}
975
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
976
		$ldapport = $authcfg['ldap_port'];
977
		if (!empty($ldapport)) {
978 9f27de6d jim-p
			$ldapserver .= ":{$ldapport}";
979 1e0b1727 Phil Davis
		}
980
		$ldapbasedn = $authcfg['ldap_basedn'];
981
		$ldapbindun = $authcfg['ldap_binddn'];
982
		$ldapbindpw = $authcfg['ldap_bindpw'];
983
		$ldapver = $authcfg['ldap_protver'];
984
		if (empty($ldapbindun) || empty($ldapbindpw)) {
985
			$ldapanon = true;
986
		} else {
987
			$ldapanon = false;
988
		}
989
		$ldapname = $authcfg['name'];
990
		$ldapfallback = false;
991
		$ldapscope = $authcfg['ldap_scope'];
992 45859aae Chris Buechler
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
993 1e0b1727 Phil Davis
	} else {
994 6306b5dd Ermal Lu?i
		return false;
995 1e0b1727 Phil Davis
	}
996 55eb9c44 --global
997 1e0b1727 Phil Davis
	/* first check if there is even an LDAP server populated */
998
	if (!$ldapserver) {
999
		log_error(gettext("ERROR!  ldap_get_user_ous() backed selected with no LDAP authentication server defined."));
1000
		return $ous;
1001
	}
1002 c61e4626 Ermal Lu?i
1003 fe2031ab Ermal
	/* Setup CA environment if needed. */
1004
	ldap_setup_caenv($authcfg);
1005
1006 c61e4626 Ermal Lu?i
	/* connect and see if server is up */
1007 1e0b1727 Phil Davis
	$error = false;
1008
	if (!($ldap = ldap_connect($ldapserver))) {
1009 9f27de6d jim-p
		$error = true;
1010 1e0b1727 Phil Davis
	}
1011 c61e4626 Ermal Lu?i
1012 1e0b1727 Phil Davis
	if ($error == true) {
1013
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1014
		return $ous;
1015
	}
1016 c61e4626 Ermal Lu?i
1017
	$ldapfilter = "(|(ou=*)(cn=Users))";
1018 55eb9c44 --global
1019
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1020 3d3081ec Andrew MacIsaac
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1021 c61e4626 Ermal Lu?i
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1022 d6b4dfe3 jim-p
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1023
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1024 55eb9c44 --global
1025 836c858f derelict-pf
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1026
		if (!(ldap_start_tls($ldap))) {
1027
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not STARTTLS to server %s."), $ldapname));
1028
			@ldap_close($ldap);
1029
			return false;
1030
		}
1031
	}
1032
1033 a5cd1c5a jim-p
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1034
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1035 c61e4626 Ermal Lu?i
	if ($ldapanon == true) {
1036 1e0b1727 Phil Davis
		if (!($res = @ldap_bind($ldap))) {
1037 94021404 Carlos Eduardo Ramos
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind anonymously to server %s."), $ldapname));
1038 6306b5dd Ermal Lu?i
			@ldap_close($ldap);
1039 1e0b1727 Phil Davis
			return $ous;
1040 c61e4626 Ermal Lu?i
		}
1041
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1042 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind to server %s."), $ldapname));
1043 6306b5dd Ermal Lu?i
		@ldap_close($ldap);
1044 c61e4626 Ermal Lu?i
		return $ous;
1045 55eb9c44 --global
	}
1046
1047 1e0b1727 Phil Davis
	if ($ldapscope == "one") {
1048 c61e4626 Ermal Lu?i
		$ldapfunc = "ldap_list";
1049 1e0b1727 Phil Davis
	} else {
1050 c61e4626 Ermal Lu?i
		$ldapfunc = "ldap_search";
1051 1e0b1727 Phil Davis
	}
1052 55eb9c44 --global
1053 7a938f1b Ermal
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
1054
	$info = @ldap_get_entries($ldap, $search);
1055 55eb9c44 --global
1056
	if (is_array($info)) {
1057
		foreach ($info as $inf) {
1058
			if (!$show_complete_ou) {
1059 cfbfd941 smos
				$inf_split = explode(",", $inf['dn']);
1060 55eb9c44 --global
				$ou = $inf_split[0];
1061 4de8f7ba Phil Davis
				$ou = str_replace("OU=", "", $ou);
1062
				$ou = str_replace("CN=", "", $ou);
1063 1e0b1727 Phil Davis
			} else {
1064
				if ($inf['dn']) {
1065 55eb9c44 --global
					$ou = $inf['dn'];
1066 1e0b1727 Phil Davis
				}
1067
			}
1068
			if ($ou) {
1069 55eb9c44 --global
				$ous[] = $ou;
1070 1e0b1727 Phil Davis
			}
1071 55eb9c44 --global
		}
1072
	}
1073
1074 6306b5dd Ermal Lu?i
	@ldap_unbind($ldap);
1075
1076 55eb9c44 --global
	return $ous;
1077
}
1078
1079 6306b5dd Ermal Lu?i
function ldap_get_groups($username, $authcfg) {
1080 55eb9c44 --global
	global $debug, $config;
1081 1180e4f0 Sjon Hortensius
1082 1e0b1727 Phil Davis
	if (!function_exists("ldap_connect")) {
1083 55eb9c44 --global
		return;
1084 1e0b1727 Phil Davis
	}
1085 1180e4f0 Sjon Hortensius
1086 1e0b1727 Phil Davis
	if (!$username) {
1087 55eb9c44 --global
		return false;
1088 1e0b1727 Phil Davis
	}
1089 55eb9c44 --global
1090 1e0b1727 Phil Davis
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1091 2ce660ad smos
		$username_split = explode("@", $username);
1092 1180e4f0 Sjon Hortensius
		$username = $username_split[0];
1093 55eb9c44 --global
	}
1094
1095 1e0b1727 Phil Davis
	if (stristr($username, "\\")) {
1096 cfbfd941 smos
		$username_split = explode("\\", $username);
1097 1180e4f0 Sjon Hortensius
		$username = $username_split[0];
1098
	}
1099
1100 55eb9c44 --global
	//log_error("Getting LDAP groups for {$username}.");
1101 1e0b1727 Phil Davis
	if ($authcfg) {
1102 836c858f derelict-pf
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1103 1e0b1727 Phil Davis
			$ldapproto = "ldaps";
1104 836c858f derelict-pf
		} else {
1105
			$ldapproto = "ldap";
1106 1e0b1727 Phil Davis
		}
1107
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1108
		$ldapport = $authcfg['ldap_port'];
1109
		if (!empty($ldapport)) {
1110 9f27de6d jim-p
			$ldapserver .= ":{$ldapport}";
1111 1e0b1727 Phil Davis
		}
1112
		$ldapbasedn = $authcfg['ldap_basedn'];
1113
		$ldapbindun = $authcfg['ldap_binddn'];
1114
		$ldapbindpw = $authcfg['ldap_bindpw'];
1115
		$ldapauthcont = $authcfg['ldap_authcn'];
1116
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1117
		$ldapgroupattribute = strtolower($authcfg['ldap_attr_member']);
1118 149efbea jim-p
		if (isset($authcfg['ldap_rfc2307'])) {
1119
			$ldapfilter         = "(&(objectClass={$authcfg['ldap_attr_groupobj']})({$ldapgroupattribute}={$username}))";
1120
		} else {
1121
			$ldapfilter         = "({$ldapnameattribute}={$username})";
1122
		}
1123 1e0b1727 Phil Davis
		$ldaptype = "";
1124
		$ldapver = $authcfg['ldap_protver'];
1125
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1126
			$ldapanon = true;
1127
		} else {
1128
			$ldapanon = false;
1129
		}
1130
		$ldapname = $authcfg['name'];
1131
		$ldapfallback = false;
1132
		$ldapscope = $authcfg['ldap_scope'];
1133 45859aae Chris Buechler
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1134 1e0b1727 Phil Davis
	} else {
1135 6306b5dd Ermal Lu?i
		return false;
1136 1e0b1727 Phil Davis
	}
1137 c61e4626 Ermal Lu?i
1138 149efbea jim-p
	if (isset($authcfg['ldap_rfc2307'])) {
1139
		$ldapdn = $ldapbasedn;
1140
	} else {
1141
		$ldapdn = $_SESSION['ldapdn'];
1142
	}
1143 c61e4626 Ermal Lu?i
1144 55eb9c44 --global
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
1145
	$ldapgroupattribute = strtolower($ldapgroupattribute);
1146 c61e4626 Ermal Lu?i
	$memberof = array();
1147 55eb9c44 --global
1148 1e0b1727 Phil Davis
	/* Setup CA environment if needed. */
1149
	ldap_setup_caenv($authcfg);
1150 fe2031ab Ermal
1151 55eb9c44 --global
	/* connect and see if server is up */
1152 c61e4626 Ermal Lu?i
	$error = false;
1153 1e0b1727 Phil Davis
	if (!($ldap = ldap_connect($ldapserver))) {
1154 9f27de6d jim-p
		$error = true;
1155 1e0b1727 Phil Davis
	}
1156 c61e4626 Ermal Lu?i
1157
	if ($error == true) {
1158 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("ERROR! ldap_get_groups() Could not connect to server %s."), $ldapname));
1159 fd6a81e1 Phil Davis
		return $memberof;
1160 1e0b1727 Phil Davis
	}
1161 1180e4f0 Sjon Hortensius
1162 55eb9c44 --global
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1163 3d3081ec Andrew MacIsaac
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1164 c61e4626 Ermal Lu?i
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1165 d6b4dfe3 jim-p
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1166
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1167 55eb9c44 --global
1168 836c858f derelict-pf
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1169
		if (!(ldap_start_tls($ldap))) {
1170
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not STARTTLS to server %s."), $ldapname));
1171
			@ldap_close($ldap);
1172
			return false;
1173
		}
1174
	}
1175
1176 55eb9c44 --global
	/* bind as user that has rights to read group attributes */
1177 a5cd1c5a jim-p
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1178
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1179 c61e4626 Ermal Lu?i
	if ($ldapanon == true) {
1180 1e0b1727 Phil Davis
		if (!($res = @ldap_bind($ldap))) {
1181 94021404 Carlos Eduardo Ramos
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind anonymously to server %s."), $ldapname));
1182 6306b5dd Ermal Lu?i
			@ldap_close($ldap);
1183 1e0b1727 Phil Davis
			return false;
1184 6306b5dd Ermal Lu?i
		}
1185 c61e4626 Ermal Lu?i
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1186 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind to server %s."), $ldapname));
1187 6306b5dd Ermal Lu?i
		@ldap_close($ldap);
1188 fd6a81e1 Phil Davis
		return $memberof;
1189 55eb9c44 --global
	}
1190
1191
	/* get groups from DN found */
1192
	/* use ldap_read instead of search so we don't have to do a bunch of extra work */
1193
	/* since we know the DN is in $_SESSION['ldapdn'] */
1194
	//$search    = ldap_read($ldap, $ldapdn, "(objectclass=*)", array($ldapgroupattribute));
1195 1e0b1727 Phil Davis
	if ($ldapscope == "one") {
1196
		$ldapfunc = "ldap_list";
1197
	} else {
1198
		$ldapfunc = "ldap_search";
1199
	}
1200 c61e4626 Ermal Lu?i
1201 1e0b1727 Phil Davis
	$search = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
1202
	$info = @ldap_get_entries($ldap, $search);
1203 55eb9c44 --global
1204 149efbea jim-p
	$gresults = isset($authcfg['ldap_rfc2307']) ? $info : $info[0][$ldapgroupattribute];
1205 1180e4f0 Sjon Hortensius
1206 4e322e2c Phil Davis
	if (is_array($gresults)) {
1207 55eb9c44 --global
		/* Iterate through the groups and throw them into an array */
1208 149efbea jim-p
		foreach ($gresults as $grp) {
1209 4e322e2c Phil Davis
			if (((isset($authcfg['ldap_rfc2307'])) && (stristr($grp["dn"], "CN=") !== false)) ||
1210
			    ((!isset($authcfg['ldap_rfc2307'])) && (stristr($grp, "CN=") !== false))) {
1211 149efbea jim-p
				$grpsplit = isset($authcfg['ldap_rfc2307']) ? explode(",", $grp["dn"]) : explode(",", $grp);
1212
				$memberof[] = preg_replace("/CN=/i", "", $grpsplit[0]);
1213 55eb9c44 --global
			}
1214
		}
1215
	}
1216 1180e4f0 Sjon Hortensius
1217 55eb9c44 --global
	/* Time to close LDAP connection */
1218 6306b5dd Ermal Lu?i
	@ldap_unbind($ldap);
1219 1180e4f0 Sjon Hortensius
1220 4de8f7ba Phil Davis
	$groups = print_r($memberof, true);
1221 1180e4f0 Sjon Hortensius
1222 55eb9c44 --global
	//log_error("Returning groups ".$groups." for user $username");
1223 1180e4f0 Sjon Hortensius
1224 55eb9c44 --global
	return $memberof;
1225
}
1226
1227 83e0d4c8 jim-p
function ldap_format_host($host) {
1228
	return is_ipaddrv6($host) ? "[$host]" : $host ;
1229
}
1230
1231 6306b5dd Ermal Lu?i
function ldap_backed($username, $passwd, $authcfg) {
1232 55eb9c44 --global
	global $debug, $config;
1233 1180e4f0 Sjon Hortensius
1234 1e0b1727 Phil Davis
	if (!$username) {
1235 55eb9c44 --global
		return;
1236 1e0b1727 Phil Davis
	}
1237 55eb9c44 --global
1238 1e0b1727 Phil Davis
	if (!function_exists("ldap_connect")) {
1239 55eb9c44 --global
		return;
1240 1e0b1727 Phil Davis
	}
1241 55eb9c44 --global
1242 1e0b1727 Phil Davis
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1243 2ce660ad smos
		$username_split = explode("@", $username);
1244 1180e4f0 Sjon Hortensius
		$username = $username_split[0];
1245 55eb9c44 --global
	}
1246 1e0b1727 Phil Davis
	if (stristr($username, "\\")) {
1247 cfbfd941 smos
		$username_split = explode("\\", $username);
1248 1180e4f0 Sjon Hortensius
		$username = $username_split[0];
1249 55eb9c44 --global
	}
1250
1251 c61e4626 Ermal Lu?i
	if ($authcfg) {
1252 836c858f derelict-pf
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1253 c61e4626 Ermal Lu?i
			$ldapproto = "ldaps";
1254 836c858f derelict-pf
		} else {
1255
			$ldapproto = "ldap";
1256 1e0b1727 Phil Davis
		}
1257
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1258
		$ldapport = $authcfg['ldap_port'];
1259
		if (!empty($ldapport)) {
1260 9f27de6d jim-p
			$ldapserver .= ":{$ldapport}";
1261 1e0b1727 Phil Davis
		}
1262
		$ldapbasedn = $authcfg['ldap_basedn'];
1263
		$ldapbindun = $authcfg['ldap_binddn'];
1264
		$ldapbindpw = $authcfg['ldap_bindpw'];
1265
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1266 c61e4626 Ermal Lu?i
			$ldapanon = true;
1267 1e0b1727 Phil Davis
		} else {
1268 c61e4626 Ermal Lu?i
			$ldapanon = false;
1269 1e0b1727 Phil Davis
		}
1270
		$ldapauthcont = $authcfg['ldap_authcn'];
1271
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1272
		$ldapextendedqueryenabled = $authcfg['ldap_extended_enabled'];
1273
		$ldapextendedquery = $authcfg['ldap_extended_query'];
1274
		$ldapfilter = "";
1275
		if (!$ldapextendedqueryenabled) {
1276
			$ldapfilter = "({$ldapnameattribute}={$username})";
1277
		} else {
1278
			$ldapfilter = "(&({$ldapnameattribute}={$username})({$ldapextendedquery}))";
1279
		}
1280
		$ldaptype = "";
1281
		$ldapver = $authcfg['ldap_protver'];
1282
		$ldapname = $authcfg['name'];
1283
		$ldapscope = $authcfg['ldap_scope'];
1284 45859aae Chris Buechler
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1285 1e0b1727 Phil Davis
	} else {
1286 6306b5dd Ermal Lu?i
		return false;
1287 1e0b1727 Phil Davis
	}
1288 55eb9c44 --global
1289 1180e4f0 Sjon Hortensius
	/* first check if there is even an LDAP server populated */
1290 1e0b1727 Phil Davis
	if (!$ldapserver) {
1291 c61e4626 Ermal Lu?i
		if ($ldapfallback) {
1292 94021404 Carlos Eduardo Ramos
			log_error(gettext("ERROR! ldap_backed() called with no LDAP authentication server defined.  Defaulting to local user database. Visit System -> User Manager."));
1293 c61e4626 Ermal Lu?i
			return local_backed($username, $passwd);
1294 1e0b1727 Phil Davis
		} else {
1295 94021404 Carlos Eduardo Ramos
			log_error(gettext("ERROR! ldap_backed() called with no LDAP authentication server defined."));
1296 1e0b1727 Phil Davis
		}
1297 c61e4626 Ermal Lu?i
1298
		return false;
1299 55eb9c44 --global
	}
1300 1180e4f0 Sjon Hortensius
1301 1e0b1727 Phil Davis
	/* Setup CA environment if needed. */
1302
	ldap_setup_caenv($authcfg);
1303 fe2031ab Ermal
1304 836c858f derelict-pf
	/* Make sure we can connect to LDAP */
1305
	$error = false;
1306
	if (!($ldap = ldap_connect($ldapserver))) {
1307
		$error = true;
1308
	}
1309
1310 906daddc Ermal
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1311 3d3081ec Andrew MacIsaac
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1312 906daddc Ermal
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1313 d6b4dfe3 jim-p
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1314
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1315 906daddc Ermal
1316 836c858f derelict-pf
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1317
		if (!(ldap_start_tls($ldap))) {
1318
			log_error(sprintf(gettext("ERROR! ldap_backed() could not STARTTLS to server %s."), $ldapname));
1319
			@ldap_close($ldap);
1320
			return false;
1321
		}
1322 1e0b1727 Phil Davis
	}
1323 c61e4626 Ermal Lu?i
1324
	if ($error == true) {
1325 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1326 c61e4626 Ermal Lu?i
		return false;
1327 55eb9c44 --global
	}
1328 c61e4626 Ermal Lu?i
1329 55eb9c44 --global
	/* ok, its up.  now, lets bind as the bind user so we can search it */
1330 c61e4626 Ermal Lu?i
	$error = false;
1331 a5cd1c5a jim-p
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1332
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1333 c61e4626 Ermal Lu?i
	if ($ldapanon == true) {
1334 1e0b1727 Phil Davis
		if (!($res = @ldap_bind($ldap))) {
1335
			$error = true;
1336
		}
1337
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1338 c61e4626 Ermal Lu?i
		$error = true;
1339 1e0b1727 Phil Davis
	}
1340 c61e4626 Ermal Lu?i
1341
	if ($error == true) {
1342 6306b5dd Ermal Lu?i
		@ldap_close($ldap);
1343 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("ERROR! Could not bind to server %s."), $ldapname));
1344 c61e4626 Ermal Lu?i
		return false;
1345 55eb9c44 --global
	}
1346 1180e4f0 Sjon Hortensius
1347 55eb9c44 --global
	/* Get LDAP Authcontainers and split em up. */
1348 cfbfd941 smos
	$ldac_splits = explode(";", $ldapauthcont);
1349 1180e4f0 Sjon Hortensius
1350 086cf944 Phil Davis
	/* setup the usercount so we think we haven't found anyone yet */
1351 4de8f7ba Phil Davis
	$usercount = 0;
1352 55eb9c44 --global
1353
	/*****************************************************************/
1354 6990ad35 Phil Davis
	/*  We first find the user based on username and filter          */
1355
	/*  then, once we find the first occurrence of that person       */
1356
	/*  we set session variables to point to the OU and DN of the    */
1357
	/*  person.  To later be used by ldap_get_groups.                */
1358 55eb9c44 --global
	/*  that way we don't have to search twice.                      */
1359
	/*****************************************************************/
1360 1e0b1727 Phil Davis
	if ($debug) {
1361 3ac8324f Ermal
		log_auth(sprintf(gettext("Now Searching for %s in directory."), $username));
1362 1e0b1727 Phil Davis
	}
1363 c61e4626 Ermal Lu?i
	/* Iterate through the user containers for search */
1364
	foreach ($ldac_splits as $i => $ldac_split) {
1365 a5cd1c5a jim-p
		$ldac_split = isset($authcfg['ldap_utf8']) ? utf8_encode($ldac_split) : $ldac_split;
1366
		$ldapfilter = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapfilter) : $ldapfilter;
1367
		$ldapsearchbasedn = isset($authcfg['ldap_utf8']) ? utf8_encode("{$ldac_split},{$ldapbasedn}") : "{$ldac_split},{$ldapbasedn}";
1368 c61e4626 Ermal Lu?i
		/* Make sure we just use the first user we find */
1369 1e0b1727 Phil Davis
		if ($debug) {
1370 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)));
1371 1e0b1727 Phil Davis
		}
1372
		if ($ldapscope == "one") {
1373 c61e4626 Ermal Lu?i
			$ldapfunc = "ldap_list";
1374 1e0b1727 Phil Davis
		} else {
1375 c61e4626 Ermal Lu?i
			$ldapfunc = "ldap_search";
1376 1e0b1727 Phil Davis
		}
1377 c61e4626 Ermal Lu?i
		/* Support legacy auth container specification. */
1378 1e0b1727 Phil Davis
		if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) {
1379 6990ad35 Phil Davis
			$search = @$ldapfunc($ldap, $ldac_split, $ldapfilter);
1380 1e0b1727 Phil Davis
		} else {
1381 6990ad35 Phil Davis
			$search = @$ldapfunc($ldap, $ldapsearchbasedn, $ldapfilter);
1382 1e0b1727 Phil Davis
		}
1383 c61e4626 Ermal Lu?i
		if (!$search) {
1384 94021404 Carlos Eduardo Ramos
			log_error(sprintf(gettext("Search resulted in error: %s"), ldap_error($ldap)));
1385 c61e4626 Ermal Lu?i
			continue;
1386 55eb9c44 --global
		}
1387 4de8f7ba Phil Davis
		$info = ldap_get_entries($ldap, $search);
1388 c61e4626 Ermal Lu?i
		$matches = $info['count'];
1389 1e0b1727 Phil Davis
		if ($matches == 1) {
1390 c61e4626 Ermal Lu?i
			$userdn = $_SESSION['ldapdn'] = $info[0]['dn'];
1391
			$_SESSION['ldapou'] = $ldac_split[$i];
1392
			$_SESSION['ldapon'] = "true";
1393
			$usercount = 1;
1394
			break;
1395 55eb9c44 --global
		}
1396
	}
1397
1398 1e0b1727 Phil Davis
	if ($usercount != 1) {
1399 6306b5dd Ermal Lu?i
		@ldap_unbind($ldap);
1400 94021404 Carlos Eduardo Ramos
		log_error(gettext("ERROR! Either LDAP search failed, or multiple users were found."));
1401 1180e4f0 Sjon Hortensius
		return false;
1402 55eb9c44 --global
	}
1403 c61e4626 Ermal Lu?i
1404 55eb9c44 --global
	/* Now lets bind as the user we found */
1405 a5cd1c5a jim-p
	$passwd = isset($authcfg['ldap_utf8']) ? utf8_encode($passwd) : $passwd;
1406 c61e4626 Ermal Lu?i
	if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
1407 3697adb2 jim-p
		log_error(sprintf(gettext('ERROR! Could not login to server %1$s as user %2$s: %3$s'), $ldapname, $username, ldap_error($ldap)));
1408 6306b5dd Ermal Lu?i
		@ldap_unbind($ldap);
1409 c61e4626 Ermal Lu?i
		return false;
1410 55eb9c44 --global
	}
1411
1412 a5cd1c5a jim-p
	if ($debug) {
1413
		$userdn = isset($authcfg['ldap_utf8']) ? utf8_decode($userdn) : $userdn;
1414 2004def5 Ermal
		log_auth(sprintf(gettext('Logged in successfully as %1$s via LDAP server %2$s with DN = %3$s.'), $username, $ldapname, $userdn));
1415 a5cd1c5a jim-p
	}
1416 c61e4626 Ermal Lu?i
1417
	/* At this point we are bound to LDAP so the user was auth'd okay. Close connection. */
1418 6306b5dd Ermal Lu?i
	@ldap_unbind($ldap);
1419 55eb9c44 --global
1420
	return true;
1421
}
1422
1423 1492e02c Ermal
function radius_backed($username, $passwd, $authcfg, &$attributes = array()) {
1424 a13ce628 Ermal Lu?i
	global $debug, $config;
1425 55eb9c44 --global
	$ret = false;
1426
1427 868c6826 Ermal
	require_once("radius.inc");
1428
1429 55eb9c44 --global
	$rauth = new Auth_RADIUS_PAP($username, $passwd);
1430 c61e4626 Ermal Lu?i
	if ($authcfg) {
1431
		$radiusservers = array();
1432
		$radiusservers[0]['ipaddr'] = $authcfg['host'];
1433
		$radiusservers[0]['port'] = $authcfg['radius_auth_port'];
1434
		$radiusservers[0]['sharedsecret'] = $authcfg['radius_secret'];
1435 bddd2be8 jim-p
		$radiusservers[0]['timeout'] = $authcfg['radius_timeout'];
1436 1e0b1727 Phil Davis
	} else {
1437 6306b5dd Ermal Lu?i
		return false;
1438 1e0b1727 Phil Davis
	}
1439 c61e4626 Ermal Lu?i
1440 1e0b1727 Phil Davis
	/* Add new servers to our instance */
1441 bddd2be8 jim-p
	foreach ($radiusservers as $radsrv) {
1442
		$timeout = (is_numeric($radsrv['timeout'])) ? $radsrv['timeout'] : 5;
1443
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret'], $timeout);
1444
	}
1445 55eb9c44 --global
1446 6e815096 Ermal
	if (PEAR::isError($rauth->start())) {
1447 55eb9c44 --global
		$retvalue['auth_val'] = 1;
1448
		$retvalue['error'] = $rauth->getError();
1449 1e0b1727 Phil Davis
		if ($debug) {
1450 7aaf60a8 k-paulius
			printf(gettext("RADIUS start: %s<br />\n"), $retvalue['error']);
1451 1e0b1727 Phil Davis
		}
1452 55eb9c44 --global
	}
1453
1454
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1455
1456
	/* Send request */
1457
	$result = $rauth->send();
1458
	if (PEAR::isError($result)) {
1459
		$retvalue['auth_val'] = 1;
1460
		$retvalue['error'] = $result->getMessage();
1461 1e0b1727 Phil Davis
		if ($debug) {
1462 7aaf60a8 k-paulius
			printf(gettext("RADIUS send failed: %s<br />\n"), $retvalue['error']);
1463 1e0b1727 Phil Davis
		}
1464 55eb9c44 --global
	} else if ($result === true) {
1465 1e0b1727 Phil Davis
		if ($rauth->getAttributes()) {
1466 1492e02c Ermal
			$attributes = $rauth->listAttributes();
1467 1e0b1727 Phil Davis
		}
1468 55eb9c44 --global
		$retvalue['auth_val'] = 2;
1469 1e0b1727 Phil Davis
		if ($debug) {
1470 7aaf60a8 k-paulius
			printf(gettext("RADIUS Auth succeeded")."<br />\n");
1471 1e0b1727 Phil Davis
		}
1472 55eb9c44 --global
		$ret = true;
1473
	} else {
1474
		$retvalue['auth_val'] = 3;
1475 1e0b1727 Phil Davis
		if ($debug) {
1476 7aaf60a8 k-paulius
			printf(gettext("RADIUS Auth rejected")."<br />\n");
1477 1e0b1727 Phil Davis
		}
1478 55eb9c44 --global
	}
1479
1480
	// close OO RADIUS_AUTHENTICATION
1481
	$rauth->close();
1482
1483
	return $ret;
1484
}
1485
1486 c4a9f99a jim-p
/*
1487
	$attributes must contain a "class" key containing the groups and local
1488
	groups must exist to match.
1489
*/
1490
function radius_get_groups($attributes) {
1491
	$groups = array();
1492 1dd07051 jim-p
	if (!empty($attributes) && is_array($attributes) && (!empty($attributes['class']) || !empty($attributes['class_int']))) {
1493
		/* Some RADIUS servers return multiple class attributes, so check them all. */
1494
		$groups = array();
1495
		if (!empty($attributes['class']) && is_array($attributes['class'])) {
1496
			foreach ($attributes['class'] as $class) {
1497
				$groups = array_unique(array_merge($groups, explode(";", $class)));
1498
			}
1499
		}
1500
1501 c4a9f99a jim-p
		foreach ($groups as & $grp) {
1502 916fc1f8 jim-p
			$grp = trim($grp);
1503
			if (strtolower(substr($grp, 0, 3)) == "ou=") {
1504 c4a9f99a jim-p
				$grp = substr($grp, 3);
1505
			}
1506
		}
1507
	}
1508
	return $groups;
1509
}
1510
1511 7dd044f2 sullrich
function get_user_expiration_date($username) {
1512 a13ce628 Ermal Lu?i
	$user = getUserEntry($username);
1513 1e0b1727 Phil Davis
	if ($user['expires']) {
1514 a13ce628 Ermal Lu?i
		return $user['expires'];
1515 1e0b1727 Phil Davis
	}
1516 a13ce628 Ermal Lu?i
}
1517
1518
function is_account_expired($username) {
1519
	$expirydate = get_user_expiration_date($username);
1520
	if ($expirydate) {
1521 4de8f7ba Phil Davis
		if (strtotime("-1 day") > strtotime(date("m/d/Y", strtotime($expirydate)))) {
1522 a13ce628 Ermal Lu?i
			return true;
1523 1e0b1727 Phil Davis
		}
1524 7dd044f2 sullrich
	}
1525 a13ce628 Ermal Lu?i
1526
	return false;
1527 7dd044f2 sullrich
}
1528
1529 b4bfd25d sullrich
function is_account_disabled($username) {
1530 a13ce628 Ermal Lu?i
	$user = getUserEntry($username);
1531 1e0b1727 Phil Davis
	if (isset($user['disabled'])) {
1532 a13ce628 Ermal Lu?i
		return true;
1533 1e0b1727 Phil Davis
	}
1534 a13ce628 Ermal Lu?i
1535 b4bfd25d sullrich
	return false;
1536
}
1537
1538 595b074d Phil Davis
function get_user_settings($username) {
1539
	global $config;
1540
	$settings = array();
1541
	$settings['widgets'] = $config['widgets'];
1542
	$settings['webgui']['dashboardcolumns'] = $config['system']['webgui']['dashboardcolumns'];
1543
	$settings['webgui']['webguihostnamemenu'] = $config['system']['webgui']['webguihostnamemenu'];
1544
	$settings['webgui']['webguicss'] = $config['system']['webgui']['webguicss'];
1545 3666d731 Phil Davis
	$settings['webgui']['interfacessort'] = isset($config['system']['webgui']['interfacessort']);
1546 595b074d Phil Davis
	$settings['webgui']['dashboardavailablewidgetspanel'] = isset($config['system']['webgui']['dashboardavailablewidgetspanel']);
1547
	$settings['webgui']['webguifixedmenu'] = isset($config['system']['webgui']['webguifixedmenu']);
1548
	$settings['webgui']['webguileftcolumnhyper'] = isset($config['system']['webgui']['webguileftcolumnhyper']);
1549
	$settings['webgui']['systemlogsfilterpanel'] = isset($config['system']['webgui']['systemlogsfilterpanel']);
1550
	$settings['webgui']['systemlogsmanagelogpanel'] = isset($config['system']['webgui']['systemlogsmanagelogpanel']);
1551
	$settings['webgui']['statusmonitoringsettingspanel'] = isset($config['system']['webgui']['statusmonitoringsettingspanel']);
1552
	$settings['webgui']['pagenamefirst'] = isset($config['system']['webgui']['pagenamefirst']);
1553
	$user = getUserEntry($username);
1554
	if (isset($user['customsettings'])) {
1555
		$settings['customsettings'] = true;
1556
		if (isset($user['widgets'])) {
1557
			// This includes the 'sequence', and any widgetname-config per-widget settings.
1558
			$settings['widgets'] = $user['widgets'];
1559
		}
1560
		if (isset($user['dashboardcolumns'])) {
1561
			$settings['webgui']['dashboardcolumns'] = $user['dashboardcolumns'];
1562
		}
1563
		if (isset($user['webguicss'])) {
1564
			$settings['webgui']['webguicss'] = $user['webguicss'];
1565
		}
1566
		if (isset($user['webguihostnamemenu'])) {
1567
			$settings['webgui']['webguihostnamemenu'] = $user['webguihostnamemenu'];
1568
		}
1569 3666d731 Phil Davis
		$settings['webgui']['interfacessort'] = isset($user['interfacessort']);
1570 595b074d Phil Davis
		$settings['webgui']['dashboardavailablewidgetspanel'] = isset($user['dashboardavailablewidgetspanel']);
1571
		$settings['webgui']['webguifixedmenu'] = isset($user['webguifixedmenu']);
1572
		$settings['webgui']['webguileftcolumnhyper'] = isset($user['webguileftcolumnhyper']);
1573
		$settings['webgui']['systemlogsfilterpanel'] = isset($user['systemlogsfilterpanel']);
1574
		$settings['webgui']['systemlogsmanagelogpanel'] = isset($user['systemlogsmanagelogpanel']);
1575
		$settings['webgui']['statusmonitoringsettingspanel'] = isset($user['statusmonitoringsettingspanel']);
1576
		$settings['webgui']['pagenamefirst'] = isset($user['pagenamefirst']);
1577
	} else {
1578
		$settings['customsettings'] = false;
1579
	}
1580
1581
	if ($settings['webgui']['dashboardcolumns'] < 1) {
1582
		$settings['webgui']['dashboardcolumns'] = 2;
1583
	}
1584
1585
	return $settings;
1586
}
1587
1588 be59d667 Phil Davis
function save_widget_settings($username, $settings, $message = "") {
1589 595b074d Phil Davis
	global $config, $userindex;
1590
	$user = getUserEntry($username);
1591 be59d667 Phil Davis
1592
	if (strlen($message) > 0) {
1593
		$msgout = $message;
1594
	} else {
1595
		$msgout = gettext("Widget configuration has been changed.");
1596
	}
1597
1598 595b074d Phil Davis
	if (isset($user['customsettings'])) {
1599
		$config['system']['user'][$userindex[$username]]['widgets'] = $settings;
1600 be59d667 Phil Davis
		write_config($msgout . " " . sprintf(gettext("(User %s)"), $username));
1601 595b074d Phil Davis
	} else {
1602
		$config['widgets'] = $settings;
1603 be59d667 Phil Davis
		write_config($msgout);
1604 595b074d Phil Davis
	}
1605
}
1606
1607 c61e4626 Ermal Lu?i
function auth_get_authserver($name) {
1608 1e0b1727 Phil Davis
	global $config;
1609
1610
	if (is_array($config['system']['authserver'])) {
1611
		foreach ($config['system']['authserver'] as $authcfg) {
1612
			if ($authcfg['name'] == $name) {
1613
				return $authcfg;
1614
			}
1615
		}
1616
	}
1617
	if ($name == "Local Database") {
1618 96568521 Vinicius Coque
		return array("name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']);
1619 1e0b1727 Phil Davis
	}
1620 6306b5dd Ermal Lu?i
}
1621
1622
function auth_get_authserver_list() {
1623 1e0b1727 Phil Davis
	global $config;
1624 6306b5dd Ermal Lu?i
1625
	$list = array();
1626
1627 1e0b1727 Phil Davis
	if (is_array($config['system']['authserver'])) {
1628
		foreach ($config['system']['authserver'] as $authcfg) {
1629 6306b5dd Ermal Lu?i
			/* Add support for disabled entries? */
1630
			$list[$authcfg['name']] = $authcfg;
1631 1e0b1727 Phil Davis
		}
1632
	}
1633 6306b5dd Ermal Lu?i
1634 4de8f7ba Phil Davis
	$list["Local Database"] = array("name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']);
1635 6306b5dd Ermal Lu?i
	return $list;
1636 c61e4626 Ermal Lu?i
}
1637
1638 c4a9f99a jim-p
function getUserGroups($username, $authcfg, &$attributes = array()) {
1639 fb0f22c0 Ermal Lu?i
	global $config;
1640
1641
	$allowed_groups = array();
1642
1643 1e0b1727 Phil Davis
	switch ($authcfg['type']) {
1644
		case 'ldap':
1645
			$allowed_groups = @ldap_get_groups($username, $authcfg);
1646
			break;
1647
		case 'radius':
1648 c4a9f99a jim-p
			$allowed_groups = @radius_get_groups($attributes);
1649 1e0b1727 Phil Davis
			break;
1650
		default:
1651
			$user = getUserEntry($username);
1652
			$allowed_groups = @local_user_get_groups($user, true);
1653
			break;
1654 fb0f22c0 Ermal Lu?i
	}
1655
1656
	$member_groups = array();
1657 1e0b1727 Phil Davis
	if (is_array($config['system']['group'])) {
1658
		foreach ($config['system']['group'] as $group) {
1659
			if (in_array($group['name'], $allowed_groups)) {
1660 fb0f22c0 Ermal Lu?i
				$member_groups[] = $group['name'];
1661 1e0b1727 Phil Davis
			}
1662
		}
1663 fb0f22c0 Ermal Lu?i
	}
1664
1665
	return $member_groups;
1666
}
1667
1668 1492e02c Ermal
function authenticate_user($username, $password, $authcfg = NULL, &$attributes = array()) {
1669 c61e4626 Ermal Lu?i
1670 b7369ff8 NewEraCracker
	if (is_array($username) || is_array($password)) {
1671
		return false;
1672
	}
1673
1674 c61e4626 Ermal Lu?i
	if (!$authcfg) {
1675
		return local_backed($username, $password);
1676
	}
1677
1678
	$authenticated = false;
1679 1e0b1727 Phil Davis
	switch ($authcfg['type']) {
1680
		case 'ldap':
1681
			if (ldap_backed($username, $password, $authcfg)) {
1682
				$authenticated = true;
1683
			}
1684
			break;
1685
		case 'radius':
1686
			if (radius_backed($username, $password, $authcfg, $attributes)) {
1687
				$authenticated = true;
1688
			}
1689
			break;
1690
		default:
1691
			/* lookup user object by name */
1692
			if (local_backed($username, $password)) {
1693
				$authenticated = true;
1694
			}
1695
			break;
1696
		}
1697 c61e4626 Ermal Lu?i
1698
	return $authenticated;
1699
}
1700
1701 6306b5dd Ermal Lu?i
function session_auth() {
1702 aa205c3b Ermal
	global $config, $_SESSION, $page;
1703 55eb9c44 --global
1704 49ddf9a1 Warren Baker
	// Handle HTTPS httponly and secure flags
1705 16789caa Renato Botelho
	$currentCookieParams = session_get_cookie_params();
1706
	session_set_cookie_params(
1707
		$currentCookieParams["lifetime"],
1708
		$currentCookieParams["path"],
1709
		NULL,
1710
		($config['system']['webgui']['protocol'] == "https"),
1711
		true
1712
	);
1713 49ddf9a1 Warren Baker
1714 1e0b1727 Phil Davis
	if (!session_id()) {
1715 9252d093 Ermal
		session_start();
1716 1e0b1727 Phil Davis
	}
1717 55eb9c44 --global
1718 dd030de9 Renato Botelho
	// Detect protocol change
1719 1e0b1727 Phil Davis
	if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) {
1720 dd030de9 Renato Botelho
		return false;
1721 1e0b1727 Phil Davis
	}
1722 dd030de9 Renato Botelho
1723 55eb9c44 --global
	/* Validate incoming login request */
1724 c4a9f99a jim-p
	$attributes = array();
1725 88165371 Ermal
	if (isset($_POST['login']) && !empty($_POST['usernamefld']) && !empty($_POST['passwordfld'])) {
1726 6306b5dd Ermal Lu?i
		$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
1727 6be782ed PiBa-NL
		$remoteauth = authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg, $attributes);
1728
		if ($remoteauth || authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) {
1729 526f5b11 Renato Botelho
			// Generate a new id to avoid session fixation
1730 8588095f Renato Botelho
			session_regenerate_id();
1731 6306b5dd Ermal Lu?i
			$_SESSION['Logged_In'] = "True";
1732 6be782ed PiBa-NL
			$_SESSION['remoteauth'] = $remoteauth;
1733 6306b5dd Ermal Lu?i
			$_SESSION['Username'] = $_POST['usernamefld'];
1734 c4a9f99a jim-p
			$_SESSION['user_radius_attributes'] = $attributes;
1735 6306b5dd Ermal Lu?i
			$_SESSION['last_access'] = time();
1736 dd030de9 Renato Botelho
			$_SESSION['protocol'] = $config['system']['webgui']['protocol'];
1737 1e0b1727 Phil Davis
			if (!isset($config['system']['webgui']['quietlogin'])) {
1738 54bdff75 Vinicius Coque
				log_auth(sprintf(gettext("Successful login for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], $_SERVER['REMOTE_ADDR']));
1739 4fc3855f smos
			}
1740 1e0b1727 Phil Davis
			if (isset($_POST['postafterlogin'])) {
1741 92140621 Ermal
				return true;
1742 1e0b1727 Phil Davis
			} else {
1743
				if (empty($page)) {
1744 80b292f3 Ermal
					$page = "/";
1745 1e0b1727 Phil Davis
				}
1746 80b292f3 Ermal
				header("Location: {$page}");
1747
			}
1748 f23e6363 Ermal
			exit;
1749 a13ce628 Ermal Lu?i
		} else {
1750
			/* give the user an error message */
1751
			$_SESSION['Login_Error'] = "Username or Password incorrect";
1752 65f7fba8 Scott Ullrich
			log_auth("webConfigurator authentication error for '{$_POST['usernamefld']}' from {$_SERVER['REMOTE_ADDR']}");
1753 1e0b1727 Phil Davis
			if (isAjax()) {
1754 a13ce628 Ermal Lu?i
				echo "showajaxmessage('{$_SESSION['Login_Error']}');";
1755
				return;
1756 55eb9c44 --global
			}
1757
		}
1758
	}
1759
1760
	/* Show login page if they aren't logged in */
1761 1e0b1727 Phil Davis
	if (empty($_SESSION['Logged_In'])) {
1762 55eb9c44 --global
		return false;
1763 1e0b1727 Phil Davis
	}
1764 55eb9c44 --global
1765
	/* If session timeout isn't set, we don't mark sessions stale */
1766 02647583 Ermal
	if (!isset($config['system']['webgui']['session_timeout'])) {
1767 bdadaf3c Chris Buechler
		/* Default to 4 hour timeout if one is not set */
1768
		if ($_SESSION['last_access'] < (time() - 14400)) {
1769
			$_GET['logout'] = true;
1770
			$_SESSION['Logout'] = true;
1771 1e0b1727 Phil Davis
		} else {
1772 1180e4f0 Sjon Hortensius
			$_SESSION['last_access'] = time();
1773 1e0b1727 Phil Davis
		}
1774 02647583 Ermal
	} else if (intval($config['system']['webgui']['session_timeout']) == 0) {
1775
		/* only update if it wasn't ajax */
1776 1e0b1727 Phil Davis
		if (!isAjax()) {
1777 02647583 Ermal
			$_SESSION['last_access'] = time();
1778 1e0b1727 Phil Davis
		}
1779 bdadaf3c Chris Buechler
	} else {
1780 55eb9c44 --global
		/* Check for stale session */
1781
		if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
1782
			$_GET['logout'] = true;
1783
			$_SESSION['Logout'] = true;
1784
		} else {
1785
			/* only update if it wasn't ajax */
1786 1e0b1727 Phil Davis
			if (!isAjax()) {
1787 55eb9c44 --global
				$_SESSION['last_access'] = time();
1788 1e0b1727 Phil Davis
			}
1789 55eb9c44 --global
		}
1790
	}
1791
1792
	/* user hit the logout button */
1793
	if (isset($_GET['logout'])) {
1794
1795 1e0b1727 Phil Davis
		if ($_SESSION['Logout']) {
1796 addc0439 Renato Botelho
			log_error(sprintf(gettext("Session timed out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR']));
1797 1e0b1727 Phil Davis
		} else {
1798 addc0439 Renato Botelho
			log_error(sprintf(gettext("User logged out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR']));
1799 1e0b1727 Phil Davis
		}
1800 55eb9c44 --global
1801
		/* wipe out $_SESSION */
1802
		$_SESSION = array();
1803
1804 1e0b1727 Phil Davis
		if (isset($_COOKIE[session_name()])) {
1805 55eb9c44 --global
			setcookie(session_name(), '', time()-42000, '/');
1806 1e0b1727 Phil Davis
		}
1807 55eb9c44 --global
1808
		/* and destroy it */
1809
		session_destroy();
1810
1811 cfbfd941 smos
		$scriptName = explode("/", $_SERVER["SCRIPT_FILENAME"]);
1812 55eb9c44 --global
		$scriptElms = count($scriptName);
1813
		$scriptName = $scriptName[$scriptElms-1];
1814
1815 1e0b1727 Phil Davis
		if (isAjax()) {
1816 55eb9c44 --global
			return false;
1817 1e0b1727 Phil Davis
		}
1818 55eb9c44 --global
1819
		/* redirect to page the user is on, it'll prompt them to login again */
1820 6f3d2063 Renato Botelho
		header("Location: {$scriptName}");
1821 55eb9c44 --global
1822
		return false;
1823
	}
1824
1825
	/*
1826
	 * this is for debugging purpose if you do not want to use Ajax
1827 1e0b1727 Phil Davis
	 * to submit a HTML form. It basically disables the observation
1828 55eb9c44 --global
	 * of the submit event and hence does not trigger Ajax.
1829
	 */
1830 1e0b1727 Phil Davis
	if ($_GET['disable_ajax']) {
1831 55eb9c44 --global
		$_SESSION['NO_AJAX'] = "True";
1832 1e0b1727 Phil Davis
	}
1833 55eb9c44 --global
1834
	/*
1835
	 * Same to re-enable Ajax.
1836
	 */
1837 1e0b1727 Phil Davis
	if ($_GET['enable_ajax']) {
1838 55eb9c44 --global
		unset($_SESSION['NO_AJAX']);
1839 1e0b1727 Phil Davis
	}
1840 55eb9c44 --global
1841
	return true;
1842
}
1843
1844 88165371 Ermal
?>