Project

General

Profile

Download (80.2 KB) Statistics
| Branch: | Tag: | Revision:
1 5b237745 Scott Ullrich
<?php
2
/*
3 8acd654a Renato Botelho
 * captiveportal.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2016 Electric Sheep Fencing, LLC
7
 * All rights reserved.
8
 *
9
 * originally part of m0n0wall (http://m0n0.ch/wall)
10 aaec5634 Renato Botelho
 * Copyright (c) 2003-2006 Manuel Kasper <mk@neon1.net>.
11 8acd654a Renato Botelho
 * All rights reserved.
12
 *
13
 * Redistribution and use in source and binary forms, with or without
14
 * modification, are permitted provided that the following conditions are met:
15
 *
16
 * 1. Redistributions of source code must retain the above copyright notice,
17
 *    this list of conditions and the following disclaimer.
18
 *
19
 * 2. Redistributions in binary form must reproduce the above copyright
20
 *    notice, this list of conditions and the following disclaimer in
21
 *    the documentation and/or other materials provided with the
22
 *    distribution.
23
 *
24
 * 3. All advertising materials mentioning features or use of this software
25
 *    must display the following acknowledgment:
26
 *    "This product includes software developed by the pfSense Project
27
 *    for use in the pfSense® software distribution. (http://www.pfsense.org/).
28
 *
29
 * 4. The names "pfSense" and "pfSense Project" must not be used to
30
 *    endorse or promote products derived from this software without
31
 *    prior written permission. For written permission, please contact
32
 *    coreteam@pfsense.org.
33
 *
34
 * 5. Products derived from this software may not be called "pfSense"
35
 *    nor may "pfSense" appear in their names without prior written
36
 *    permission of the Electric Sheep Fencing, LLC.
37
 *
38
 * 6. Redistributions of any form whatsoever must retain the following
39
 *    acknowledgment:
40
 *
41
 * "This product includes software developed by the pfSense Project
42
 * for use in the pfSense software distribution (http://www.pfsense.org/).
43
 *
44
 * THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
45
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
46
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
47
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE pfSense PROJECT OR
48
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
49
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
50
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
51
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
53
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
54
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
55
 * OF THE POSSIBILITY OF SUCH DAMAGE.
56
 */
57 36254e4a Scott Ullrich
58 5b237745 Scott Ullrich
/* include all configuration functions */
59 a55cdcc0 Ermal Lu?i
require_once("config.inc");
60
require_once("functions.inc");
61 71fdaecd Ermal
require_once("filter.inc");
62 856e58a6 Scott Ullrich
require_once("radius.inc");
63 156487ed Ermal Lu?i
require_once("voucher.inc");
64 0bd34ed6 Scott Ullrich
65 023aa1f2 Scott Ullrich
function get_default_captive_portal_html() {
66 b4792bf8 Ermal
	global $config, $g, $cpzone;
67 0e296bce Ermal
68 d18f3f6e Phil Davis
	$translated_text1 = sprintf(gettext("%s captive portal"), $g['product_name']);
69
	$translated_text2 = sprintf(gettext("Welcome to the %s Captive Portal!"), $g['product_name']);
70
	$translated_text3 = gettext("Username:");
71
	$translated_text4 = gettext("Password:");
72 0e296bce Ermal
	$htmltext = <<<EOD
73 1e0b1727 Phil Davis
<html>
74
<body>
75
<form method="post" action="\$PORTAL_ACTION\$">
76 0e296bce Ermal
	<input name="redirurl" type="hidden" value="\$PORTAL_REDIRURL\$">
77
	<input name="zone" type="hidden" value="\$PORTAL_ZONE\$">
78
	<center>
79
	<table cellpadding="6" cellspacing="0" width="550" height="380" style="border:1px solid #000000">
80 5f18e743 NOYB
	<tr height="10" style="background-color:#990000">
81 0e296bce Ermal
		<td style="border-bottom:1px solid #000000">
82
			<font color='white'>
83
			<b>
84 d18f3f6e Phil Davis
				{$translated_text1}
85 0e296bce Ermal
			</b>
86
			</font>
87
		</td>
88
	</tr>
89
	<tr>
90
		<td>
91
			<div id="mainlevel">
92 023aa1f2 Scott Ullrich
			<center>
93 0e296bce Ermal
			<table width="100%" border="0" cellpadding="5" cellspacing="0">
94
			<tr>
95
				<td>
96
					<center>
97
					<div id="mainarea">
98
					<center>
99
					<table width="100%" border="0" cellpadding="5" cellspacing="5">
100 023aa1f2 Scott Ullrich
					<tr>
101
						<td>
102 0e296bce Ermal
							<div id="maindivarea">
103
							<center>
104
								<div id='statusbox'>
105
									<font color='red' face='arial' size='+1'>
106
									<b>
107
										\$PORTAL_MESSAGE\$
108
									</b>
109
									</font>
110
								</div>
111 8cd558b6 ayvis
								<br />
112 0e296bce Ermal
								<div id='loginbox'>
113
								<table>
114 d18f3f6e Phil Davis
									<tr><td colspan="2"><center>{$translated_text2}</td></tr>
115 87e7fdea bcyrill
									<tr><td>&nbsp;</td></tr>
116 5f18e743 NOYB
									<tr><td class="text-right">{$translated_text3}</td><td><input name="auth_user" type="text" style="border: 1px dashed;"></td></tr>
117
									<tr><td class="text-right">{$translated_text4}</td><td><input name="auth_pass" type="password" style="border: 1px dashed;"></td></tr>
118 87e7fdea bcyrill
									<tr><td>&nbsp;</td></tr>
119 0e296bce Ermal
120
EOD;
121
122 1e0b1727 Phil Davis
	if (isset($config['voucher'][$cpzone]['enable'])) {
123 d18f3f6e Phil Davis
		$translated_text = gettext("Enter Voucher Code:");
124 1e0b1727 Phil Davis
		$htmltext .= <<<EOD
125 87e7fdea bcyrill
									<tr>
126 5f18e743 NOYB
										<td class="text-right">{$translated_text} </td>
127 87e7fdea bcyrill
										<td><input name="auth_voucher" type="text" style="border:1px dashed;" size="22"></td>
128
									</tr>
129 36254e4a Scott Ullrich
130 023aa1f2 Scott Ullrich
EOD;
131 c2056357 Scott Ullrich
	}
132 0bd34ed6 Scott Ullrich
133 d18f3f6e Phil Davis
	$translated_text = gettext("Continue");
134 0e296bce Ermal
	$htmltext .= <<<EOD
135 87e7fdea bcyrill
									<tr>
136 d18f3f6e Phil Davis
										<td colspan="2"><center><input name="accept" type="submit" value="{$translated_text}"></center></td>
137 87e7fdea bcyrill
									</tr>
138 0e296bce Ermal
								</table>
139
								</div>
140
							</center>
141 b260c8e0 Scott Ullrich
							</div>
142
						</td>
143
					</tr>
144 0e296bce Ermal
					</table>
145
					</center>
146
					</div>
147
					</center>
148
				</td>
149
			</tr>
150
			</table>
151 b260c8e0 Scott Ullrich
			</center>
152 0e296bce Ermal
			</div>
153
		</td>
154
	</tr>
155
	</table>
156
	</center>
157
</form>
158 1e0b1727 Phil Davis
</body>
159 5b237745 Scott Ullrich
</html>
160
161 023aa1f2 Scott Ullrich
EOD;
162 0bd34ed6 Scott Ullrich
163 023aa1f2 Scott Ullrich
	return $htmltext;
164
}
165 0bd34ed6 Scott Ullrich
166 3a4b0147 Ermal
function captiveportal_load_modules() {
167 87e7fdea bcyrill
	global $config;
168 3a4b0147 Ermal
169
	mute_kernel_msgs();
170 87e7fdea bcyrill
	if (!is_module_loaded("ipfw.ko")) {
171
		mwexec("/sbin/kldload ipfw");
172
		/* make sure ipfw is not on pfil hooks */
173 971de1f9 Renato Botelho
		set_sysctl(array(
174
			"net.inet.ip.pfil.inbound" => "pf", "net.inet6.ip6.pfil.inbound" => "pf",
175
			"net.inet.ip.pfil.outbound" => "pf", "net.inet6.ip6.pfil.outbound" => "pf")
176
		);
177 87e7fdea bcyrill
	}
178 2657f21f Ermal
	/* Activate layer2 filtering */
179 971de1f9 Renato Botelho
	set_sysctl(array("net.link.ether.ipfw" => "1", "net.inet.ip.fw.one_pass" => "1"));
180 c06bdb94 Ermal
181 3a4b0147 Ermal
	/* Always load dummynet now that even allowed ip and mac passthrough use it. */
182
	if (!is_module_loaded("dummynet.ko")) {
183
		mwexec("/sbin/kldload dummynet");
184 971de1f9 Renato Botelho
		set_sysctl(array("net.inet.ip.dummynet.io_fast" => "1", "net.inet.ip.dummynet.hash_size" => "256"));
185 3a4b0147 Ermal
	}
186
	unmute_kernel_msgs();
187
}
188
189 023aa1f2 Scott Ullrich
function captiveportal_configure() {
190 baec2b00 Ermal
	global $config, $cpzone, $cpzoneid;
191 023aa1f2 Scott Ullrich
192 b4792bf8 Ermal
	if (is_array($config['captiveportal'])) {
193
		foreach ($config['captiveportal'] as $cpkey => $cp) {
194
			$cpzone = $cpkey;
195 baec2b00 Ermal
			$cpzoneid = $cp['zoneid'];
196 b4792bf8 Ermal
			captiveportal_configure_zone($cp);
197
		}
198 4010266a Ermal
	}
199 b4792bf8 Ermal
}
200
201
function captiveportal_configure_zone($cpcfg) {
202 baec2b00 Ermal
	global $config, $g, $cpzone, $cpzoneid;
203 b4792bf8 Ermal
204
	$captiveportallck = lock("captiveportal{$cpzone}", LOCK_EX);
205 1e0b1727 Phil Davis
206 b4792bf8 Ermal
	if (isset($cpcfg['enable'])) {
207 023aa1f2 Scott Ullrich
208 285ef132 Ermal LUÇI
		if (platform_booting()) {
209 b4792bf8 Ermal
			echo "Starting captive portal({$cpcfg['zone']})... ";
210 023aa1f2 Scott Ullrich
211 37e67d04 Ermal
			/* remove old information */
212 26ee5aaf Ermal
			unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
213 1e0b1727 Phil Davis
		} else {
214 37e67d04 Ermal
			captiveportal_syslog("Reconfiguring captive portal({$cpcfg['zone']}).");
215 1e0b1727 Phil Davis
		}
216 023aa1f2 Scott Ullrich
217 37e67d04 Ermal
		/* init ipfw rules */
218
		captiveportal_init_rules(true);
219 023aa1f2 Scott Ullrich
220
		/* kill any running minicron */
221 b4792bf8 Ermal
		killbypid("{$g['varrun_path']}/cp_prunedb_{$cpzone}.pid");
222
223 023aa1f2 Scott Ullrich
		/* initialize minicron interval value */
224 b4792bf8 Ermal
		$croninterval = $cpcfg['croninterval'] ? $cpcfg['croninterval'] : 60;
225 023aa1f2 Scott Ullrich
226
		/* double check if the $croninterval is numeric and at least 10 seconds. If not we set it to 60 to avoid problems */
227 1e0b1727 Phil Davis
		if ((!is_numeric($croninterval)) || ($croninterval < 10)) {
228 eb7aa263 Ermal
			$croninterval = 60;
229 1e0b1727 Phil Davis
		}
230 023aa1f2 Scott Ullrich
231
		/* write portal page */
232 1e0b1727 Phil Davis
		if (is_array($cpcfg['page']) && $cpcfg['page']['htmltext']) {
233 b4792bf8 Ermal
			$htmltext = base64_decode($cpcfg['page']['htmltext']);
234 1e0b1727 Phil Davis
		} else {
235 023aa1f2 Scott Ullrich
			/* example/template page */
236
			$htmltext = get_default_captive_portal_html();
237 5b237745 Scott Ullrich
		}
238
239 b4792bf8 Ermal
		$fd = @fopen("{$g['varetc_path']}/captiveportal_{$cpzone}.html", "w");
240 5b237745 Scott Ullrich
		if ($fd) {
241 7a7e94a7 Scott Ullrich
			// Special case handling.  Convert so that we can pass this page
242
			// through the PHP interpreter later without clobbering the vars.
243 b4792bf8 Ermal
			$htmltext = str_replace("\$PORTAL_ZONE\$", "#PORTAL_ZONE#", $htmltext);
244 7a7e94a7 Scott Ullrich
			$htmltext = str_replace("\$PORTAL_REDIRURL\$", "#PORTAL_REDIRURL#", $htmltext);
245
			$htmltext = str_replace("\$PORTAL_MESSAGE\$", "#PORTAL_MESSAGE#", $htmltext);
246
			$htmltext = str_replace("\$CLIENT_MAC\$", "#CLIENT_MAC#", $htmltext);
247
			$htmltext = str_replace("\$CLIENT_IP\$", "#CLIENT_IP#", $htmltext);
248
			$htmltext = str_replace("\$PORTAL_ACTION\$", "#PORTAL_ACTION#", $htmltext);
249 1e0b1727 Phil Davis
			if ($cpcfg['preauthurl']) {
250 b4792bf8 Ermal
				$htmltext = str_replace("\$PORTAL_REDIRURL\$", "{$cpcfg['preauthurl']}", $htmltext);
251
				$htmltext = str_replace("#PORTAL_REDIRURL#", "{$cpcfg['preauthurl']}", $htmltext);
252 c4e228f3 Scott Ullrich
			}
253 5b237745 Scott Ullrich
			fwrite($fd, $htmltext);
254 36254e4a Scott Ullrich
			fclose($fd);
255 5b237745 Scott Ullrich
		}
256 2e62a7c4 Ermal
		unset($htmltext);
257 36254e4a Scott Ullrich
258 5b237745 Scott Ullrich
		/* write error page */
259 1e0b1727 Phil Davis
		if (is_array($cpcfg['page']) && $cpcfg['page']['errtext']) {
260 b4792bf8 Ermal
			$errtext = base64_decode($cpcfg['page']['errtext']);
261 1e0b1727 Phil Davis
		} else {
262 a34b8b3b Ermal
			/* example page  */
263
			$errtext = get_default_captive_portal_html();
264 5b237745 Scott Ullrich
		}
265
266 b4792bf8 Ermal
		$fd = @fopen("{$g['varetc_path']}/captiveportal-{$cpzone}-error.html", "w");
267 5b237745 Scott Ullrich
		if ($fd) {
268 7a7e94a7 Scott Ullrich
			// Special case handling.  Convert so that we can pass this page
269
			// through the PHP interpreter later without clobbering the vars.
270 b4792bf8 Ermal
			$errtext = str_replace("\$PORTAL_ZONE\$", "#PORTAL_ZONE#", $errtext);
271 7a7e94a7 Scott Ullrich
			$errtext = str_replace("\$PORTAL_REDIRURL\$", "#PORTAL_REDIRURL#", $errtext);
272
			$errtext = str_replace("\$PORTAL_MESSAGE\$", "#PORTAL_MESSAGE#", $errtext);
273
			$errtext = str_replace("\$CLIENT_MAC\$", "#CLIENT_MAC#", $errtext);
274
			$errtext = str_replace("\$CLIENT_IP\$", "#CLIENT_IP#", $errtext);
275
			$errtext = str_replace("\$PORTAL_ACTION\$", "#PORTAL_ACTION#", $errtext);
276 1e0b1727 Phil Davis
			if ($cpcfg['preauthurl']) {
277 b4792bf8 Ermal
				$errtext = str_replace("\$PORTAL_REDIRURL\$", "{$cpcfg['preauthurl']}", $errtext);
278
				$errtext = str_replace("#PORTAL_REDIRURL#", "{$cpcfg['preauthurl']}", $errtext);
279 c4e228f3 Scott Ullrich
			}
280 5b237745 Scott Ullrich
			fwrite($fd, $errtext);
281 36254e4a Scott Ullrich
			fclose($fd);
282 5b237745 Scott Ullrich
		}
283 2e62a7c4 Ermal
		unset($errtext);
284 36254e4a Scott Ullrich
285 b4792bf8 Ermal
		/* write logout page */
286 1e0b1727 Phil Davis
		if (is_array($cpcfg['page']) && $cpcfg['page']['logouttext']) {
287 b4792bf8 Ermal
			$logouttext = base64_decode($cpcfg['page']['logouttext']);
288 1e0b1727 Phil Davis
		} else {
289 5b87b24e Ermal
			/* example page */
290 d18f3f6e Phil Davis
			$translated_text1 = gettext("Redirecting...");
291
			$translated_text2 = gettext("Redirecting to");
292
			$translated_text3 = gettext("Logout");
293
			$translated_text4 = gettext("Click the button below to disconnect");
294 5b87b24e Ermal
			$logouttext = <<<EOD
295 91f026b0 ayvis
<html>
296 d18f3f6e Phil Davis
<head><title>{$translated_text1}</title></head>
297 91f026b0 ayvis
<body>
298
<span style="font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 11px;">
299 d18f3f6e Phil Davis
<b>{$translated_text2} <a href="<?=\$my_redirurl;?>"><?=\$my_redirurl;?></a>...</b>
300 91f026b0 ayvis
</span>
301
<script type="text/javascript">
302 1b244d38 Colin Fleming
//<![CDATA[
303 5b87b24e Ermal
LogoutWin = window.open('', 'Logout', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=256,height=64');
304
if (LogoutWin) {
305 91f026b0 ayvis
	LogoutWin.document.write('<html>');
306 d18f3f6e Phil Davis
	LogoutWin.document.write('<head><title>{$translated_text3}</title></head>') ;
307 5f18e743 NOYB
	LogoutWin.document.write('<body style="background-color:#435370">');
308
	LogoutWin.document.write('<div class="text-center" style="color: #ffffff; font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 11px;">') ;
309 d18f3f6e Phil Davis
	LogoutWin.document.write('<b>{$translated_text4}</b><p />');
310 91f026b0 ayvis
	LogoutWin.document.write('<form method="POST" action="<?=\$logouturl;?>">');
311
	LogoutWin.document.write('<input name="logout_id" type="hidden" value="<?=\$sessionid;?>" />');
312
	LogoutWin.document.write('<input name="zone" type="hidden" value="<?=\$cpzone;?>" />');
313 d18f3f6e Phil Davis
	LogoutWin.document.write('<input name="logout" type="submit" value="{$translated_text3}" />');
314 91f026b0 ayvis
	LogoutWin.document.write('</form>');
315
	LogoutWin.document.write('</div></body>');
316
	LogoutWin.document.write('</html>');
317 5060dea7 Scott Ullrich
	LogoutWin.document.close();
318 5b87b24e Ermal
}
319
320 6991e1a6 Erik Fonnesbeck
document.location.href="<?=\$my_redirurl;?>";
321 1b244d38 Colin Fleming
//]]>
322 91f026b0 ayvis
</script>
323
</body>
324
</html>
325 5b87b24e Ermal
326
EOD;
327
		}
328
329 b4792bf8 Ermal
		$fd = @fopen("{$g['varetc_path']}/captiveportal-{$cpzone}-logout.html", "w");
330 5b87b24e Ermal
		if ($fd) {
331
			fwrite($fd, $logouttext);
332
			fclose($fd);
333
		}
334 2e62a7c4 Ermal
		unset($logouttext);
335
336 0bd34ed6 Scott Ullrich
		/* write elements */
337
		captiveportal_write_elements();
338 5b237745 Scott Ullrich
339 57cc06af Chris Buechler
		/* kill any running CP nginx instances */
340 4877ae1e Chris Buechler
		killbypid("{$g['varrun_path']}/nginx-{$cpzone}-CaptivePortal.pid");
341
		killbypid("{$g['varrun_path']}/nginx-{$cpzone}-CaptivePortal-SSL.pid");
342 37e67d04 Ermal
343 769e254e Ermal
		/* start up the webserving daemon */
344 e3cf528e bcyrill
		captiveportal_init_webgui_zone($cpcfg);
345 36254e4a Scott Ullrich
346 aa69dbd2 Scott Ullrich
		/* Kill any existing prunecaptiveportal processes */
347 1e0b1727 Phil Davis
		if (file_exists("{$g['varrun_path']}/cp_prunedb_{$cpzone}.pid")) {
348 b4792bf8 Ermal
			killbypid("{$g['varrun_path']}/cp_prunedb_{$cpzone}.pid");
349 1e0b1727 Phil Davis
		}
350 aa69dbd2 Scott Ullrich
351 0bd34ed6 Scott Ullrich
		/* start pruning process (interval defaults to 60 seconds) */
352 b4792bf8 Ermal
		mwexec("/usr/local/bin/minicron $croninterval {$g['varrun_path']}/cp_prunedb_{$cpzone}.pid " .
353
			"/etc/rc.prunecaptiveportal {$cpzone}");
354 36254e4a Scott Ullrich
355 d99f7864 Scott Ullrich
		/* generate radius server database */
356 37e67d04 Ermal
		unlink_if_exists("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db");
357 d31bc32a Ermal
		captiveportal_init_radius_servers();
358 36254e4a Scott Ullrich
359 285ef132 Ermal LUÇI
		if (platform_booting()) {
360 e35ab948 Michael Newton
			/* send Accounting-On to server */
361
			captiveportal_send_server_accounting();
362 b4792bf8 Ermal
			echo "done\n";
363 e35ab948 Michael Newton
		}
364 36254e4a Scott Ullrich
365 5b237745 Scott Ullrich
	} else {
366 4877ae1e Chris Buechler
		killbypid("{$g['varrun_path']}/nginx-{$cpzone}-CaptivePortal.pid");
367
		killbypid("{$g['varrun_path']}/nginx-{$cpzone}-CaptivePortal-SSL.pid");
368 b4792bf8 Ermal
		killbypid("{$g['varrun_path']}/cp_prunedb_{$cpzone}.pid");
369
		@unlink("{$g['varetc_path']}/captiveportal_{$cpzone}.html");
370
		@unlink("{$g['varetc_path']}/captiveportal-{$cpzone}-error.html");
371
		@unlink("{$g['varetc_path']}/captiveportal-{$cpzone}-logout.html");
372 f8cb8685 Ermal
373
		captiveportal_radius_stop_all();
374
375 62f20eab Michael Newton
		/* send Accounting-Off to server */
376 285ef132 Ermal LUÇI
		if (!platform_booting()) {
377 62f20eab Michael Newton
			captiveportal_send_server_accounting(true);
378
		}
379
380 8b34498c Ermal
		/* remove old information */
381 26ee5aaf Ermal
		unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
382 8b34498c Ermal
		unlink_if_exists("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db");
383 0f50d70d Ermal
		unlink_if_exists("{$g['vardb_path']}/captiveportal_{$cpzone}.rules");
384 7fb23399 Ermal
		/* Release allocated pipes for this zone */
385
		captiveportal_free_dnrules();
386 12ee8fe4 Scott Ullrich
387 0fcae2ec Ermal
		mwexec("/sbin/ipfw zone {$cpzoneid} destroy", true);
388 b4792bf8 Ermal
389 1e0b1727 Phil Davis
		if (empty($config['captiveportal'])) {
390 971de1f9 Renato Botelho
			set_single_sysctl("net.link.ether.ipfw", "0");
391 1e0b1727 Phil Davis
		} else {
392 c06bdb94 Ermal
			/* Deactivate ipfw(4) if not needed */
393
			$cpactive = false;
394 52034432 Renato Botelho
			if (is_array($config['captiveportal'])) {
395
				foreach ($config['captiveportal'] as $cpkey => $cp) {
396
					if (isset($cp['enable'])) {
397
						$cpactive = true;
398
						break;
399
					}
400 c06bdb94 Ermal
				}
401
			}
402 1e0b1727 Phil Davis
			if ($cpactive === false) {
403 971de1f9 Renato Botelho
				set_single_sysctl("net.link.ether.ipfw", "0");
404 1e0b1727 Phil Davis
			}
405 c06bdb94 Ermal
		}
406 3db19cf1 Scott Ullrich
	}
407 36254e4a Scott Ullrich
408 f8b11310 Ermal Lu?i
	unlock($captiveportallck);
409 1e0b1727 Phil Davis
410 5b237745 Scott Ullrich
	return 0;
411
}
412
413 769e254e Ermal
function captiveportal_init_webgui() {
414 b4792bf8 Ermal
	global $config, $cpzone;
415 769e254e Ermal
416 b4792bf8 Ermal
	if (is_array($config['captiveportal'])) {
417 e3cf528e bcyrill
		foreach ($config['captiveportal'] as $cpkey => $cp) {
418 b4792bf8 Ermal
			$cpzone = $cpkey;
419 e3cf528e bcyrill
			captiveportal_init_webgui_zone($cp);
420 b4792bf8 Ermal
		}
421
	}
422
}
423 769e254e Ermal
424 e3cf528e bcyrill
function captiveportal_init_webgui_zonename($zone) {
425
	global $config, $cpzone;
426 1e0b1727 Phil Davis
427 e3cf528e bcyrill
	if (isset($config['captiveportal'][$zone])) {
428
		$cpzone = $zone;
429
		captiveportal_init_webgui_zone($config['captiveportal'][$zone]);
430
	}
431
}
432
433
function captiveportal_init_webgui_zone($cpcfg) {
434 b4792bf8 Ermal
	global $g, $config, $cpzone;
435
436 1e0b1727 Phil Davis
	if (!isset($cpcfg['enable'])) {
437 b4792bf8 Ermal
		return;
438 1e0b1727 Phil Davis
	}
439 b4792bf8 Ermal
440
	if (isset($cpcfg['httpslogin'])) {
441 36f6ed35 bcyrill
		$cert = lookup_cert($cpcfg['certref']);
442 adca02c4 bcyrill
		$crt = base64_decode($cert['crt']);
443
		$key = base64_decode($cert['prv']);
444
		$ca = ca_chain($cert);
445 87e7fdea bcyrill
446 c4a278f2 Chris Buechler
		/* generate nginx configuration */
447 1e0b1727 Phil Davis
		if (!empty($cpcfg['listenporthttps'])) {
448 1c69dbb0 Ermal
			$listenporthttps = $cpcfg['listenporthttps'];
449 1e0b1727 Phil Davis
		} else {
450 1c69dbb0 Ermal
			$listenporthttps = 8001 + $cpcfg['zoneid'];
451 1e0b1727 Phil Davis
		}
452 c4a278f2 Chris Buechler
		system_generate_nginx_config("{$g['varetc_path']}/nginx-{$cpzone}-CaptivePortal-SSL.conf",
453
			$crt, $key, $ca, "nginx-{$cpzone}-CaptivePortal-SSL.pid", $listenporthttps, "/usr/local/captiveportal",
454 a96f2d3d Ermal
			"cert-{$cpzone}-portal.pem", "ca-{$cpzone}-portal.pem", $cpzone);
455 769e254e Ermal
	}
456
457 c4a278f2 Chris Buechler
	/* generate nginx configuration */
458 1e0b1727 Phil Davis
	if (!empty($cpcfg['listenporthttp'])) {
459 1c69dbb0 Ermal
		$listenporthttp = $cpcfg['listenporthttp'];
460 1e0b1727 Phil Davis
	} else {
461 1c69dbb0 Ermal
		$listenporthttp = 8000 + $cpcfg['zoneid'];
462 1e0b1727 Phil Davis
	}
463 c4a278f2 Chris Buechler
	system_generate_nginx_config("{$g['varetc_path']}/nginx-{$cpzone}-CaptivePortal.conf",
464
		"", "", "", "nginx-{$cpzone}-CaptivePortal.pid", $listenporthttp, "/usr/local/captiveportal",
465 a96f2d3d Ermal
		"", "", $cpzone);
466 769e254e Ermal
467 c4a278f2 Chris Buechler
	@unlink("{$g['varrun']}/nginx-{$cpzone}-CaptivePortal.pid");
468
	/* attempt to start nginx */
469 4877ae1e Chris Buechler
	$res = mwexec("/usr/local/sbin/nginx -c {$g['varetc_path']}/nginx-{$cpzone}-CaptivePortal.conf");
470 769e254e Ermal
471
	/* fire up https instance */
472 fe2eb995 Ermal
	if (isset($cpcfg['httpslogin'])) {
473 c4a278f2 Chris Buechler
		@unlink("{$g['varrun']}/nginx-{$cpzone}-CaptivePortal-SSL.pid");
474
		$res = mwexec("/usr/local/sbin/nginx -c {$g['varetc_path']}/nginx-{$cpzone}-CaptivePortal-SSL.conf");
475 fe2eb995 Ermal
	}
476 769e254e Ermal
}
477
478 a08db603 Ermal LUÇI
function captiveportal_init_rules_byinterface($interface) {
479
	global $cpzone, $cpzoneid, $config;
480
481 1e0b1727 Phil Davis
	if (!is_array($config['captiveportal'])) {
482 a08db603 Ermal LUÇI
		return;
483 1e0b1727 Phil Davis
	}
484 a08db603 Ermal LUÇI
485
	foreach ($config['captiveportal'] as $cpkey => $cp) {
486
		$cpzone = $cpkey;
487
		$cpzoneid = $cp['zoneid'];
488
		$cpinterfaces = explode(",", $cp['interface']);
489
		if (in_array($interface, $cpinterfaces)) {
490
			captiveportal_init_rules();
491
			break;
492
		}
493
	}
494
}
495
496 847e5e82 Scott Ullrich
/* reinit will disconnect all users, be careful! */
497 1d9e9cca Ermal
function captiveportal_init_rules($reinit = false) {
498 baec2b00 Ermal
	global $config, $g, $cpzone, $cpzoneid;
499 36254e4a Scott Ullrich
500 1e0b1727 Phil Davis
	if (!isset($config['captiveportal'][$cpzone]['enable'])) {
501 769e254e Ermal
		return;
502 1e0b1727 Phil Davis
	}
503 769e254e Ermal
504 3a4b0147 Ermal
	captiveportal_load_modules();
505 3b68d29c Ermal
	mwexec("/sbin/ipfw zone {$cpzoneid} create", true);
506 f084049d Ermal LUÇI
507
	/* Cleanup so nothing is leaked */
508 fd9e6066 Ermal LUÇI
	captiveportal_free_dnrules();
509 f084049d Ermal LUÇI
	unlink_if_exists("{$g['vardb_path']}/captiveportal_{$cpzone}.rules");
510 3a4b0147 Ermal
511 769e254e Ermal
	$cpips = array();
512
	$ifaces = get_configured_interface_list();
513 b4792bf8 Ermal
	$cpinterfaces = explode(",", $config['captiveportal'][$cpzone]['interface']);
514 769e254e Ermal
	$firsttime = 0;
515
	foreach ($cpinterfaces as $cpifgrp) {
516 1e0b1727 Phil Davis
		if (!isset($ifaces[$cpifgrp])) {
517 769e254e Ermal
			continue;
518 1e0b1727 Phil Davis
		}
519 769e254e Ermal
		$tmpif = get_real_interface($cpifgrp);
520
		if (!empty($tmpif)) {
521
			$cpipm = get_interface_ip($cpifgrp);
522
			if (is_ipaddr($cpipm)) {
523 6538d22f jim-p
				$cpips[] = $cpipm;
524 4169bf0c Chris Buechler
				if (is_array($config['virtualip']['vip'])) {
525 701f5caa Chris Buechler
					foreach ($config['virtualip']['vip'] as $vip) {
526
						if (($vip['interface'] == $cpifgrp) && (($vip['mode'] == "carp") || ($vip['mode'] == "ipalias"))) {
527
							$cpips[] = $vip['subnet'];
528
						}
529 769e254e Ermal
					}
530
				}
531
			}
532 3b68d29c Ermal
			mwexec("/sbin/ipfw zone {$cpzoneid} madd {$tmpif}", true);
533 769e254e Ermal
		}
534
	}
535
	if (count($cpips) > 0) {
536
		$cpactive = true;
537 1e0b1727 Phil Davis
	} else {
538 769e254e Ermal
		return false;
539 1e0b1727 Phil Davis
	}
540 769e254e Ermal
541 1e0b1727 Phil Davis
	if ($reinit == false) {
542 b4792bf8 Ermal
		$captiveportallck = lock("captiveportal{$cpzone}");
543 1e0b1727 Phil Davis
	}
544 eade409a Ermal
545 98bf4991 Ermal LUÇI
	$cprules = <<<EOD
546
547
flush
548
add 65291 allow pfsync from any to any
549
add 65292 allow carp from any to any
550 181a843c Scott Ullrich
551 3db19cf1 Scott Ullrich
# layer 2: pass ARP
552 ec509679 Ermal
add 65301 pass layer2 mac-type arp,rarp
553 b9d1d810 Scott Ullrich
# pfsense requires for WPA
554 ec509679 Ermal
add 65302 pass layer2 mac-type 0x888e,0x88c7
555 ee79fcda Ermal
# PPP Over Ethernet Session Stage/Discovery Stage
556 ec509679 Ermal
add 65303 pass layer2 mac-type 0x8863,0x8864
557 684c787e Scott Ullrich
558 ee79fcda Ermal
# layer 2: block anything else non-IP(v4/v6)
559 ec509679 Ermal
add 65307 deny layer2 not mac-type ip,ipv6
560 3db19cf1 Scott Ullrich
561
EOD;
562
563 b01792a0 Ermal
	$rulenum = 65310;
564 98bf4991 Ermal LUÇI
	/* These tables contain host ips */
565
	$cprules .= "add {$rulenum} pass ip from any to table(100) in\n";
566
	$rulenum++;
567
	$cprules .= "add {$rulenum} pass ip from table(100) to any out\n";
568
	$rulenum++;
569 4e322e2c Phil Davis
	foreach ($cpips as $cpip) {
570 98bf4991 Ermal LUÇI
		$cprules .= "table 100 add {$cpip}\n";
571 4e322e2c Phil Davis
	}
572 42d59a5d Luiz Otavio O Souza
	$cprules .= "add {$rulenum} pass ip from any to 255.255.255.255 in\n";
573 2f27dffd Ermal
	$rulenum++;
574 42d59a5d Luiz Otavio O Souza
	$cprules .= "add {$rulenum} pass ip from 255.255.255.255 to any out\n";
575 2f27dffd Ermal
	$rulenum++;
576 42d59a5d Luiz Otavio O Souza
577 b01792a0 Ermal
	/* Allowed ips */
578 aea56408 Ermal
	$cprules .= "add {$rulenum} pipe tablearg ip from table(3) to any in\n";
579 b01792a0 Ermal
	$rulenum++;
580 7aff41fe Ermal
	$cprules .= "add {$rulenum} pipe tablearg ip from any to table(4) in\n";
581
	$rulenum++;
582
	$cprules .= "add {$rulenum} pipe tablearg ip from table(3) to any out\n";
583
	$rulenum++;
584 aea56408 Ermal
	$cprules .= "add {$rulenum} pipe tablearg ip from any to table(4) out\n";
585 b01792a0 Ermal
	$rulenum++;
586
587
	/* Authenticated users rules. */
588 ec509679 Ermal
	$cprules .= "add {$rulenum} pipe tablearg ip from table(1) to any in\n";
589 10b9dfcf Ermal
	$rulenum++;
590 ec509679 Ermal
	$cprules .= "add {$rulenum} pipe tablearg ip from any to table(2) out\n";
591 10b9dfcf Ermal
	$rulenum++;
592 bb58ed63 Ermal
593 1e0b1727 Phil Davis
	if (!empty($config['captiveportal'][$cpzone]['listenporthttp'])) {
594 391cad9f Renato Botelho
		$listenporthttp = $config['captiveportal'][$cpzone]['listenporthttp'];
595 1e0b1727 Phil Davis
	} else {
596 36de334e Renato Botelho
		$listenporthttp = 8000 + $cpzoneid;
597 1e0b1727 Phil Davis
	}
598 06a45374 Ermal
599 d61cbd50 bcyrill
	if (isset($config['captiveportal'][$cpzone]['httpslogin'])) {
600 1e0b1727 Phil Davis
		if (!empty($config['captiveportal'][$cpzone]['listenporthttps'])) {
601 1c69dbb0 Ermal
			$listenporthttps = $config['captiveportal'][$cpzone]['listenporthttps'];
602 1e0b1727 Phil Davis
		} else {
603 36de334e Renato Botelho
			$listenporthttps = 8001 + $cpzoneid;
604 1e0b1727 Phil Davis
		}
605
		if (!isset($config['captiveportal'][$cpzone]['nohttpsforwards'])) {
606
			$cprules .= "add 65531 fwd 127.0.0.1,{$listenporthttps} tcp from any to any dst-port 443 in\n";
607
		}
608 06a45374 Ermal
	}
609 1e0b1727 Phil Davis
610 b4792bf8 Ermal
	$cprules .= <<<EOD
611 5480497a Scott Ullrich
612 d44bccc7 Scott Ullrich
# redirect non-authenticated clients to captive portal
613 1e0b1727 Phil Davis
add 65532 fwd 127.0.0.1,{$listenporthttp} tcp from any to any dst-port 80 in
614 3db19cf1 Scott Ullrich
# let the responses from the captive portal web server back out
615 ec509679 Ermal
add 65533 pass tcp from any to any out
616 3db19cf1 Scott Ullrich
# block everything else
617 ec509679 Ermal
add 65534 deny all from any to any
618 3db19cf1 Scott Ullrich
619
EOD;
620
621 769e254e Ermal
	/* generate passthru mac database */
622
	$cprules .= captiveportal_passthrumac_configure(true);
623
	$cprules .= "\n";
624 55c18b30 Scott Ullrich
625 769e254e Ermal
	/* allowed ipfw rules to make allowed ip work */
626
	$cprules .= captiveportal_allowedip_configure();
627
628 55c18b30 Scott Ullrich
	/* allowed ipfw rules to make allowed hostnames work */
629
	$cprules .= captiveportal_allowedhostname_configure();
630 1e0b1727 Phil Davis
631 769e254e Ermal
	/* load rules */
632 b4792bf8 Ermal
	file_put_contents("{$g['tmp_path']}/ipfw_{$cpzone}.cp.rules", $cprules);
633 baec2b00 Ermal
	mwexec("/sbin/ipfw -x {$cpzoneid} -q {$g['tmp_path']}/ipfw_{$cpzone}.cp.rules", true);
634 b4792bf8 Ermal
	//@unlink("{$g['tmp_path']}/ipfw_{$cpzone}.cp.rules");
635 98bf4991 Ermal LUÇI
	unset($cprules);
636 eade409a Ermal
637 1e0b1727 Phil Davis
	if ($reinit == false) {
638 eade409a Ermal
		unlock($captiveportallck);
639 1e0b1727 Phil Davis
	}
640 3db19cf1 Scott Ullrich
}
641
642 1e0b1727 Phil Davis
/*
643 f1f58a6f Ermal
 * Remove clients that have been around for longer than the specified amount of time
644 eb7aa263 Ermal
 * db file structure:
645 338c0941 Ermal
 * timestamp,ipfw_rule_no,clientip,clientmac,username,sessionid,password,session_timeout,idle_timeout,session_terminate_time,interim_interval
646 eb7aa263 Ermal
 * (password is in Base64 and only saved when reauthentication is enabled)
647
 */
648 5b237745 Scott Ullrich
function captiveportal_prune_old() {
649 baec2b00 Ermal
	global $g, $config, $cpzone, $cpzoneid;
650 b4792bf8 Ermal
651 1e0b1727 Phil Davis
	if (empty($cpzone)) {
652 b4792bf8 Ermal
		return;
653 1e0b1727 Phil Davis
	}
654 23c4f978 Scott Ullrich
655 f1f58a6f Ermal
	$cpcfg = $config['captiveportal'][$cpzone];
656
	$vcpcfg = $config['voucher'][$cpzone];
657
658 5060dea7 Scott Ullrich
	/* check for expired entries */
659 f1f58a6f Ermal
	$idletimeout = 0;
660
	$timeout = 0;
661 1e0b1727 Phil Davis
	if (!empty($cpcfg['timeout']) && is_numeric($cpcfg['timeout'])) {
662 f1f58a6f Ermal
		$timeout = $cpcfg['timeout'] * 60;
663 1e0b1727 Phil Davis
	}
664 f1f58a6f Ermal
665 1e0b1727 Phil Davis
	if (!empty($cpcfg['idletimeout']) && is_numeric($cpcfg['idletimeout'])) {
666 f1f58a6f Ermal
		$idletimeout = $cpcfg['idletimeout'] * 60;
667 1e0b1727 Phil Davis
	}
668 f1f58a6f Ermal
669
	/* Is there any job to do? */
670 87e7fdea bcyrill
	if (!$timeout && !$idletimeout && !isset($cpcfg['reauthenticate']) &&
671 ae52d165 Renato Botelho
	    !isset($cpcfg['radiussession_timeout']) && !isset($vcpcfg['enable'])) {
672 5060dea7 Scott Ullrich
		return;
673 1e0b1727 Phil Davis
	}
674 5060dea7 Scott Ullrich
675 ebc0e4b6 Ermal
	$radiussrvs = captiveportal_get_radius_servers();
676 006802ab Ermal
677 26ee5aaf Ermal
	/* Read database */
678
	/* NOTE: while this can be simplified in non radius case keep as is for now */
679 5060dea7 Scott Ullrich
	$cpdb = captiveportal_read_db();
680 0bd34ed6 Scott Ullrich
681 5060dea7 Scott Ullrich
	$unsetindexes = array();
682 5ebe85e9 Ermal
	$voucher_needs_sync = false;
683 1e0b1727 Phil Davis
	/*
684 b09c2d86 Ermal
	 * Snapshot the time here to use for calculation to speed up the process.
685
	 * If something is missed next run will catch it!
686
	 */
687
	$pruning_time = time();
688 3e5c0ab7 Ermal
	foreach ($cpdb as $cpentry) {
689 b5ccfb0b Renato Botelho
		$stop_time = $pruning_time;
690 5060dea7 Scott Ullrich
691
		$timedout = false;
692
		$term_cause = 1;
693 1e0b1727 Phil Davis
		if (empty($cpentry[11])) {
694 74a40221 Ermal
			$cpentry[11] = 'first';
695 1e0b1727 Phil Davis
		}
696 74a40221 Ermal
		$radiusservers = $radiussrvs[$cpentry[11]];
697 5060dea7 Scott Ullrich
698
		/* hard timeout? */
699
		if ($timeout) {
700 5705c60a Renato Botelho
			if (($pruning_time - $cpentry[0]) >= $timeout) {
701 5060dea7 Scott Ullrich
				$timedout = true;
702 5705c60a Renato Botelho
				$term_cause = 5; // Session-Timeout
703 5060dea7 Scott Ullrich
			}
704 eb7aa263 Ermal
		}
705 23c4f978 Scott Ullrich
706 5060dea7 Scott Ullrich
		/* Session-Terminate-Time */
707 5705c60a Renato Botelho
		if (!$timedout && !empty($cpentry[9])) {
708
			if ($pruning_time >= $cpentry[9]) {
709 5060dea7 Scott Ullrich
				$timedout = true;
710 5705c60a Renato Botelho
				$term_cause = 5; // Session-Timeout
711 5060dea7 Scott Ullrich
			}
712
		}
713
714
		/* check if the radius idle_timeout attribute has been set and if its set change the idletimeout to this value */
715 5705c60a Renato Botelho
		$uidletimeout = (is_numeric($cpentry[8])) ? $cpentry[8] : $idletimeout;
716 5060dea7 Scott Ullrich
		/* if an idle timeout is specified, get last activity timestamp from ipfw */
717 1a1967d6 Ermal
		if (!$timedout && $uidletimeout > 0) {
718 fcaf1709 Ermal
			$lastact = captiveportal_get_last_activity($cpentry[2], $cpentry[3]);
719 5060dea7 Scott Ullrich
			/*	If the user has logged on but not sent any traffic they will never be logged out.
720 1e0b1727 Phil Davis
			 *	We "fix" this by setting lastact to the login timestamp.
721 f56a73f1 Scott Ullrich
			 */
722 5705c60a Renato Botelho
			$lastact = $lastact ? $lastact : $cpentry[0];
723 b09c2d86 Ermal
			if ($lastact && (($pruning_time - $lastact) >= $uidletimeout)) {
724 5060dea7 Scott Ullrich
				$timedout = true;
725 5705c60a Renato Botelho
				$term_cause = 4; // Idle-Timeout
726 5060dea7 Scott Ullrich
				$stop_time = $lastact; // Entry added to comply with WISPr
727
			}
728 336e3c1c Charlie
		}
729
730 5060dea7 Scott Ullrich
		/* if vouchers are configured, activate session timeouts */
731 5705c60a Renato Botelho
		if (!$timedout && isset($vcpcfg['enable']) && !empty($cpentry[7])) {
732
			if ($pruning_time >= ($cpentry[0] + $cpentry[7])) {
733 5060dea7 Scott Ullrich
				$timedout = true;
734 5705c60a Renato Botelho
				$term_cause = 5; // Session-Timeout
735 5ebe85e9 Ermal
				$voucher_needs_sync = true;
736 5060dea7 Scott Ullrich
			}
737
		}
738
739
		/* if radius session_timeout is enabled and the session_timeout is not null, then check if the user should be logged out */
740 5705c60a Renato Botelho
		if (!$timedout && isset($cpcfg['radiussession_timeout']) && !empty($cpentry[7])) {
741
			if ($pruning_time >= ($cpentry[0] + $cpentry[7])) {
742 5060dea7 Scott Ullrich
				$timedout = true;
743 5705c60a Renato Botelho
				$term_cause = 5; // Session-Timeout
744 5060dea7 Scott Ullrich
			}
745
		}
746
747
		if ($timedout) {
748 086cf944 Phil Davis
			captiveportal_disconnect($cpentry, $radiusservers, $term_cause, $stop_time);
749 5705c60a Renato Botelho
			captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "TIMEOUT");
750
			$unsetindexes[] = $cpentry[5];
751 5060dea7 Scott Ullrich
		}
752
753
		/* do periodic RADIUS reauthentication? */
754
		if (!$timedout && !empty($radiusservers)) {
755 f1f58a6f Ermal
			if (isset($cpcfg['radacct_enable'])) {
756 ab225849 jim-p
				if (substr($cpcfg['reauthenticateacct'], 0, 9) == "stopstart") {
757 5060dea7 Scott Ullrich
					/* stop and restart accounting */
758 ab225849 jim-p
					if ($cpcfg['reauthenticateacct'] == "stopstartfreeradius") {
759
						$rastart_time = 0;
760
						$rastop_time = 60;
761
					} else {
762
						$rastart_time = $cpentry[0];
763
						$rastop_time = null;
764
					}
765 5705c60a Renato Botelho
					RADIUS_ACCOUNTING_STOP($cpentry[1], // ruleno
766
						$cpentry[4], // username
767
						$cpentry[5], // sessionid
768 ab225849 jim-p
						$rastart_time, // start time
769 5060dea7 Scott Ullrich
						$radiusservers,
770 5705c60a Renato Botelho
						$cpentry[2], // clientip
771
						$cpentry[3], // clientmac
772 ab225849 jim-p
						10, // NAS Request
773
						false, // Not an interim request
774
						$rastop_time); // Stop Time
775 0cd7c91a Renato Botelho
					$clientsn = (is_ipaddrv6($cpentry[2])) ? 128 : 32;
776
					$_gb = @pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XZEROENTRY, 1, $cpentry[2], $clientsn, $cpentry[3]);
777
					$_gb = @pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XZEROENTRY, 2, $cpentry[2], $clientsn, $cpentry[3]);
778 ab225849 jim-p
					if ($cpcfg['reauthenticateacct'] == "stopstartfreeradius") {
779
						/* Need to pause here or the FreeRADIUS server gets confused about packet ordering. */
780
						sleep(1);
781
					}
782 5705c60a Renato Botelho
					RADIUS_ACCOUNTING_START($cpentry[1], // ruleno
783
						$cpentry[4], // username
784
						$cpentry[5], // sessionid
785 5060dea7 Scott Ullrich
						$radiusservers,
786 5705c60a Renato Botelho
						$cpentry[2], // clientip
787
						$cpentry[3]); // clientmac
788 f1f58a6f Ermal
				} else if ($cpcfg['reauthenticateacct'] == "interimupdate") {
789 5705c60a Renato Botelho
					$session_time = $pruning_time - $cpentry[0];
790 1e0b1727 Phil Davis
					if (!empty($cpentry[10]) && $cpentry[10] > 60) {
791 5705c60a Renato Botelho
						$interval = $cpentry[10];
792 1e0b1727 Phil Davis
					} else {
793 338c0941 Ermal
						$interval = 0;
794 1e0b1727 Phil Davis
					}
795 338c0941 Ermal
					$past_interval_min = ($session_time > $interval);
796 1e0b1727 Phil Davis
					if ($interval != 0) {
797 40a8f669 Renato Botelho
						$within_interval = ($session_time % $interval >= 0 && $session_time % $interval <= 59);
798 1e0b1727 Phil Davis
					}
799 40a8f669 Renato Botelho
					if ($interval === 0 || ($interval > 0 && $past_interval_min && $within_interval)) {
800 5705c60a Renato Botelho
						RADIUS_ACCOUNTING_STOP($cpentry[1], // ruleno
801
							$cpentry[4], // username
802
							$cpentry[5], // sessionid
803
							$cpentry[0], // start time
804 338c0941 Ermal
							$radiusservers,
805 5705c60a Renato Botelho
							$cpentry[2], // clientip
806
							$cpentry[3], // clientmac
807
							10, // NAS Request
808
							true); // Interim Updates
809 338c0941 Ermal
					}
810 5060dea7 Scott Ullrich
				}
811
			}
812 23c4f978 Scott Ullrich
813 5060dea7 Scott Ullrich
			/* check this user against RADIUS again */
814 f1f58a6f Ermal
			if (isset($cpcfg['reauthenticate'])) {
815 5705c60a Renato Botelho
				$auth_list = RADIUS_AUTHENTICATION($cpentry[4], // username
816
					base64_decode($cpentry[6]), // password
817 5060dea7 Scott Ullrich
					$radiusservers,
818 5705c60a Renato Botelho
					$cpentry[2], // clientip
819
					$cpentry[3], // clientmac
820
					$cpentry[1]); // ruleno
821 5060dea7 Scott Ullrich
				if ($auth_list['auth_val'] == 3) {
822 5705c60a Renato Botelho
					captiveportal_disconnect($cpentry, $radiusservers, 17);
823
					captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "RADIUS_DISCONNECT", $auth_list['reply_message']);
824
					$unsetindexes[] = $cpentry[5];
825 1e0b1727 Phil Davis
				} else if ($auth_list['auth_val'] == 2) {
826 aec0f2fd Ermal
					captiveportal_reapply_attributes($cpentry, $auth_list);
827 1e0b1727 Phil Davis
				}
828 5060dea7 Scott Ullrich
			}
829
		}
830
	}
831 f32eae2d Ermal
	unset($cpdb);
832 23c4f978 Scott Ullrich
833 522f1cc7 Ermal
	captiveportal_prune_old_automac();
834
835 1e0b1727 Phil Davis
	if ($voucher_needs_sync == true) {
836 f416763b Phil Davis
		/* Trigger a sync of the vouchers on config */
837 5ebe85e9 Ermal
		send_event("service sync vouchers");
838 1e0b1727 Phil Davis
	}
839 5ebe85e9 Ermal
840 5060dea7 Scott Ullrich
	/* write database */
841 1e0b1727 Phil Davis
	if (!empty($unsetindexes)) {
842 26ee5aaf Ermal
		captiveportal_remove_entries($unsetindexes);
843 1e0b1727 Phil Davis
	}
844 5b237745 Scott Ullrich
}
845
846 522f1cc7 Ermal
function captiveportal_prune_old_automac() {
847 baec2b00 Ermal
	global $g, $config, $cpzone, $cpzoneid;
848 522f1cc7 Ermal
849
	if (is_array($config['captiveportal'][$cpzone]['passthrumac']) && isset($config['captiveportal'][$cpzone]['passthrumacaddusername'])) {
850
		$tmpvoucherdb = array();
851
		$macrules = "";
852
		$writecfg = false;
853
		foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $eid => $emac) {
854
			if ($emac['logintype'] == "voucher") {
855 bae729da Ermal
				if (isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) {
856
					if (isset($tmpvoucherdb[$emac['username']])) {
857
						$temac = $config['captiveportal'][$cpzone]['passthrumac'][$tmpvoucherdb[$emac['username']]];
858
						$ruleno = captiveportal_get_ipfw_passthru_ruleno($temac['mac']);
859
						$pipeno = captiveportal_get_dn_passthru_ruleno($temac['mac']);
860
						if ($ruleno) {
861
							captiveportal_free_ipfw_ruleno($ruleno);
862
							$macrules .= "delete {$ruleno}";
863
							++$ruleno;
864
							$macrules .= "delete {$ruleno}";
865
						}
866
						if ($pipeno) {
867
							captiveportal_free_dn_ruleno($pipeno);
868
							$macrules .= "pipe delete {$pipeno}\n";
869
							++$pipeno;
870
							$macrules .= "pipe delete {$pipeno}\n";
871
						}
872
						$writecfg = true;
873
						captiveportal_logportalauth($temac['username'], $temac['mac'], $temac['ip'], "DUPLICATE {$temac['username']} LOGIN - TERMINATING OLD SESSION");
874
						unset($config['captiveportal'][$cpzone]['passthrumac'][$tmpvoucherdb[$emac['username']]]);
875 aea56408 Ermal
					}
876 bae729da Ermal
					$tmpvoucherdb[$emac['username']] = $eid;
877 522f1cc7 Ermal
				}
878
				if (voucher_auth($emac['username']) <= 0) {
879
					$ruleno = captiveportal_get_ipfw_passthru_ruleno($emac['mac']);
880 aea56408 Ermal
					$pipeno = captiveportal_get_dn_passthru_ruleno($emac['mac']);
881 522f1cc7 Ermal
					if ($ruleno) {
882 aea56408 Ermal
						captiveportal_free_ipfw_ruleno($ruleno);
883 522f1cc7 Ermal
						$macrules .= "delete {$ruleno}";
884
						++$ruleno;
885
						$macrules .= "delete {$ruleno}";
886
					}
887 aea56408 Ermal
					if ($pipeno) {
888
						captiveportal_free_dn_ruleno($pipeno);
889
						$macrules .= "pipe delete {$pipeno}\n";
890
						++$pipeno;
891
						$macrules .= "pipe delete {$pipeno}\n";
892
					}
893 522f1cc7 Ermal
					$writecfg = true;
894
					captiveportal_logportalauth($emac['username'], $emac['mac'], $emac['ip'], "EXPIRED {$emac['username']} LOGIN - TERMINATING SESSION");
895
					unset($config['captiveportal'][$cpzone]['passthrumac'][$eid]);
896
				}
897
			}
898
		}
899 bae729da Ermal
		unset($tmpvoucherdb);
900 522f1cc7 Ermal
		if (!empty($macrules)) {
901
			@file_put_contents("{$g['tmp_path']}/macentry.prunerules.tmp", $macrules);
902 2e62a7c4 Ermal
			unset($macrules);
903 baec2b00 Ermal
			mwexec("/sbin/ipfw -x {$cpzoneid} -q {$g['tmp_path']}/macentry.prunerules.tmp");
904 522f1cc7 Ermal
		}
905 1e0b1727 Phil Davis
		if ($writecfg === true) {
906 522f1cc7 Ermal
			write_config("Prune session for auto-added macs");
907 1e0b1727 Phil Davis
		}
908 522f1cc7 Ermal
	}
909
}
910
911 3db19cf1 Scott Ullrich
/* remove a single client according to the DB entry */
912 086cf944 Phil Davis
function captiveportal_disconnect($dbent, $radiusservers, $term_cause = 1, $stop_time = null) {
913 cbe38717 Ermal
	global $g, $config, $cpzone, $cpzoneid;
914 d99f7864 Scott Ullrich
915
	$stop_time = (empty($stop_time)) ? time() : $stop_time;
916
917
	/* this client needs to be deleted - remove ipfw rules */
918 b4792bf8 Ermal
	if (isset($config['captiveportal'][$cpzone]['radacct_enable']) && !empty($radiusservers)) {
919 00de7de6 jim-p
		if ($config['captiveportal'][$cpzone]['reauthenticateacct'] == "stopstartfreeradius") {
920
			/* Interim updates are on so the session time must be reported as the elapsed time since the previous interim update. */
921
			$session_time = ($stop_time - $dbent[0]) % 60;
922
			$start_time = $stop_time - $session_time;
923
		} else {
924
			$start_time = $dbent[0];
925
		}
926 5705c60a Renato Botelho
		RADIUS_ACCOUNTING_STOP($dbent[1], // ruleno
927
			$dbent[4], // username
928
			$dbent[5], // sessionid
929 00de7de6 jim-p
			$start_time, // start time
930 5060dea7 Scott Ullrich
			$radiusservers,
931 5705c60a Renato Botelho
			$dbent[2], // clientip
932
			$dbent[3], // clientmac
933 5060dea7 Scott Ullrich
			$term_cause, // Acct-Terminate-Cause
934
			false,
935
			$stop_time);
936 d99f7864 Scott Ullrich
	}
937 1e0b1727 Phil Davis
938 5705c60a Renato Botelho
	if (is_ipaddr($dbent[2])) {
939 ddd69ea9 bcyrill
		/* Delete client's ip entry from tables 1 and 2. */
940 0cd7c91a Renato Botelho
		$clientsn = (is_ipaddrv6($dbent[2])) ? 128 : 32;
941
		pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XDEL, 1, $dbent[2], $clientsn, $dbent[3]);
942
		pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XDEL, 2, $dbent[2], $clientsn, $dbent[3]);
943 32c392aa Ermal
		/* XXX: Redundant?! Ensure all pf(4) states are killed. */
944 c2e2d133 Ermal
		$_gb = @pfSense_kill_states($dbent[2]);
945
		$_gb = @pfSense_kill_srcstates($dbent[2]);
946 32c392aa Ermal
	}
947 f9f71ad3 Ermal Lu?i
948 1e0b1727 Phil Davis
	/*
949 f9f71ad3 Ermal Lu?i
	* These are the pipe numbers we use to control traffic shaping for each logged in user via captive portal
950
	* We could get an error if the pipe doesn't exist but everything should still be fine
951
	*/
952 5705c60a Renato Botelho
	if (!empty($dbent[1])) {
953 c2e2d133 Ermal
		$_gb = @pfSense_pipe_action("pipe delete {$dbent[1]}");
954
		$_gb = @pfSense_pipe_action("pipe delete " . ($dbent[1]+1));
955 7a7abeba Scott Ullrich
956 6cbda317 Ermal
		/* Release the ruleno so it can be reallocated to new clients. */
957 5705c60a Renato Botelho
		captiveportal_free_dn_ruleno($dbent[1]);
958 6cbda317 Ermal
	}
959 d322e3b3 Scott Ullrich
960
	// XMLRPC Call over to the master Voucher node
961 1e0b1727 Phil Davis
	if (!empty($config['voucher'][$cpzone]['vouchersyncdbip'])) {
962 b4792bf8 Ermal
		$syncip   = $config['voucher'][$cpzone]['vouchersyncdbip'];
963
		$syncport = $config['voucher'][$cpzone]['vouchersyncport'];
964
		$syncpass = $config['voucher'][$cpzone]['vouchersyncpass'];
965
		$vouchersyncusername = $config['voucher'][$cpzone]['vouchersyncusername'];
966 f989aa5b Ermal
		$remote_status = xmlrpc_sync_voucher_disconnect($dbent, $syncip, $syncport, $syncpass, $vouchersyncusername, $term_cause, $stop_time);
967 d322e3b3 Scott Ullrich
	}
968
969 3db19cf1 Scott Ullrich
}
970 12ee8fe4 Scott Ullrich
971 006802ab Ermal
/* remove a single client by sessionid */
972
function captiveportal_disconnect_client($sessionid, $term_cause = 1, $logoutReason = "LOGOUT") {
973 26ee5aaf Ermal
	global $g, $config;
974 36254e4a Scott Ullrich
975 69c97c32 Chris Buechler
	$sessionid = SQLite3::escapeString($sessionid);
976 d99f7864 Scott Ullrich
	$radiusservers = captiveportal_get_radius_servers();
977 006802ab Ermal
978
	/* read database */
979 5038fb53 bcyrill
	$result = captiveportal_read_db("WHERE sessionid = '{$sessionid}'");
980 d99f7864 Scott Ullrich
981
	/* find entry */
982 5038fb53 bcyrill
	if (!empty($result)) {
983 26ee5aaf Ermal
		captiveportal_write_db("DELETE FROM captiveportal WHERE sessionid = '{$sessionid}'");
984
985 5038fb53 bcyrill
		foreach ($result as $cpentry) {
986 1e0b1727 Phil Davis
			if (empty($cpentry[11])) {
987 74a40221 Ermal
				$cpentry[11] = 'first';
988 1e0b1727 Phil Davis
			}
989 74a40221 Ermal
			captiveportal_disconnect($cpentry, $radiusservers[$cpentry[11]], $term_cause);
990 5705c60a Renato Botelho
			captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "DISCONNECT");
991 5038fb53 bcyrill
		}
992
		unset($result);
993 26ee5aaf Ermal
	}
994 5b237745 Scott Ullrich
}
995
996
/* send RADIUS acct stop for all current clients */
997 d31bc32a Ermal
function captiveportal_radius_stop_all() {
998 b4792bf8 Ermal
	global $config, $cpzone;
999 d99f7864 Scott Ullrich
1000 1e0b1727 Phil Davis
	if (!isset($config['captiveportal'][$cpzone]['radacct_enable'])) {
1001 d99f7864 Scott Ullrich
		return;
1002 1e0b1727 Phil Davis
	}
1003 d99f7864 Scott Ullrich
1004
	$radiusservers = captiveportal_get_radius_servers();
1005 40b48c6c Ermal Lu?i
	if (!empty($radiusservers)) {
1006 d31bc32a Ermal
		$cpdb = captiveportal_read_db();
1007
		foreach ($cpdb as $cpentry) {
1008 1e0b1727 Phil Davis
			if (empty($cpentry[11])) {
1009 74a40221 Ermal
				$cpentry[11] = 'first';
1010 1e0b1727 Phil Davis
			}
1011 74a40221 Ermal
			if (!empty($radiusservers[$cpentry[11]])) {
1012 5705c60a Renato Botelho
				RADIUS_ACCOUNTING_STOP($cpentry[1], // ruleno
1013
					$cpentry[4], // username
1014
					$cpentry[5], // sessionid
1015
					$cpentry[0], // start time
1016 74a40221 Ermal
					$radiusservers[$cpentry[11]],
1017 5705c60a Renato Botelho
					$cpentry[2], // clientip
1018
					$cpentry[3], // clientmac
1019
					7); // Admin Reboot
1020 ebc0e4b6 Ermal
			}
1021 d99f7864 Scott Ullrich
		}
1022
	}
1023 5b237745 Scott Ullrich
}
1024
1025 621fed0e Ermal
function captiveportal_passthrumac_configure_entry($macent, $pipeinrule = false) {
1026 a413e743 Renato Botelho
	global $config, $g, $cpzone;
1027 aea56408 Ermal
1028 7519cc29 Ermal
	$bwUp = 0;
1029 1e0b1727 Phil Davis
	if (!empty($macent['bw_up'])) {
1030 7519cc29 Ermal
		$bwUp = $macent['bw_up'];
1031 1e0b1727 Phil Davis
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultup'])) {
1032 7519cc29 Ermal
		$bwUp = $config['captiveportal'][$cpzone]['bwdefaultup'];
1033 1e0b1727 Phil Davis
	}
1034 7519cc29 Ermal
	$bwDown = 0;
1035 1e0b1727 Phil Davis
	if (!empty($macent['bw_down'])) {
1036 7519cc29 Ermal
		$bwDown = $macent['bw_down'];
1037 1e0b1727 Phil Davis
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultdn'])) {
1038 7519cc29 Ermal
		$bwDown = $config['captiveportal'][$cpzone]['bwdefaultdn'];
1039 1e0b1727 Phil Davis
	}
1040 d5ae560d Ermal
1041 10b9dfcf Ermal
	$ruleno = captiveportal_get_next_ipfw_ruleno();
1042 d5ae560d Ermal
1043 666f88e0 Renato Botelho
	if ($macent['action'] == 'pass') {
1044 621fed0e Ermal
		$rules = "";
1045 666f88e0 Renato Botelho
		$pipeno = captiveportal_get_next_dn_ruleno();
1046
1047
		$pipeup = $pipeno;
1048 1e0b1727 Phil Davis
		if ($pipeinrule == true) {
1049 621fed0e Ermal
			$_gb = @pfSense_pipe_action("pipe {$pipeno} config bw {$bwUp}Kbit/s queue 100 buckets 16");
1050 1e0b1727 Phil Davis
		} else {
1051 621fed0e Ermal
			$rules .= "pipe {$pipeno} config bw {$bwUp}Kbit/s queue 100 buckets 16\n";
1052 1e0b1727 Phil Davis
		}
1053
1054 666f88e0 Renato Botelho
		$pipedown = $pipeno + 1;
1055 1e0b1727 Phil Davis
		if ($pipeinrule == true) {
1056 621fed0e Ermal
			$_gb = @pfSense_pipe_action("pipe {$pipedown} config bw {$bwDown}Kbit/s queue 100 buckets 16");
1057 1e0b1727 Phil Davis
		} else {
1058 621fed0e Ermal
			$rules .= "pipe {$pipedown} config bw {$bwDown}Kbit/s queue 100 buckets 16\n";
1059 1e0b1727 Phil Davis
		}
1060 666f88e0 Renato Botelho
1061 621fed0e Ermal
		$rules .= "add {$ruleno} pipe {$pipeup} ip from any to any MAC any {$macent['mac']}\n";
1062 666f88e0 Renato Botelho
		$ruleno++;
1063
		$rules .= "add {$ruleno} pipe {$pipedown} ip from any to any MAC {$macent['mac']} any\n";
1064 0d33f1fc Renato Botelho
	}
1065 d5ae560d Ermal
1066
	return $rules;
1067
}
1068
1069 666f88e0 Renato Botelho
function captiveportal_passthrumac_delete_entry($macent) {
1070 5eee3755 Renato Botelho
	$rules = "";
1071 666f88e0 Renato Botelho
1072 a413e743 Renato Botelho
	if ($macent['action'] == 'pass') {
1073
		$ruleno = captiveportal_get_ipfw_passthru_ruleno($macent['mac']);
1074 666f88e0 Renato Botelho
1075 1e0b1727 Phil Davis
		if (!$ruleno) {
1076 a413e743 Renato Botelho
			return $rules;
1077 1e0b1727 Phil Davis
		}
1078 666f88e0 Renato Botelho
1079 a413e743 Renato Botelho
		captiveportal_free_ipfw_ruleno($ruleno);
1080 666f88e0 Renato Botelho
1081 a413e743 Renato Botelho
		$rules .= "delete {$ruleno}\n";
1082 5eee3755 Renato Botelho
		$rules .= "delete " . ++$ruleno . "\n";
1083 666f88e0 Renato Botelho
1084
		$pipeno = captiveportal_get_dn_passthru_ruleno($macent['mac']);
1085
1086
		if (!empty($pipeno)) {
1087
			captiveportal_free_dn_ruleno($pipeno);
1088 5eee3755 Renato Botelho
			$rules .= "pipe delete " . $pipeno . "\n";
1089
			$rules .= "pipe delete " . ++$pipeno . "\n";
1090 666f88e0 Renato Botelho
		}
1091
	}
1092
1093 5eee3755 Renato Botelho
	return $rules;
1094 666f88e0 Renato Botelho
}
1095
1096 41196b69 Ermal LUÇI
function captiveportal_passthrumac_configure($filename = false, $startindex = 0, $stopindex = 0) {
1097 b4792bf8 Ermal
	global $config, $g, $cpzone;
1098 36254e4a Scott Ullrich
1099 d5ae560d Ermal
	$rules = "";
1100 36254e4a Scott Ullrich
1101 621fed0e Ermal
	if (is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
1102 41196b69 Ermal LUÇI
		if ($stopindex > 0) {
1103
			$fd = fopen($filename, "w");
1104
			for ($idx = $startindex; $idx <= $stopindex; $idx++) {
1105
				if (isset($config['captiveportal'][$cpzone]['passthrumac'][$idx])) {
1106
					$rules = captiveportal_passthrumac_configure_entry($config['captiveportal'][$cpzone]['passthrumac'][$idx]);
1107
					fwrite($fd, $rules);
1108
				}
1109
			}
1110
			fclose($fd);
1111
1112
			return;
1113
		} else {
1114
			$nentries = count($config['captiveportal'][$cpzone]['passthrumac']);
1115
			if ($nentries > 2000) {
1116
				$nloops = $nentries / 1000;
1117
				$remainder= $nentries % 1000;
1118 1e0b1727 Phil Davis
				for ($i = 0; $i < $nloops; $i++) {
1119 41196b69 Ermal LUÇI
					mwexec_bg("/usr/local/sbin/fcgicli -f /etc/rc.captiveportal_configure_mac -d \"cpzone={$cpzone}&startidx=" . ($i * 1000) . "&stopidx=" . ((($i+1) * 1000) - 1) . "\"");
1120 1e0b1727 Phil Davis
				}
1121
				if ($remainder > 0) {
1122 41196b69 Ermal LUÇI
					mwexec_bg("/usr/local/sbin/fcgicli -f /etc/rc.captiveportal_configure_mac -d \"cpzone={$cpzone}&startidx=" . ($i * 1000) . "&stopidx=" . (($i* 1000) + $remainder) ."\"");
1123 1e0b1727 Phil Davis
				}
1124 41196b69 Ermal LUÇI
			} else {
1125 1e0b1727 Phil Davis
				foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $macent) {
1126 41196b69 Ermal LUÇI
					$rules .= captiveportal_passthrumac_configure_entry($macent, true);
1127 1e0b1727 Phil Davis
				}
1128 41196b69 Ermal LUÇI
			}
1129 fe9ec12b Ermal LUÇI
		}
1130 621fed0e Ermal
	}
1131 0bd34ed6 Scott Ullrich
1132 d5ae560d Ermal
	return $rules;
1133 5b237745 Scott Ullrich
}
1134
1135 fac13a5e Ermal
function captiveportal_passthrumac_findbyname($username) {
1136 b4792bf8 Ermal
	global $config, $cpzone;
1137 fac13a5e Ermal
1138 b4792bf8 Ermal
	if (is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
1139
		foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $macent) {
1140 1e0b1727 Phil Davis
			if ($macent['username'] == $username) {
1141 fac13a5e Ermal
				return $macent;
1142 1e0b1727 Phil Davis
			}
1143 fac13a5e Ermal
		}
1144
	}
1145
	return NULL;
1146
}
1147
1148 1e0b1727 Phil Davis
/*
1149 b01792a0 Ermal
 * table (3=IN)/(4=OUT) hold allowed ip's without bw limits
1150
 */
1151 1272429c Ermal
function captiveportal_allowedip_configure_entry($ipent, $ishostname = false) {
1152 1b584e3f Ermal
	global $g;
1153 b01792a0 Ermal
1154 8b73cc7e Scott Ullrich
	/*  Instead of copying this entire function for something
1155
	 *  easy such as hostname vs ip address add this check
1156
	 */
1157 bb58ed63 Ermal
	if ($ishostname === true) {
1158 285ef132 Ermal LUÇI
		if (!platform_booting()) {
1159 9e875e0c Renato Botelho
			$ipaddress = gethostbyname($ipent['hostname']);
1160 1e0b1727 Phil Davis
			if (!is_ipaddr($ipaddress)) {
1161 1b584e3f Ermal
				return;
1162 1e0b1727 Phil Davis
			}
1163
		} else {
1164 9e875e0c Renato Botelho
			$ipaddress = "";
1165 1e0b1727 Phil Davis
		}
1166
	} else {
1167 9e875e0c Renato Botelho
		$ipaddress = $ipent['ip'];
1168 1e0b1727 Phil Davis
	}
1169 0b108eda Scott Ullrich
1170 b01792a0 Ermal
	$rules = "";
1171 1272429c Ermal
	$cp_filterdns_conf = "";
1172 2e080989 Ermal
	$enBwup = 0;
1173 1e0b1727 Phil Davis
	if (!empty($ipent['bw_up'])) {
1174 ca321bfd Ermal
		$enBwup = intval($ipent['bw_up']);
1175 1e0b1727 Phil Davis
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultup'])) {
1176 2e080989 Ermal
		$enBwup = $config['captiveportal'][$cpzone]['bwdefaultup'];
1177 1e0b1727 Phil Davis
	}
1178 2e080989 Ermal
	$enBwdown = 0;
1179 1e0b1727 Phil Davis
	if (!empty($ipent['bw_down'])) {
1180 2e080989 Ermal
		$enBwdown = intval($ipent['bw_down']);
1181 1e0b1727 Phil Davis
	} else if (!empty($config['captiveportal'][$cpzone]['bwdefaultdn'])) {
1182 2e080989 Ermal
		$enBwdown = $config['captiveportal'][$cpzone]['bwdefaultdn'];
1183 1e0b1727 Phil Davis
	}
1184 b01792a0 Ermal
1185 aea56408 Ermal
	$pipeno = captiveportal_get_next_dn_ruleno();
1186 c2e2d133 Ermal
	$_gb = @pfSense_pipe_action("pipe {$pipeno} config bw {$enBwup}Kbit/s queue 100 buckets 16");
1187 aea56408 Ermal
	$pipedown = $pipeno + 1;
1188 c2e2d133 Ermal
	$_gb = @pfSense_pipe_action("pipe {$pipedown} config bw {$enBwdown}Kbit/s queue 100 buckets 16");
1189 1272429c Ermal
	if ($ishostname === true) {
1190
		$cp_filterdns_conf .= "ipfw {$ipent['hostname']} 3 pipe {$pipeno}\n";
1191
		$cp_filterdns_conf .= "ipfw {$ipent['hostname']} 4 pipe {$pipedown}\n";
1192 1e0b1727 Phil Davis
		if (!is_ipaddr($ipaddress)) {
1193 1b584e3f Ermal
			return array("", $cp_filterdns_conf);
1194 1e0b1727 Phil Davis
		}
1195 1272429c Ermal
	}
1196 d6a0379d Ermal
	$subnet = "";
1197 1e0b1727 Phil Davis
	if (!empty($ipent['sn'])) {
1198 d6a0379d Ermal
		$subnet = "/{$ipent['sn']}";
1199 1e0b1727 Phil Davis
	}
1200 9e875e0c Renato Botelho
	$rules .= "table 3 add {$ipaddress}{$subnet} {$pipeno}\n";
1201
	$rules .= "table 4 add {$ipaddress}{$subnet} {$pipedown}\n";
1202
1203 1e0b1727 Phil Davis
	if ($ishostname === true) {
1204 1272429c Ermal
		return array($rules, $cp_filterdns_conf);
1205 1e0b1727 Phil Davis
	} else {
1206 1272429c Ermal
		return $rules;
1207 1e0b1727 Phil Davis
	}
1208 f23a6091 Scott Ullrich
}
1209
1210
function captiveportal_allowedhostname_configure() {
1211 3378289a Ermal LUÇI
	global $config, $g, $cpzone, $cpzoneid;
1212 f23a6091 Scott Ullrich
1213 1272429c Ermal
	$rules = "";
1214 b4792bf8 Ermal
	if (is_array($config['captiveportal'][$cpzone]['allowedhostname'])) {
1215 1272429c Ermal
		$rules = "\n# captiveportal_allowedhostname_configure()\n";
1216
		$cp_filterdns_conf = "";
1217
		foreach ($config['captiveportal'][$cpzone]['allowedhostname'] as $hostnameent) {
1218
			$tmprules = captiveportal_allowedip_configure_entry($hostnameent, true);
1219
			$rules .= $tmprules[0];
1220
			$cp_filterdns_conf .= $tmprules[1];
1221
		}
1222
		$cp_filterdns_filename = "{$g['varetc_path']}/filterdns-{$cpzone}-captiveportal.conf";
1223
		@file_put_contents($cp_filterdns_filename, $cp_filterdns_conf);
1224
		unset($cp_filterdns_conf);
1225 1e0b1727 Phil Davis
		if (isvalidpid("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid")) {
1226 081320a4 Ermal
			sigkillbypid("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid", "HUP");
1227 1e0b1727 Phil Davis
		} else {
1228 3378289a Ermal LUÇI
			mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid -i 300 -c {$cp_filterdns_filename} -y {$cpzoneid} -d 1");
1229 1e0b1727 Phil Davis
		}
1230 7b5eab84 bcyrill
	} else {
1231
		killbypid("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid");
1232
		@unlink("{$g['varrun_path']}/filterdns-{$cpzone}-cpah.pid");
1233 55c18b30 Scott Ullrich
	}
1234 1272429c Ermal
1235 f23a6091 Scott Ullrich
	return $rules;
1236
}
1237
1238 cb0a2913 Ermal Lu?i
function captiveportal_allowedip_configure() {
1239 b4792bf8 Ermal
	global $config, $g, $cpzone;
1240 36254e4a Scott Ullrich
1241 6ce61a8f Ermal
	$rules = "";
1242 b4792bf8 Ermal
	if (is_array($config['captiveportal'][$cpzone]['allowedip'])) {
1243 1e0b1727 Phil Davis
		foreach ($config['captiveportal'][$cpzone]['allowedip'] as $ipent) {
1244 b01792a0 Ermal
			$rules .= captiveportal_allowedip_configure_entry($ipent);
1245 1e0b1727 Phil Davis
		}
1246 cb0a2913 Ermal Lu?i
	}
1247 36254e4a Scott Ullrich
1248 6ce61a8f Ermal
	return $rules;
1249 5b237745 Scott Ullrich
}
1250
1251 2d53158f stompro
/* get last activity timestamp given client IP address */
1252 bc9155c3 Ermal LUÇI
function captiveportal_get_last_activity($ip, $mac = NULL, $table = 1) {
1253 27c2e32e Renato Botelho
	global $cpzoneid;
1254 36254e4a Scott Ullrich
1255 bc9155c3 Ermal LUÇI
	$ipfwoutput = pfSense_ipfw_getTablestats($cpzoneid, IP_FW_TABLE_XLISTENTRY, $table, $ip, $mac);
1256 f9f71ad3 Ermal Lu?i
	/* Reading only from one of the tables is enough of approximation. */
1257 1272429c Ermal
	if (is_array($ipfwoutput)) {
1258 2842c8d4 Ermal LUÇI
		/* Workaround for #46652 */
1259 086cf944 Phil Davis
		if ($ipfwoutput['packets'] > 0) {
1260 2842c8d4 Ermal LUÇI
			return $ipfwoutput['timestamp'];
1261 be754c8b Ermal LUÇI
		} else {
1262
			return 0;
1263 2842c8d4 Ermal LUÇI
		}
1264 d99f7864 Scott Ullrich
	}
1265 36254e4a Scott Ullrich
1266 d99f7864 Scott Ullrich
	return 0;
1267 5b237745 Scott Ullrich
}
1268
1269 d31bc32a Ermal
function captiveportal_init_radius_servers() {
1270 b4792bf8 Ermal
	global $config, $g, $cpzone;
1271 d31bc32a Ermal
1272
	/* generate radius server database */
1273 ae52d165 Renato Botelho
	if ($config['captiveportal'][$cpzone]['radiusip'] &&
1274
	    (!isset($config['captiveportal'][$cpzone]['auth_method']) || $config['captiveportal'][$cpzone]['auth_method'] == "radius")) {
1275 b4792bf8 Ermal
		$radiusip = $config['captiveportal'][$cpzone]['radiusip'];
1276
		$radiusip2 = ($config['captiveportal'][$cpzone]['radiusip2']) ? $config['captiveportal'][$cpzone]['radiusip2'] : null;
1277 7468a29f jim-p
		$radiusip3 = ($config['captiveportal'][$cpzone]['radiusip3']) ? $config['captiveportal'][$cpzone]['radiusip3'] : null;
1278
		$radiusip4 = ($config['captiveportal'][$cpzone]['radiusip4']) ? $config['captiveportal'][$cpzone]['radiusip4'] : null;
1279 d31bc32a Ermal
1280 1e0b1727 Phil Davis
		if ($config['captiveportal'][$cpzone]['radiusport']) {
1281 b4792bf8 Ermal
			$radiusport = $config['captiveportal'][$cpzone]['radiusport'];
1282 1e0b1727 Phil Davis
		} else {
1283 d31bc32a Ermal
			$radiusport = 1812;
1284 1e0b1727 Phil Davis
		}
1285
		if ($config['captiveportal'][$cpzone]['radiusacctport']) {
1286 b4792bf8 Ermal
			$radiusacctport = $config['captiveportal'][$cpzone]['radiusacctport'];
1287 1e0b1727 Phil Davis
		} else {
1288 d31bc32a Ermal
			$radiusacctport = 1813;
1289 1e0b1727 Phil Davis
		}
1290
		if ($config['captiveportal'][$cpzone]['radiusport2']) {
1291 b4792bf8 Ermal
			$radiusport2 = $config['captiveportal'][$cpzone]['radiusport2'];
1292 1e0b1727 Phil Davis
		} else {
1293 d31bc32a Ermal
			$radiusport2 = 1812;
1294 1e0b1727 Phil Davis
		}
1295
		if ($config['captiveportal'][$cpzone]['radiusport3']) {
1296 7468a29f jim-p
			$radiusport3 = $config['captiveportal'][$cpzone]['radiusport3'];
1297 1e0b1727 Phil Davis
		} else {
1298 ebc0e4b6 Ermal
			$radiusport3 = 1812;
1299 1e0b1727 Phil Davis
		}
1300
		if ($config['captiveportal'][$cpzone]['radiusport4']) {
1301 7468a29f jim-p
			$radiusport4 = $config['captiveportal'][$cpzone]['radiusport4'];
1302 1e0b1727 Phil Davis
		} else {
1303 ebc0e4b6 Ermal
			$radiusport4 = 1812;
1304 1e0b1727 Phil Davis
		}
1305 ebc0e4b6 Ermal
1306 b4792bf8 Ermal
		$radiuskey = $config['captiveportal'][$cpzone]['radiuskey'];
1307 dbce0c2c bcyrill
		$radiuskey2 = $config['captiveportal'][$cpzone]['radiuskey2'];
1308
		$radiuskey3 = $config['captiveportal'][$cpzone]['radiuskey3'];
1309
		$radiuskey4 = $config['captiveportal'][$cpzone]['radiuskey4'];
1310 d31bc32a Ermal
1311 b4792bf8 Ermal
		$cprdsrvlck = lock("captiveportalradius{$cpzone}", LOCK_EX);
1312
		$fd = @fopen("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db", "w");
1313 d31bc32a Ermal
		if (!$fd) {
1314 7aaf60a8 k-paulius
			captiveportal_syslog("Error: cannot open RADIUS DB file in captiveportal_configure().\n");
1315 d31bc32a Ermal
			unlock($cprdsrvlck);
1316
			return 1;
1317 ebc0e4b6 Ermal
		}
1318 1e0b1727 Phil Davis
		if (isset($radiusip)) {
1319 086cf944 Phil Davis
			fwrite($fd, $radiusip . "," . $radiusport . "," . $radiusacctport . "," . $radiuskey . ",first");
1320 1e0b1727 Phil Davis
		}
1321
		if (isset($radiusip2)) {
1322 086cf944 Phil Davis
			fwrite($fd, "\n" . $radiusip2 . "," . $radiusport2 . "," . $radiusacctport . "," . $radiuskey2 . ",first");
1323 1e0b1727 Phil Davis
		}
1324
		if (isset($radiusip3)) {
1325 086cf944 Phil Davis
			fwrite($fd, "\n" . $radiusip3 . "," . $radiusport3 . "," . $radiusacctport . "," . $radiuskey3 . ",second");
1326 1e0b1727 Phil Davis
		}
1327
		if (isset($radiusip4)) {
1328 086cf944 Phil Davis
			fwrite($fd, "\n" . $radiusip4 . "," . $radiusport4 . "," . $radiusacctport . "," . $radiuskey4 . ",second");
1329 1e0b1727 Phil Davis
		}
1330 ebc0e4b6 Ermal
1331 d31bc32a Ermal
		fclose($fd);
1332
		unlock($cprdsrvlck);
1333
	}
1334
}
1335
1336 5b237745 Scott Ullrich
/* read RADIUS servers into array */
1337
function captiveportal_get_radius_servers() {
1338 b4792bf8 Ermal
	global $g, $cpzone;
1339 ac07425a Ermal
1340 b4792bf8 Ermal
	$cprdsrvlck = lock("captiveportalradius{$cpzone}");
1341
	if (file_exists("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db")) {
1342 ac07425a Ermal
		$radiusservers = array();
1343 1e0b1727 Phil Davis
		$cpradiusdb = file("{$g['vardb_path']}/captiveportal_radius_{$cpzone}.db",
1344 ac07425a Ermal
		FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
1345
		if ($cpradiusdb) {
1346 1e0b1727 Phil Davis
			foreach ($cpradiusdb as $cpradiusentry) {
1347 ac07425a Ermal
				$line = trim($cpradiusentry);
1348
				if ($line) {
1349
					$radsrv = array();
1350 086cf944 Phil Davis
					list($radsrv['ipaddr'], $radsrv['port'], $radsrv['acctport'], $radsrv['key'], $context) = explode(",", $line);
1351 ebc0e4b6 Ermal
				}
1352
				if (empty($context)) {
1353 1e0b1727 Phil Davis
					if (!is_array($radiusservers['first'])) {
1354 ebc0e4b6 Ermal
						$radiusservers['first'] = array();
1355 1e0b1727 Phil Davis
					}
1356 ebc0e4b6 Ermal
					$radiusservers['first'] = $radsrv;
1357
				} else {
1358 1e0b1727 Phil Davis
					if (!is_array($radiusservers[$context])) {
1359 ebc0e4b6 Ermal
						$radiusservers[$context] = array();
1360 1e0b1727 Phil Davis
					}
1361 ebc0e4b6 Ermal
					$radiusservers[$context][] = $radsrv;
1362 5060dea7 Scott Ullrich
				}
1363
			}
1364 2f70eac7 Ermal Lu?i
		}
1365 60b66b60 Ermal
		unlock($cprdsrvlck);
1366 ac07425a Ermal
		return $radiusservers;
1367
	}
1368
1369
	unlock($cprdsrvlck);
1370
	return false;
1371 5b237745 Scott Ullrich
}
1372
1373 3db19cf1 Scott Ullrich
/* log successful captive portal authentication to syslog */
1374
/* part of this code from php.net */
1375 086cf944 Phil Davis
function captiveportal_logportalauth($user, $mac, $ip, $status, $message = null) {
1376 d99f7864 Scott Ullrich
	// Log it
1377 1e0b1727 Phil Davis
	if (!$message) {
1378 12feed15 Ermal
		$message = "{$status}: {$user}, {$mac}, {$ip}";
1379 1e0b1727 Phil Davis
	} else {
1380 d31bc32a Ermal
		$message = trim($message);
1381 12feed15 Ermal
		$message = "{$status}: {$user}, {$mac}, {$ip}, {$message}";
1382 d31bc32a Ermal
	}
1383 f56a73f1 Scott Ullrich
	captiveportal_syslog($message);
1384
}
1385
1386
/* log simple messages to syslog */
1387
function captiveportal_syslog($message) {
1388 12feed15 Ermal
	global $cpzone;
1389
1390 f56a73f1 Scott Ullrich
	$message = trim($message);
1391 9aec47b7 Chris Buechler
	$message = "Zone: {$cpzone} - {$message}";
1392 f56a73f1 Scott Ullrich
	openlog("logportalauth", LOG_PID, LOG_LOCAL4);
1393
	// Log it
1394
	syslog(LOG_INFO, $message);
1395 d99f7864 Scott Ullrich
	closelog();
1396 3db19cf1 Scott Ullrich
}
1397
1398 086cf944 Phil Davis
function radius($username, $password, $clientip, $clientmac, $type, $radiusctx = null) {
1399 baec2b00 Ermal
	global $g, $config, $cpzoneid;
1400 d44bccc7 Scott Ullrich
1401 aea56408 Ermal
	$pipeno = captiveportal_get_next_dn_ruleno();
1402 2f70eac7 Ermal Lu?i
1403 5060dea7 Scott Ullrich
	/* If the pool is empty, return appropriate message and fail authentication */
1404 0f50d70d Ermal
	if (empty($pipeno)) {
1405 5060dea7 Scott Ullrich
		$auth_list = array();
1406
		$auth_list['auth_val'] = 1;
1407
		$auth_list['error'] = "System reached maximum login capacity";
1408
		return $auth_list;
1409
	}
1410 9befcca7 Ermal Lu?i
1411 5060dea7 Scott Ullrich
	$radiusservers = captiveportal_get_radius_servers();
1412 d44bccc7 Scott Ullrich
1413 1e0b1727 Phil Davis
	if (is_null($radiusctx)) {
1414 ebc0e4b6 Ermal
		$radiusctx = 'first';
1415 1e0b1727 Phil Davis
	}
1416 ebc0e4b6 Ermal
1417 5060dea7 Scott Ullrich
	$auth_list = RADIUS_AUTHENTICATION($username,
1418
		$password,
1419 ebc0e4b6 Ermal
		$radiusservers[$radiusctx],
1420 5060dea7 Scott Ullrich
		$clientip,
1421
		$clientmac,
1422 aea56408 Ermal
		$pipeno);
1423 5060dea7 Scott Ullrich
1424
	if ($auth_list['auth_val'] == 2) {
1425 086cf944 Phil Davis
		captiveportal_logportalauth($username, $clientmac, $clientip, $type);
1426 5060dea7 Scott Ullrich
		$sessionid = portal_allow($clientip,
1427
			$clientmac,
1428
			$username,
1429
			$password,
1430
			$auth_list,
1431 aea56408 Ermal
			$pipeno,
1432 ebc0e4b6 Ermal
			$radiusctx);
1433 d2c98878 falbertopl
	} else {
1434 1e0b1727 Phil Davis
		captiveportal_free_dn_ruleno($pipeno);
1435
	}
1436 0bd34ed6 Scott Ullrich
1437 5060dea7 Scott Ullrich
	return $auth_list;
1438 0bd34ed6 Scott Ullrich
}
1439
1440 26ee5aaf Ermal
function captiveportal_opendb() {
1441 5e71234e Chris Buechler
	global $g, $config, $cpzone, $cpzoneid;
1442 5060dea7 Scott Ullrich
1443 79e46ebd jim-p
	$db_path = "{$g['vardb_path']}/captiveportal{$cpzone}.db";
1444
	$createquery = "CREATE TABLE IF NOT EXISTS captiveportal (" .
1445
				"allow_time INTEGER, pipeno INTEGER, ip TEXT, mac TEXT, username TEXT, " .
1446
				"sessionid TEXT, bpassword TEXT, session_timeout INTEGER, idle_timeout INTEGER, " .
1447
				"session_terminate_time INTEGER, interim_interval INTEGER, radiusctx TEXT); " .
1448
			"CREATE UNIQUE INDEX IF NOT EXISTS idx_active ON captiveportal (sessionid, username); " .
1449
			"CREATE INDEX IF NOT EXISTS user ON captiveportal (username); " .
1450
			"CREATE INDEX IF NOT EXISTS ip ON captiveportal (ip); " .
1451
			"CREATE INDEX IF NOT EXISTS starttime ON captiveportal (allow_time)";
1452
1453 6b8ad2da jim-p
	try {
1454
		$DB = new SQLite3($db_path);
1455 18ca572b Chris Buechler
		$DB->busyTimeout(60000);
1456 6b8ad2da jim-p
	} catch (Exception $e) {
1457
		captiveportal_syslog("Could not open {$db_path} as an sqlite database for {$cpzone}. Error message: " . $e->getMessage() . " -- Trying again.");
1458
		unlink_if_exists($db_path);
1459
		try {
1460
			$DB = new SQLite3($db_path);
1461 18ca572b Chris Buechler
			$DB->busyTimeout(60000);
1462 6b8ad2da jim-p
		} catch (Exception $e) {
1463
			captiveportal_syslog("Still could not open {$db_path} as an sqlite database for {$cpzone}. Error message: " . $e->getMessage() . " -- Remove the database file manually and ensure there is enough free space.");
1464
			return;
1465
		}
1466
	}
1467
1468 7c38032f jim-p
	if (!$DB) {
1469
		captiveportal_syslog("Could not open {$db_path} as an sqlite database for {$cpzone}. Error message: {$DB->lastErrorMsg()}. Trying again.");
1470
		unlink_if_exists($db_path);
1471
		$DB = new SQLite3($db_path);
1472 18ca572b Chris Buechler
		$DB->busyTimeout(60000);
1473 7c38032f jim-p
		if (!$DB) {
1474
			captiveportal_syslog("Still could not open {$db_path} as an sqlite database for {$cpzone}. Error message: {$DB->lastErrorMsg()}. Remove the database file manually and ensure there is enough free space.");
1475
			return;
1476
		}
1477
	}
1478
1479 79e46ebd jim-p
	if (! $DB->exec($createquery)) {
1480
		captiveportal_syslog("Error during table {$cpzone} creation. Error message: {$DB->lastErrorMsg()}. Resetting and trying again.");
1481
1482
		/* If unable to initialize the database, reset and try again. */
1483
		$DB->close();
1484
		unset($DB);
1485
		unlink_if_exists($db_path);
1486
		$DB = new SQLite3($db_path);
1487 18ca572b Chris Buechler
		$DB->busyTimeout(60000);
1488 79e46ebd jim-p
		if ($DB->exec($createquery)) {
1489
			captiveportal_syslog("Successfully reinitialized tables for {$cpzone} -- database has been reset.");
1490 5e71234e Chris Buechler
			if (!is_numericint($cpzoneid)) {
1491
				if (is_array($config['captiveportal'])) {
1492
					foreach ($config['captiveportal'] as $cpkey => $cp) {
1493 26c7100b Renato Botelho
						if ($cpzone == $cpkey) {
1494 5e71234e Chris Buechler
							$cpzoneid = $cp['zoneid'];
1495
						}
1496
					}
1497
				}
1498
			}
1499
			if (is_numericint($cpzoneid)) {
1500
				mwexec("/sbin/ipfw -x $cpzoneid table all flush");
1501
				captiveportal_syslog("Flushed tables for {$cpzone} after database reset.");
1502
			}
1503 79e46ebd jim-p
		} else {
1504
			captiveportal_syslog("Still unable to create tables for {$cpzone}. Error message: {$DB->lastErrorMsg()}. Remove the database file manually and try again.");
1505
		}
1506 1e0b1727 Phil Davis
	}
1507 26ee5aaf Ermal
1508
	return $DB;
1509 0bd34ed6 Scott Ullrich
}
1510
1511 26ee5aaf Ermal
/* read captive portal DB into array */
1512
function captiveportal_read_db($query = "") {
1513 5cf91315 Renato Botelho
	$cpdb = array();
1514 5060dea7 Scott Ullrich
1515 26ee5aaf Ermal
	$DB = captiveportal_opendb();
1516
	if ($DB) {
1517 5cf91315 Renato Botelho
		$response = $DB->query("SELECT * FROM captiveportal {$query}");
1518 d338018f Ermal
		if ($response != FALSE) {
1519 1e0b1727 Phil Davis
			while ($row = $response->fetchArray()) {
1520 d338018f Ermal
				$cpdb[] = $row;
1521 1e0b1727 Phil Davis
			}
1522 d338018f Ermal
		}
1523 5cf91315 Renato Botelho
		$DB->close();
1524 006802ab Ermal
	}
1525 26ee5aaf Ermal
1526
	return $cpdb;
1527
}
1528
1529
function captiveportal_remove_entries($remove) {
1530
1531 1e0b1727 Phil Davis
	if (!is_array($remove) || empty($remove)) {
1532 26ee5aaf Ermal
		return;
1533 1e0b1727 Phil Davis
	}
1534 26ee5aaf Ermal
1535 1974c2d6 bcyrill
	$query = "DELETE FROM captiveportal WHERE sessionid in (";
1536 1e0b1727 Phil Davis
	foreach ($remove as $idx => $unindex) {
1537 26ee5aaf Ermal
		$query .= "'{$unindex}'";
1538 1e0b1727 Phil Davis
		if ($idx < (count($remove) - 1)) {
1539 26ee5aaf Ermal
			$query .= ",";
1540 1e0b1727 Phil Davis
		}
1541 006802ab Ermal
	}
1542 26ee5aaf Ermal
	$query .= ")";
1543
	captiveportal_write_db($query);
1544
}
1545
1546
/* write captive portal DB */
1547
function captiveportal_write_db($queries) {
1548
	global $g;
1549
1550 1e0b1727 Phil Davis
	if (is_array($queries)) {
1551 26ee5aaf Ermal
		$query = implode(";", $queries);
1552 1e0b1727 Phil Davis
	} else {
1553 26ee5aaf Ermal
		$query = $queries;
1554 1e0b1727 Phil Davis
	}
1555 26ee5aaf Ermal
1556
	$DB = captiveportal_opendb();
1557
	if ($DB) {
1558 5cf91315 Renato Botelho
		$DB->exec("BEGIN TRANSACTION");
1559
		$result = $DB->exec($query);
1560 1e0b1727 Phil Davis
		if (!$result) {
1561 5cf91315 Renato Botelho
			captiveportal_syslog("Trying to modify DB returned error: {$DB->lastErrorMsg()}");
1562 1e0b1727 Phil Davis
		} else {
1563 5cf91315 Renato Botelho
			$DB->exec("END TRANSACTION");
1564 1e0b1727 Phil Davis
		}
1565 5cf91315 Renato Botelho
		$DB->close();
1566 26ee5aaf Ermal
		return $result;
1567 1e0b1727 Phil Davis
	} else {
1568 26ee5aaf Ermal
		return true;
1569 1e0b1727 Phil Davis
	}
1570 0bd34ed6 Scott Ullrich
}
1571
1572
function captiveportal_write_elements() {
1573 b4792bf8 Ermal
	global $g, $config, $cpzone;
1574 1e0b1727 Phil Davis
1575 b4792bf8 Ermal
	$cpcfg = $config['captiveportal'][$cpzone];
1576
1577 1e0b1727 Phil Davis
	if (!is_dir($g['captiveportal_element_path'])) {
1578 769e254e Ermal
		@mkdir($g['captiveportal_element_path']);
1579 1e0b1727 Phil Davis
	}
1580 769e254e Ermal
1581 b4792bf8 Ermal
	if (is_array($cpcfg['element'])) {
1582 1fadb31d Scott Ullrich
		conf_mount_rw();
1583 b4792bf8 Ermal
		foreach ($cpcfg['element'] as $data) {
1584 84b128b6 jim-p
			/* Do not attempt to decode or write out empty files. */
1585
			if (empty($data['content']) || empty(base64_decode($data['content']))) {
1586
				unlink_if_exists("{$g['captiveportal_element_path']}/{$data['name']}");
1587
				touch("{$g['captiveportal_element_path']}/{$data['name']}");
1588
			} elseif (!@file_put_contents("{$g['captiveportal_element_path']}/{$data['name']}", base64_decode($data['content']))) {
1589 fdc55311 Carlos Eduardo Ramos
				printf(gettext("Error: cannot open '%s' in captiveportal_write_elements()%s"), $data['name'], "\n");
1590 1fadb31d Scott Ullrich
				return 1;
1591
			}
1592 1e0b1727 Phil Davis
			if (!file_exists("{$g['captiveportal_path']}/{$data['name']}")) {
1593 bdba4fa7 Ermal
				@symlink("{$g['captiveportal_element_path']}/{$data['name']}", "{$g['captiveportal_path']}/{$data['name']}");
1594 1e0b1727 Phil Davis
			}
1595 1fadb31d Scott Ullrich
		}
1596
		conf_mount_ro();
1597
	}
1598 1e0b1727 Phil Davis
1599 769e254e Ermal
	return 0;
1600 0bd34ed6 Scott Ullrich
}
1601
1602 7fb23399 Ermal
function captiveportal_free_dnrules($rulenos_start = 2000, $rulenos_range_max = 64500) {
1603
	global $cpzone;
1604
1605
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1606
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1607
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1608 1f965b69 Ermal
		$ridx = $rulenos_start;
1609
		while ($ridx < $rulenos_range_max) {
1610 7fb23399 Ermal
			if ($rules[$ridx] == $cpzone) {
1611 5b0f7191 Ermal Luçi
				$rules[$ridx] = false;
1612 7fb23399 Ermal
				$ridx++;
1613 5b0f7191 Ermal Luçi
				$rules[$ridx] = false;
1614 1f965b69 Ermal
				$ridx++;
1615 1e0b1727 Phil Davis
			} else {
1616 1f965b69 Ermal
				$ridx += 2;
1617 1e0b1727 Phil Davis
			}
1618 7fb23399 Ermal
		}
1619 1f965b69 Ermal
		file_put_contents("{$g['vardb_path']}/captiveportaldn.rules", serialize($rules));
1620
		unset($rules);
1621 7fb23399 Ermal
	}
1622
	unlock($cpruleslck);
1623
}
1624
1625 aea56408 Ermal
function captiveportal_get_next_dn_ruleno($rulenos_start = 2000, $rulenos_range_max = 64500) {
1626 7fb23399 Ermal
	global $config, $g, $cpzone;
1627 6ce61a8f Ermal
1628 aea56408 Ermal
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1629
	$ruleno = 0;
1630
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1631
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1632 1f965b69 Ermal
		$ridx = $rulenos_start;
1633
		while ($ridx < $rulenos_range_max) {
1634 f38b383b Ermal
			if (empty($rules[$ridx])) {
1635 1f965b69 Ermal
				$ruleno = $ridx;
1636
				$rules[$ridx] = $cpzone;
1637 aea56408 Ermal
				$ridx++;
1638 1f965b69 Ermal
				$rules[$ridx] = $cpzone;
1639
				break;
1640 21f82ab6 Ermal
			} else {
1641
				$ridx += 2;
1642 aea56408 Ermal
			}
1643
		}
1644
	} else {
1645 fe3693cb Ermal
		$rules = array_pad(array(), $rulenos_range_max, false);
1646 d2c98878 falbertopl
		$ruleno = $rulenos_start;
1647 7fb23399 Ermal
		$rules[$rulenos_start] = $cpzone;
1648 1f965b69 Ermal
		$rulenos_start++;
1649
		$rules[$rulenos_start] = $cpzone;
1650 aea56408 Ermal
	}
1651
	file_put_contents("{$g['vardb_path']}/captiveportaldn.rules", serialize($rules));
1652
	unlock($cpruleslck);
1653 1f965b69 Ermal
	unset($rules);
1654 aea56408 Ermal
1655
	return $ruleno;
1656
}
1657
1658
function captiveportal_free_dn_ruleno($ruleno) {
1659 87e7fdea bcyrill
	global $config, $g;
1660
1661
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1662
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1663
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1664
		$rules[$ruleno] = false;
1665 a2a42c72 Ermal
		$ruleno++;
1666
		$rules[$ruleno] = false;
1667 87e7fdea bcyrill
		file_put_contents("{$g['vardb_path']}/captiveportaldn.rules", serialize($rules));
1668 1f965b69 Ermal
		unset($rules);
1669 87e7fdea bcyrill
	}
1670
	unlock($cpruleslck);
1671 aea56408 Ermal
}
1672
1673
function captiveportal_get_dn_passthru_ruleno($value) {
1674 baec2b00 Ermal
	global $config, $g, $cpzone, $cpzoneid;
1675 b273dd26 Ermal
1676
	$cpcfg = $config['captiveportal'][$cpzone];
1677 1e0b1727 Phil Davis
	if (!isset($cpcfg['enable'])) {
1678 b273dd26 Ermal
		return NULL;
1679 1e0b1727 Phil Davis
	}
1680 aea56408 Ermal
1681 fe7e987e Ermal
	$cpruleslck = lock("captiveportalrulesdn", LOCK_EX);
1682 1f965b69 Ermal
	$ruleno = NULL;
1683 fe7e987e Ermal
	if (file_exists("{$g['vardb_path']}/captiveportaldn.rules")) {
1684
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportaldn.rules"));
1685 1f965b69 Ermal
		unset($output);
1686 cfa53879 Ermal
		$_gb = exec("/sbin/ipfw -x {$cpzoneid} show | /usr/bin/grep " . escapeshellarg($value) . " | /usr/bin/grep -v grep | /usr/bin/awk '{print $5}' | /usr/bin/head -n 1", $output);
1687 1f965b69 Ermal
		$ruleno = intval($output[0]);
1688 1e0b1727 Phil Davis
		if (!$rules[$ruleno]) {
1689 1f965b69 Ermal
			$ruleno = NULL;
1690 1e0b1727 Phil Davis
		}
1691 1f965b69 Ermal
		unset($rules);
1692 aea56408 Ermal
	}
1693
	unlock($cpruleslck);
1694 1f965b69 Ermal
1695
	return $ruleno;
1696 6ce61a8f Ermal
}
1697
1698 920cafaf Scott Ullrich
/*
1699
 * This function will calculate the lowest free firewall ruleno
1700 f9f71ad3 Ermal Lu?i
 * within the range specified based on the actual logged on users
1701 920cafaf Scott Ullrich
 *
1702
 */
1703 aea56408 Ermal
function captiveportal_get_next_ipfw_ruleno($rulenos_start = 2, $rulenos_range_max = 64500) {
1704 b4792bf8 Ermal
	global $config, $g, $cpzone;
1705 6ce61a8f Ermal
1706 b4792bf8 Ermal
	$cpcfg = $config['captiveportal'][$cpzone];
1707 1e0b1727 Phil Davis
	if (!isset($cpcfg['enable'])) {
1708 01d57b8c Scott Ullrich
		return NULL;
1709 1e0b1727 Phil Davis
	}
1710 6ce61a8f Ermal
1711 b4792bf8 Ermal
	$cpruleslck = lock("captiveportalrules{$cpzone}", LOCK_EX);
1712 f9f71ad3 Ermal Lu?i
	$ruleno = 0;
1713 b4792bf8 Ermal
	if (file_exists("{$g['vardb_path']}/captiveportal_{$cpzone}.rules")) {
1714
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportal_{$cpzone}.rules"));
1715 1f965b69 Ermal
		$ridx = $rulenos_start;
1716
		while ($ridx < $rulenos_range_max) {
1717 21f82ab6 Ermal
			if (empty($rules[$ridx])) {
1718 1f965b69 Ermal
				$ruleno = $ridx;
1719
				$rules[$ridx] = $cpzone;
1720 10b9dfcf Ermal
				$ridx++;
1721 1f965b69 Ermal
				$rules[$ridx] = $cpzone;
1722
				break;
1723 21f82ab6 Ermal
			} else {
1724 1e0b1727 Phil Davis
				/*
1725
				 * This allows our traffic shaping pipes to be the in pipe the same as ruleno
1726 21f82ab6 Ermal
				 * and the out pipe ruleno + 1.
1727
				 */
1728
				$ridx += 2;
1729 6ce61a8f Ermal
			}
1730
		}
1731
	} else {
1732 fe3693cb Ermal
		$rules = array_pad(array(), $rulenos_range_max, false);
1733 1f965b69 Ermal
		$ruleno = $rulenos_start;
1734
		$rules[$rulenos_start] = $cpzone;
1735
		$rulenos_start++;
1736
		$rules[$rulenos_start] = $cpzone;
1737 6ce61a8f Ermal
	}
1738 b4792bf8 Ermal
	file_put_contents("{$g['vardb_path']}/captiveportal_{$cpzone}.rules", serialize($rules));
1739 d31bc32a Ermal
	unlock($cpruleslck);
1740 1f965b69 Ermal
	unset($rules);
1741
1742 6ce61a8f Ermal
	return $ruleno;
1743
}
1744
1745 a413e743 Renato Botelho
function captiveportal_free_ipfw_ruleno($ruleno) {
1746 b4792bf8 Ermal
	global $config, $g, $cpzone;
1747 6ce61a8f Ermal
1748 b4792bf8 Ermal
	$cpcfg = $config['captiveportal'][$cpzone];
1749 1e0b1727 Phil Davis
	if (!isset($cpcfg['enable'])) {
1750 6ce61a8f Ermal
		return NULL;
1751 1e0b1727 Phil Davis
	}
1752 6ce61a8f Ermal
1753 b4792bf8 Ermal
	$cpruleslck = lock("captiveportalrules{$cpzone}", LOCK_EX);
1754
	if (file_exists("{$g['vardb_path']}/captiveportal_{$cpzone}.rules")) {
1755
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportal_{$cpzone}.rules"));
1756 6ce61a8f Ermal
		$rules[$ruleno] = false;
1757 1f965b69 Ermal
		$ruleno++;
1758
		$rules[$ruleno] = false;
1759 b4792bf8 Ermal
		file_put_contents("{$g['vardb_path']}/captiveportal_{$cpzone}.rules", serialize($rules));
1760 1f965b69 Ermal
		unset($rules);
1761 f9f71ad3 Ermal Lu?i
	}
1762 d31bc32a Ermal
	unlock($cpruleslck);
1763 6ce61a8f Ermal
}
1764
1765 d5ae560d Ermal
function captiveportal_get_ipfw_passthru_ruleno($value) {
1766 baec2b00 Ermal
	global $config, $g, $cpzone, $cpzoneid;
1767 6ce61a8f Ermal
1768 b4792bf8 Ermal
	$cpcfg = $config['captiveportal'][$cpzone];
1769 1e0b1727 Phil Davis
	if (!isset($cpcfg['enable'])) {
1770 b4792bf8 Ermal
		return NULL;
1771 1e0b1727 Phil Davis
	}
1772 6ce61a8f Ermal
1773 b4792bf8 Ermal
	$cpruleslck = lock("captiveportalrules{$cpzone}", LOCK_EX);
1774 1f965b69 Ermal
	$ruleno = NULL;
1775 b4792bf8 Ermal
	if (file_exists("{$g['vardb_path']}/captiveportal_{$cpzone}.rules")) {
1776
		$rules = unserialize(file_get_contents("{$g['vardb_path']}/captiveportal_{$cpzone}.rules"));
1777 1f965b69 Ermal
		unset($output);
1778 cfa53879 Ermal
		$_gb = exec("/sbin/ipfw -x {$cpzoneid} show | /usr/bin/grep " . escapeshellarg($value) . " | /usr/bin/grep -v grep | /usr/bin/awk '{print $1}' | /usr/bin/head -n 1", $output);
1779 1f965b69 Ermal
		$ruleno = intval($output[0]);
1780 1e0b1727 Phil Davis
		if (!$rules[$ruleno]) {
1781 1f965b69 Ermal
			$ruleno = NULL;
1782 1e0b1727 Phil Davis
		}
1783 1f965b69 Ermal
		unset($rules);
1784 5060dea7 Scott Ullrich
	}
1785 d31bc32a Ermal
	unlock($cpruleslck);
1786 1f965b69 Ermal
1787
	return $ruleno;
1788 920cafaf Scott Ullrich
}
1789
1790 360d815d Scott Ullrich
/**
1791
 * This function will calculate the traffic produced by a client
1792
 * based on its firewall rule
1793
 *
1794
 * Point of view: NAS
1795
 *
1796
 * Input means: from the client
1797
 * Output means: to the client
1798
 *
1799
 */
1800
1801 fcaf1709 Ermal
function getVolume($ip, $mac = NULL) {
1802 27c2e32e Renato Botelho
	global $config, $cpzone, $cpzoneid;
1803 360d815d Scott Ullrich
1804 f48abba2 Michael Newton
	$reverse = empty($config['captiveportal'][$cpzone]['reverseacct']) ? false : true;
1805 5060dea7 Scott Ullrich
	$volume = array();
1806
	// Initialize vars properly, since we don't want NULL vars
1807
	$volume['input_pkts'] = $volume['input_bytes'] = $volume['output_pkts'] = $volume['output_bytes'] = 0 ;
1808 360d815d Scott Ullrich
1809 b9276845 Ermal LUÇI
	$ipfw = pfSense_ipfw_getTablestats($cpzoneid, IP_FW_TABLE_XLISTENTRY, 1, $ip, $mac);
1810 1272429c Ermal
	if (is_array($ipfw)) {
1811 f48abba2 Michael Newton
		if ($reverse) {
1812
			$volume['output_pkts'] = $ipfw['packets'];
1813
			$volume['output_bytes'] = $ipfw['bytes'];
1814
		}
1815
		else {
1816
			$volume['input_pkts'] = $ipfw['packets'];
1817
			$volume['input_bytes'] = $ipfw['bytes'];
1818
		}
1819 5060dea7 Scott Ullrich
	}
1820 f9f71ad3 Ermal Lu?i
1821 b9276845 Ermal LUÇI
	$ipfw = pfSense_ipfw_getTablestats($cpzoneid, IP_FW_TABLE_XLISTENTRY, 2, $ip, $mac);
1822 1272429c Ermal
	if (is_array($ipfw)) {
1823 f48abba2 Michael Newton
		if ($reverse) {
1824
			$volume['input_pkts'] = $ipfw['packets'];
1825
			$volume['input_bytes'] = $ipfw['bytes'];
1826
		}
1827
		else {
1828
			$volume['output_pkts'] = $ipfw['packets'];
1829
			$volume['output_bytes'] = $ipfw['bytes'];
1830
		}
1831 5060dea7 Scott Ullrich
	}
1832 360d815d Scott Ullrich
1833 5060dea7 Scott Ullrich
	return $volume;
1834 360d815d Scott Ullrich
}
1835
1836 856e58a6 Scott Ullrich
/**
1837
 * Get the NAS-IP-Address based on the current wan address
1838
 *
1839
 * Use functions in interfaces.inc to find this out
1840
 *
1841
 */
1842
1843 086cf944 Phil Davis
function getNasIP() {
1844 b4792bf8 Ermal
	global $config, $cpzone;
1845 64c0462b Ermal
1846 b4792bf8 Ermal
	if (empty($config['captiveportal'][$cpzone]['radiussrcip_attribute'])) {
1847 5060dea7 Scott Ullrich
			$nasIp = get_interface_ip();
1848
	} else {
1849 1e0b1727 Phil Davis
		if (is_ipaddr($config['captiveportal'][$cpzone]['radiussrcip_attribute'])) {
1850 b4792bf8 Ermal
			$nasIp = $config['captiveportal'][$cpzone]['radiussrcip_attribute'];
1851 1e0b1727 Phil Davis
		} else {
1852 b4792bf8 Ermal
			$nasIp = get_interface_ip($config['captiveportal'][$cpzone]['radiussrcip_attribute']);
1853 1e0b1727 Phil Davis
		}
1854 36ff7f81 Ermal
	}
1855 1e0b1727 Phil Davis
1856
	if (!is_ipaddr($nasIp)) {
1857 5060dea7 Scott Ullrich
		$nasIp = "0.0.0.0";
1858 1e0b1727 Phil Davis
	}
1859 64c0462b Ermal
1860
	return $nasIp;
1861 856e58a6 Scott Ullrich
}
1862
1863 f8b11310 Ermal Lu?i
function portal_ip_from_client_ip($cliip) {
1864 b4792bf8 Ermal
	global $config, $cpzone;
1865 f8b11310 Ermal Lu?i
1866 45bef774 bcyrill
	$isipv6 = is_ipaddrv6($cliip);
1867 b4792bf8 Ermal
	$interfaces = explode(",", $config['captiveportal'][$cpzone]['interface']);
1868 f8b11310 Ermal Lu?i
	foreach ($interfaces as $cpif) {
1869 45bef774 bcyrill
		if ($isipv6) {
1870
			$ip = get_interface_ipv6($cpif);
1871
			$sn = get_interface_subnetv6($cpif);
1872
		} else {
1873
			$ip = get_interface_ip($cpif);
1874
			$sn = get_interface_subnet($cpif);
1875
		}
1876 1e0b1727 Phil Davis
		if (ip_in_subnet($cliip, "{$ip}/{$sn}")) {
1877 f8b11310 Ermal Lu?i
			return $ip;
1878 1e0b1727 Phil Davis
		}
1879 f8b11310 Ermal Lu?i
	}
1880
1881 45bef774 bcyrill
	$inet = ($isipv6) ? '-inet6' : '-inet';
1882
	$iface = exec_command("/sbin/route -n get {$inet} {$cliip} | /usr/bin/awk '/interface/ { print \$2; };'");
1883 f86fa91c jim-p
	$iface = trim($iface, "\n");
1884
	if (!empty($iface)) {
1885 45bef774 bcyrill
		$ip = ($isipv6) ? find_interface_ipv6($iface) : find_interface_ip($iface);
1886 1e0b1727 Phil Davis
		if (is_ipaddr($ip)) {
1887 f86fa91c jim-p
			return $ip;
1888 1e0b1727 Phil Davis
		}
1889 f86fa91c jim-p
	}
1890
1891 cc125e13 Chris Buechler
	// doesn't match up to any particular interface
1892 1e0b1727 Phil Davis
	// so let's set the portal IP to what PHP says
1893
	// the server IP issuing the request is.
1894
	// allows same behavior as 1.2.x where IP isn't
1895 cc125e13 Chris Buechler
	// in the subnet of any CP interface (static routes, etc.)
1896
	// rather than forcing to DNS hostname resolution
1897
	$ip = $_SERVER['SERVER_ADDR'];
1898 1e0b1727 Phil Davis
	if (is_ipaddr($ip)) {
1899 cc125e13 Chris Buechler
		return $ip;
1900 1e0b1727 Phil Davis
	}
1901 cc125e13 Chris Buechler
1902 f8b11310 Ermal Lu?i
	return false;
1903
}
1904
1905 de132ae3 bcyrill
function portal_hostname_from_client_ip($cliip) {
1906
	global $config, $cpzone;
1907
1908
	$cpcfg = $config['captiveportal'][$cpzone];
1909
1910
	if (isset($cpcfg['httpslogin'])) {
1911 4320083f Renato Botelho
		$listenporthttps = $cpcfg['listenporthttps'] ? $cpcfg['listenporthttps'] : ($cpcfg['zoneid'] + 8001);
1912 de132ae3 bcyrill
		$ourhostname = $cpcfg['httpsname'];
1913 1e0b1727 Phil Davis
1914
		if ($listenporthttps != 443) {
1915 de132ae3 bcyrill
			$ourhostname .= ":" . $listenporthttps;
1916 1e0b1727 Phil Davis
		}
1917 de132ae3 bcyrill
	} else {
1918 6c07db48 Phil Davis
		$listenporthttp = $cpcfg['listenporthttp'] ? $cpcfg['listenporthttp'] : ($cpcfg['zoneid'] + 8000);
1919 de132ae3 bcyrill
		$ifip = portal_ip_from_client_ip($cliip);
1920 1e0b1727 Phil Davis
		if (!$ifip) {
1921 de132ae3 bcyrill
			$ourhostname = "{$config['system']['hostname']}.{$config['system']['domain']}";
1922 1e0b1727 Phil Davis
		} else {
1923 de132ae3 bcyrill
			$ourhostname = (is_ipaddrv6($ifip)) ? "[{$ifip}]" : "{$ifip}";
1924 1e0b1727 Phil Davis
		}
1925
1926
		if ($listenporthttp != 80) {
1927 de132ae3 bcyrill
			$ourhostname .= ":" . $listenporthttp;
1928 1e0b1727 Phil Davis
		}
1929 de132ae3 bcyrill
	}
1930 1e0b1727 Phil Davis
1931 d5ac388b bcyrill
	return $ourhostname;
1932 de132ae3 bcyrill
}
1933
1934 ac631bba lgcosta
/* functions move from index.php */
1935
1936
function portal_reply_page($redirurl, $type = null, $message = null, $clientmac = null, $clientip = null, $username = null, $password = null) {
1937 b4792bf8 Ermal
	global $g, $config, $cpzone;
1938 ac631bba lgcosta
1939
	/* Get captive portal layout */
1940
	if ($type == "redir") {
1941
		header("Location: {$redirurl}");
1942
		return;
1943 1e0b1727 Phil Davis
	} else if ($type == "login") {
1944 b4792bf8 Ermal
		$htmltext = get_include_contents("{$g['varetc_path']}/captiveportal_{$cpzone}.html");
1945 1e0b1727 Phil Davis
	} else {
1946 b4792bf8 Ermal
		$htmltext = get_include_contents("{$g['varetc_path']}/captiveportal-{$cpzone}-error.html");
1947 1e0b1727 Phil Davis
	}
1948 b4792bf8 Ermal
1949
	$cpcfg = $config['captiveportal'][$cpzone];
1950 ac631bba lgcosta
1951
	/* substitute the PORTAL_REDIRURL variable */
1952 de132ae3 bcyrill
	if ($cpcfg['preauthurl']) {
1953
		$htmltext = str_replace("\$PORTAL_REDIRURL\$", "{$cpcfg['preauthurl']}", $htmltext);
1954
		$htmltext = str_replace("#PORTAL_REDIRURL#", "{$cpcfg['preauthurl']}", $htmltext);
1955 ac631bba lgcosta
	}
1956
1957
	/* substitute other variables */
1958 de132ae3 bcyrill
	$ourhostname = portal_hostname_from_client_ip($clientip);
1959
	$protocol = (isset($cpcfg['httpslogin'])) ? 'https://' : 'http://';
1960 26c7100b Renato Botelho
	$htmltext = str_replace("\$PORTAL_ACTION\$", "{$protocol}{$ourhostname}/index.php?zone={$cpzone}", $htmltext);
1961
	$htmltext = str_replace("#PORTAL_ACTION#", "{$protocol}{$ourhostname}/index.php?zone={$cpzone}", $htmltext);
1962 ac631bba lgcosta
1963 b4792bf8 Ermal
	$htmltext = str_replace("\$PORTAL_ZONE\$", htmlspecialchars($cpzone), $htmltext);
1964 ac631bba lgcosta
	$htmltext = str_replace("\$PORTAL_REDIRURL\$", htmlspecialchars($redirurl), $htmltext);
1965
	$htmltext = str_replace("\$PORTAL_MESSAGE\$", htmlspecialchars($message), $htmltext);
1966
	$htmltext = str_replace("\$CLIENT_MAC\$", htmlspecialchars($clientmac), $htmltext);
1967
	$htmltext = str_replace("\$CLIENT_IP\$", htmlspecialchars($clientip), $htmltext);
1968
1969 1e0b1727 Phil Davis
	// Special handling case for captive portal master page so that it can be ran
1970 ac631bba lgcosta
	// through the PHP interpreter using the include method above.  We convert the
1971
	// $VARIABLE$ case to #VARIABLE# in /etc/inc/captiveportal.inc before writing out.
1972 b4792bf8 Ermal
	$htmltext = str_replace("#PORTAL_ZONE#", htmlspecialchars($cpzone), $htmltext);
1973 ac631bba lgcosta
	$htmltext = str_replace("#PORTAL_REDIRURL#", htmlspecialchars($redirurl), $htmltext);
1974
	$htmltext = str_replace("#PORTAL_MESSAGE#", htmlspecialchars($message), $htmltext);
1975
	$htmltext = str_replace("#CLIENT_MAC#", htmlspecialchars($clientmac), $htmltext);
1976
	$htmltext = str_replace("#CLIENT_IP#", htmlspecialchars($clientip), $htmltext);
1977
	$htmltext = str_replace("#USERNAME#", htmlspecialchars($username), $htmltext);
1978
	$htmltext = str_replace("#PASSWORD#", htmlspecialchars($password), $htmltext);
1979
1980 87e7fdea bcyrill
	echo $htmltext;
1981 ac631bba lgcosta
}
1982
1983 086cf944 Phil Davis
function portal_mac_radius($clientmac, $clientip) {
1984 87e7fdea bcyrill
	global $config, $cpzone;
1985 ac631bba lgcosta
1986 87e7fdea bcyrill
	$radmac_secret = $config['captiveportal'][$cpzone]['radmac_secret'];
1987 ac631bba lgcosta
1988 87e7fdea bcyrill
	/* authentication against the radius server */
1989
	$username = mac_format($clientmac);
1990 086cf944 Phil Davis
	$auth_list = radius($username, $radmac_secret, $clientip, $clientmac, "MACHINE LOGIN");
1991 1e0b1727 Phil Davis
	if ($auth_list['auth_val'] == 2) {
1992 87e7fdea bcyrill
		return TRUE;
1993 1e0b1727 Phil Davis
	}
1994 ac631bba lgcosta
1995 1e0b1727 Phil Davis
	if (!empty($auth_list['url_redirection'])) {
1996 87e7fdea bcyrill
		portal_reply_page($auth_list['url_redirection'], "redir");
1997 1e0b1727 Phil Davis
	}
1998 87e7fdea bcyrill
1999
	return FALSE;
2000 ac631bba lgcosta
}
2001
2002 aec0f2fd Ermal
function captiveportal_reapply_attributes($cpentry, $attributes) {
2003 2ec063f9 Warren Baker
	global $config, $cpzone, $g;
2004 87e7fdea bcyrill
2005 ce90c89a Ermal LUÇI
	if (isset($config['captiveportal'][$cpzone]['peruserbw'])) {
2006 384deecb Ermal LUÇI
		$dwfaultbw_up = !empty($config['captiveportal'][$cpzone]['bwdefaultup']) ? $config['captiveportal'][$cpzone]['bwdefaultup'] : 0;
2007
		$dwfaultbw_down = !empty($config['captiveportal'][$cpzone]['bwdefaultdn']) ? $config['captiveportal'][$cpzone]['bwdefaultdn'] : 0;
2008 1e0b1727 Phil Davis
	} else {
2009 ce90c89a Ermal LUÇI
		$dwfaultbw_up = $dwfaultbw_down = 0;
2010 1e0b1727 Phil Davis
	}
2011 384deecb Ermal LUÇI
	$bw_up = !empty($attributes['bw_up']) ? round(intval($attributes['bw_up'])/1000, 2) : $dwfaultbw_up;
2012
	$bw_down = !empty($attributes['bw_down']) ? round(intval($attributes['bw_down'])/1000, 2) : $dwfaultbw_down;
2013 5705c60a Renato Botelho
	$bw_up_pipeno = $cpentry[1];
2014
	$bw_down_pipeno = $cpentry[1]+1;
2015 aec0f2fd Ermal
2016 c2e2d133 Ermal
	$_gb = @pfSense_pipe_action("pipe {$bw_up_pipeno} config bw {$bw_up}Kbit/s queue 100 buckets 16");
2017
	$_gb = @pfSense_pipe_action("pipe {$bw_down_pipeno} config bw {$bw_down}Kbit/s queue 100 buckets 16");
2018 10b9dfcf Ermal
	//captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "RADIUS_BANDWIDTH_REAPPLY", "{$bw_up}/{$bw_down}");
2019 aec0f2fd Ermal
2020 87e7fdea bcyrill
	unset($bw_up_pipeno, $bw_down_pipeno, $bw_up, $bw_down);
2021 aec0f2fd Ermal
}
2022
2023 6c07db48 Phil Davis
function portal_allow($clientip, $clientmac, $username, $password = null, $attributes = null, $pipeno = null, $radiusctx = null) {
2024 baec2b00 Ermal
	global $redirurl, $g, $config, $type, $passthrumac, $_POST, $cpzone, $cpzoneid;
2025 ac631bba lgcosta
2026
	// Ensure we create an array if we are missing attributes
2027 1e0b1727 Phil Davis
	if (!is_array($attributes)) {
2028 ac631bba lgcosta
		$attributes = array();
2029 1e0b1727 Phil Davis
	}
2030 ac631bba lgcosta
2031 26ee5aaf Ermal
	unset($sessionid);
2032 ac631bba lgcosta
2033 006802ab Ermal
	/* Do not allow concurrent login execution. */
2034 b4792bf8 Ermal
	$cpdblck = lock("captiveportaldb{$cpzone}", LOCK_EX);
2035 006802ab Ermal
2036 1e0b1727 Phil Davis
	if ($attributes['voucher']) {
2037 ac631bba lgcosta
		$remaining_time = $attributes['session_timeout'];
2038 6fe72c1c fischeol
	// Set RADIUS-Attribute to Voucher to prevent ReAuth-Reqeuest for Vouchers Bug: #2155
2039
		$radiusctx="voucher";
2040 1e0b1727 Phil Davis
	}
2041 ac631bba lgcosta
2042
	$writecfg = false;
2043
	/* Find an existing session */
2044 b4792bf8 Ermal
	if ((isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) && $passthrumac) {
2045
		if (isset($config['captiveportal'][$cpzone]['passthrumacadd'])) {
2046 ac631bba lgcosta
			$mac = captiveportal_passthrumac_findbyname($username);
2047
			if (!empty($mac)) {
2048
				if ($_POST['replacemacpassthru']) {
2049 b4792bf8 Ermal
					foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $idx => $macent) {
2050 ac631bba lgcosta
						if ($macent['mac'] == $mac['mac']) {
2051
							$macrules = "";
2052
							$ruleno = captiveportal_get_ipfw_passthru_ruleno($mac['mac']);
2053 aea56408 Ermal
							$pipeno = captiveportal_get_dn_passthru_ruleno($mac['mac']);
2054 87e7fdea bcyrill
							if ($ruleno) {
2055 aea56408 Ermal
								captiveportal_free_ipfw_ruleno($ruleno);
2056 87e7fdea bcyrill
								$macrules .= "delete {$ruleno}\n";
2057 ac631bba lgcosta
								++$ruleno;
2058 87e7fdea bcyrill
								$macrules .= "delete {$ruleno}\n";
2059
							}
2060 aea56408 Ermal
							if ($pipeno) {
2061
								captiveportal_free_dn_ruleno($pipeno);
2062 87e7fdea bcyrill
								$macrules .= "pipe delete {$pipeno}\n";
2063 aea56408 Ermal
								++$pipeno;
2064 87e7fdea bcyrill
								$macrules .= "pipe delete {$pipeno}\n";
2065 aea56408 Ermal
							}
2066 b4792bf8 Ermal
							unset($config['captiveportal'][$cpzone]['passthrumac'][$idx]);
2067 6b1cb3fd Renato Botelho
							$mac['action'] = 'pass';
2068 ac631bba lgcosta
							$mac['mac'] = $clientmac;
2069 b4792bf8 Ermal
							$config['captiveportal'][$cpzone]['passthrumac'][] = $mac;
2070 ac631bba lgcosta
							$macrules .= captiveportal_passthrumac_configure_entry($mac);
2071 b4792bf8 Ermal
							file_put_contents("{$g['tmp_path']}/macentry_{$cpzone}.rules.tmp", $macrules);
2072 baec2b00 Ermal
							mwexec("/sbin/ipfw -x {$cpzoneid} -q {$g['tmp_path']}/macentry_{$cpzone}.rules.tmp");
2073 ac631bba lgcosta
							$writecfg = true;
2074
							$sessionid = true;
2075
							break;
2076
						}
2077
					}
2078 87e7fdea bcyrill
				} else {
2079 ac631bba lgcosta
					portal_reply_page($redirurl, "error", "Username: {$username} is already authenticated using another MAC address.",
2080
						$clientmac, $clientip, $username, $password);
2081 ee79fcda Ermal
					unlock($cpdblck);
2082 aea56408 Ermal
					return;
2083 ac631bba lgcosta
				}
2084
			}
2085
		}
2086
	}
2087
2088 26ee5aaf Ermal
	/* read in client database */
2089
	$query = "WHERE ip = '{$clientip}'";
2090 ab2f9684 Phil Davis
	$tmpusername = SQLite3::escapeString(strtolower($username));
2091 1e0b1727 Phil Davis
	if (isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) {
2092 26ee5aaf Ermal
		$query .= " OR (username != 'unauthenticated' AND lower(username) = '{$tmpusername}')";
2093 1e0b1727 Phil Davis
	}
2094 26ee5aaf Ermal
	$cpdb = captiveportal_read_db($query);
2095
2096 ebc0e4b6 Ermal
	/* Snapshot the timestamp */
2097 b09c2d86 Ermal
	$allow_time = time();
2098 26ee5aaf Ermal
	$radiusservers = captiveportal_get_radius_servers();
2099
	$unsetindexes = array();
2100 1e0b1727 Phil Davis
	if (is_null($radiusctx)) {
2101 ebc0e4b6 Ermal
		$radiusctx = 'first';
2102 1e0b1727 Phil Davis
	}
2103 26ee5aaf Ermal
2104
	foreach ($cpdb as $cpentry) {
2105 74a40221 Ermal
		if (empty($cpentry[11])) {
2106
			$cpentry[11] = 'first';
2107
		}
2108 ac631bba lgcosta
		/* on the same ip */
2109 5705c60a Renato Botelho
		if ($cpentry[2] == $clientip) {
2110 1e0b1727 Phil Davis
			if (isset($config['captiveportal'][$cpzone]['nomacfilter']) || $cpentry[3] == $clientmac) {
2111 086cf944 Phil Davis
				captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - REUSING OLD SESSION");
2112 1e0b1727 Phil Davis
			} else {
2113 086cf944 Phil Davis
				captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - REUSING IP {$cpentry[2]} WITH DIFFERENT MAC ADDRESS {$cpentry[3]}");
2114 1e0b1727 Phil Davis
			}
2115 5705c60a Renato Botelho
			$sessionid = $cpentry[5];
2116 ac631bba lgcosta
			break;
2117 1e0b1727 Phil Davis
		} elseif (($attributes['voucher']) && ($username != 'unauthenticated') && ($cpentry[4] == $username)) {
2118
			// user logged in with an active voucher. Check for how long and calculate
2119 ac631bba lgcosta
			// how much time we can give him (voucher credit - used time)
2120 5705c60a Renato Botelho
			$remaining_time = $cpentry[0] + $cpentry[7] - $allow_time;
2121 1e0b1727 Phil Davis
			if ($remaining_time < 0) { // just in case.
2122 ac631bba lgcosta
				$remaining_time = 0;
2123 1e0b1727 Phil Davis
			}
2124 ac631bba lgcosta
2125
			/* This user was already logged in so we disconnect the old one */
2126 086cf944 Phil Davis
			captiveportal_disconnect($cpentry, $radiusservers[$cpentry[11]], 13);
2127
			captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - TERMINATING OLD SESSION");
2128 5705c60a Renato Botelho
			$unsetindexes[] = $cpentry[5];
2129 ac631bba lgcosta
			break;
2130 1e0b1727 Phil Davis
		} elseif ((isset($config['captiveportal'][$cpzone]['noconcurrentlogins'])) && ($username != 'unauthenticated')) {
2131 ac631bba lgcosta
			/* on the same username */
2132 5705c60a Renato Botelho
			if (strcasecmp($cpentry[4], $username) == 0) {
2133 ac631bba lgcosta
				/* This user was already logged in so we disconnect the old one */
2134 086cf944 Phil Davis
				captiveportal_disconnect($cpentry, $radiusservers[$cpentry[11]], 13);
2135
				captiveportal_logportalauth($cpentry[4], $cpentry[3], $cpentry[2], "CONCURRENT LOGIN - TERMINATING OLD SESSION");
2136 5705c60a Renato Botelho
				$unsetindexes[] = $cpentry[5];
2137 ac631bba lgcosta
				break;
2138
			}
2139
		}
2140
	}
2141 f32eae2d Ermal
	unset($cpdb);
2142 ac631bba lgcosta
2143 1e0b1727 Phil Davis
	if (!empty($unsetindexes)) {
2144 26ee5aaf Ermal
		captiveportal_remove_entries($unsetindexes);
2145 1e0b1727 Phil Davis
	}
2146 26ee5aaf Ermal
2147 1e0b1727 Phil Davis
	if ($attributes['voucher'] && $remaining_time <= 0) {
2148 ac631bba lgcosta
		return 0;       // voucher already used and no time left
2149 1e0b1727 Phil Davis
	}
2150 ac631bba lgcosta
2151
	if (!isset($sessionid)) {
2152
		/* generate unique session ID */
2153
		$tod = gettimeofday();
2154
		$sessionid = substr(md5(mt_rand() . $tod['sec'] . $tod['usec'] . $clientip . $clientmac), 0, 16);
2155
2156
		if ($passthrumac) {
2157
			$mac = array();
2158 6ffb064f Renato Botelho
			$mac['action'] = 'pass';
2159 ac631bba lgcosta
			$mac['mac'] = $clientmac;
2160 522f1cc7 Ermal
			$mac['ip'] = $clientip; /* Used only for logging */
2161
			if (isset($config['captiveportal'][$cpzone]['passthrumacaddusername'])) {
2162 ac631bba lgcosta
				$mac['username'] = $username;
2163 1e0b1727 Phil Davis
				if ($attributes['voucher']) {
2164 522f1cc7 Ermal
					$mac['logintype'] = "voucher";
2165 1e0b1727 Phil Davis
				}
2166 522f1cc7 Ermal
			}
2167 cc229ee9 Phil Davis
			if ($username == "unauthenticated") {
2168 6c07db48 Phil Davis
				$mac['descr'] = "Auto-added";
2169 1e0b1727 Phil Davis
			} else {
2170 6c07db48 Phil Davis
				$mac['descr'] = "Auto-added for user {$username}";
2171 1e0b1727 Phil Davis
			}
2172
			if (!empty($bw_up)) {
2173 ac631bba lgcosta
				$mac['bw_up'] = $bw_up;
2174 1e0b1727 Phil Davis
			}
2175
			if (!empty($bw_down)) {
2176 ac631bba lgcosta
				$mac['bw_down'] = $bw_down;
2177 1e0b1727 Phil Davis
			}
2178
			if (!is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
2179 b4792bf8 Ermal
				$config['captiveportal'][$cpzone]['passthrumac'] = array();
2180 1e0b1727 Phil Davis
			}
2181 b4792bf8 Ermal
			$config['captiveportal'][$cpzone]['passthrumac'][] = $mac;
2182 006802ab Ermal
			unlock($cpdblck);
2183 ac631bba lgcosta
			$macrules = captiveportal_passthrumac_configure_entry($mac);
2184 b4792bf8 Ermal
			file_put_contents("{$g['tmp_path']}/macentry_{$cpzone}.rules.tmp", $macrules);
2185 baec2b00 Ermal
			mwexec("/sbin/ipfw -x {$cpzoneid} -q {$g['tmp_path']}/macentry_{$cpzone}.rules.tmp");
2186 ac631bba lgcosta
			$writecfg = true;
2187
		} else {
2188 aea56408 Ermal
			/* See if a pipeno is passed, if not start sessions because this means there isn't one atm */
2189 1e0b1727 Phil Davis
			if (is_null($pipeno)) {
2190 aea56408 Ermal
				$pipeno = captiveportal_get_next_dn_ruleno();
2191 1e0b1727 Phil Davis
			}
2192 aea56408 Ermal
2193
			/* if the pool is empty, return appropriate message and exit */
2194
			if (is_null($pipeno)) {
2195
				portal_reply_page($redirurl, "error", "System reached maximum login capacity");
2196 12feed15 Ermal
				log_error("Zone: {$cpzone} - WARNING!  Captive portal has reached maximum login capacity");
2197 aea56408 Ermal
				unlock($cpdblck);
2198
				return;
2199
			}
2200
2201 ce90c89a Ermal LUÇI
			if (isset($config['captiveportal'][$cpzone]['peruserbw'])) {
2202 384deecb Ermal LUÇI
				$dwfaultbw_up = !empty($config['captiveportal'][$cpzone]['bwdefaultup']) ? $config['captiveportal'][$cpzone]['bwdefaultup'] : 0;
2203
				$dwfaultbw_down = !empty($config['captiveportal'][$cpzone]['bwdefaultdn']) ? $config['captiveportal'][$cpzone]['bwdefaultdn'] : 0;
2204 1e0b1727 Phil Davis
			} else {
2205 ce90c89a Ermal LUÇI
				$dwfaultbw_up = $dwfaultbw_down = 0;
2206 1e0b1727 Phil Davis
			}
2207 384deecb Ermal LUÇI
			$bw_up = !empty($attributes['bw_up']) ? round(intval($attributes['bw_up'])/1000, 2) : $dwfaultbw_up;
2208
			$bw_down = !empty($attributes['bw_down']) ? round(intval($attributes['bw_down'])/1000, 2) : $dwfaultbw_down;
2209 553abb0d Ermal
2210 aea56408 Ermal
			$bw_up_pipeno = $pipeno;
2211
			$bw_down_pipeno = $pipeno + 1;
2212 10b9dfcf Ermal
			//$bw_up /= 1000; // Scale to Kbit/s
2213 c2e2d133 Ermal
			$_gb = @pfSense_pipe_action("pipe {$bw_up_pipeno} config bw {$bw_up}Kbit/s queue 100 buckets 16");
2214
			$_gb = @pfSense_pipe_action("pipe {$bw_down_pipeno} config bw {$bw_down}Kbit/s queue 100 buckets 16");
2215 ac631bba lgcosta
2216 60884727 bcyrill
			$clientsn = (is_ipaddrv6($clientip)) ? 128 : 32;
2217 1e0b1727 Phil Davis
			if (!isset($config['captiveportal'][$cpzone]['nomacfilter'])) {
2218 cbe38717 Ermal
				$_gb = @pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XADD, 1, $clientip, $clientsn, $clientmac, $bw_up_pipeno);
2219 1e0b1727 Phil Davis
			} else {
2220 cbe38717 Ermal
				$_gb = @pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XADD, 1, $clientip, $clientsn, NULL, $bw_up_pipeno);
2221 1e0b1727 Phil Davis
			}
2222 10b9dfcf Ermal
2223 1e0b1727 Phil Davis
			if (!isset($config['captiveportal'][$cpzone]['nomacfilter'])) {
2224 cbe38717 Ermal
				$_gb = @pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XADD, 2, $clientip, $clientsn, $clientmac, $bw_down_pipeno);
2225 1e0b1727 Phil Davis
			} else {
2226 cbe38717 Ermal
				$_gb = @pfSense_ipfw_Tableaction($cpzoneid, IP_FW_TABLE_XADD, 2, $clientip, $clientsn, NULL, $bw_down_pipeno);
2227 1e0b1727 Phil Davis
			}
2228 ac631bba lgcosta
2229 1e0b1727 Phil Davis
			if ($attributes['voucher']) {
2230 ac631bba lgcosta
				$attributes['session_timeout'] = $remaining_time;
2231 1e0b1727 Phil Davis
			}
2232
2233 1974c2d6 bcyrill
			/* handle empty attributes */
2234
			$session_timeout = (!empty($attributes['session_timeout'])) ? $attributes['session_timeout'] : 'NULL';
2235
			$idle_timeout = (!empty($attributes['idle_timeout'])) ? $attributes['idle_timeout'] : 'NULL';
2236
			$session_terminate_time = (!empty($attributes['session_terminate_time'])) ? $attributes['session_terminate_time'] : 'NULL';
2237 338c0941 Ermal
			$interim_interval = (!empty($attributes['interim_interval'])) ? $attributes['interim_interval'] : 'NULL';
2238 1974c2d6 bcyrill
2239
			/* escape username */
2240 5cf91315 Renato Botelho
			$safe_username = SQLite3::escapeString($username);
2241 ac631bba lgcosta
2242
			/* encode password in Base64 just in case it contains commas */
2243
			$bpassword = base64_encode($password);
2244 6c07db48 Phil Davis
			$insertquery = "INSERT INTO captiveportal (allow_time, pipeno, ip, mac, username, sessionid, bpassword, session_timeout, idle_timeout, session_terminate_time, interim_interval, radiusctx) ";
2245 1974c2d6 bcyrill
			$insertquery .= "VALUES ({$allow_time}, {$pipeno}, '{$clientip}', '{$clientmac}', '{$safe_username}', '{$sessionid}', '{$bpassword}', ";
2246 ac420abd Ermal
			$insertquery .= "{$session_timeout}, {$idle_timeout}, {$session_terminate_time}, {$interim_interval}, '{$radiusctx}')";
2247 ac631bba lgcosta
2248 26ee5aaf Ermal
			/* store information to database */
2249
			captiveportal_write_db($insertquery);
2250 006802ab Ermal
			unlock($cpdblck);
2251 1f965b69 Ermal
			unset($insertquery, $bpassword);
2252 006802ab Ermal
2253 ebc0e4b6 Ermal
			if (isset($config['captiveportal'][$cpzone]['radacct_enable']) && !empty($radiusservers[$radiusctx])) {
2254 87e7fdea bcyrill
				$acct_val = RADIUS_ACCOUNTING_START($pipeno, $username, $sessionid, $radiusservers[$radiusctx], $clientip, $clientmac);
2255 1e0b1727 Phil Davis
				if ($acct_val == 1) {
2256 086cf944 Phil Davis
					captiveportal_logportalauth($username, $clientmac, $clientip, $type, "RADIUS ACCOUNTING FAILED");
2257 1e0b1727 Phil Davis
				}
2258 ac631bba lgcosta
			}
2259
		}
2260 a7ee038b Ermal
	} else {
2261
		/* NOTE: #3062-11 If the pipeno has been allocated free it to not DoS the CP and maintain proper operation as in radius() case */
2262 1e0b1727 Phil Davis
		if (!is_null($pipeno)) {
2263 a7ee038b Ermal
			captiveportal_free_dn_ruleno($pipeno);
2264 1e0b1727 Phil Davis
		}
2265 a7ee038b Ermal
2266 006802ab Ermal
		unlock($cpdblck);
2267 a7ee038b Ermal
	}
2268 ac631bba lgcosta
2269 1e0b1727 Phil Davis
	if ($writecfg == true) {
2270 ac631bba lgcosta
		write_config();
2271 1e0b1727 Phil Davis
	}
2272 ac631bba lgcosta
2273
	/* redirect user to desired destination */
2274 1e0b1727 Phil Davis
	if (!empty($attributes['url_redirection'])) {
2275 ac631bba lgcosta
		$my_redirurl = $attributes['url_redirection'];
2276 1e0b1727 Phil Davis
	} else if (!empty($redirurl)) {
2277 ac420abd Ermal
		$my_redirurl = $redirurl;
2278 1e0b1727 Phil Davis
	} else if (!empty($config['captiveportal'][$cpzone]['redirurl'])) {
2279 b4792bf8 Ermal
		$my_redirurl = $config['captiveportal'][$cpzone]['redirurl'];
2280 1e0b1727 Phil Davis
	}
2281 ac631bba lgcosta
2282 1e0b1727 Phil Davis
	if (isset($config['captiveportal'][$cpzone]['logoutwin_enable']) && !$passthrumac) {
2283 de132ae3 bcyrill
		$ourhostname = portal_hostname_from_client_ip($clientip);
2284
		$protocol = (isset($config['captiveportal'][$cpzone]['httpslogin'])) ? 'https://' : 'http://';
2285
		$logouturl = "{$protocol}{$ourhostname}/";
2286 ac631bba lgcosta
2287 1e0b1727 Phil Davis
		if (isset($attributes['reply_message'])) {
2288 ac631bba lgcosta
			$message = $attributes['reply_message'];
2289 1e0b1727 Phil Davis
		} else {
2290 ac631bba lgcosta
			$message = 0;
2291 1e0b1727 Phil Davis
		}
2292 ac631bba lgcosta
2293 6dfb6b27 Phil Davis
		include_once("{$g['varetc_path']}/captiveportal-{$cpzone}-logout.html");
2294 ac631bba lgcosta
2295
	} else {
2296 fb0c2bd6 Ermal
		portal_reply_page($my_redirurl, "redir", "Just redirect the user.");
2297 ac631bba lgcosta
	}
2298
2299
	return $sessionid;
2300
}
2301
2302
2303
/*
2304
 * Used for when pass-through credits are enabled.
2305
 * Returns true when there was at least one free login to deduct for the MAC.
2306
 * Expired entries are removed as they are seen.
2307
 * Active entries are updated according to the configuration.
2308
 */
2309
function portal_consume_passthrough_credit($clientmac) {
2310 b4792bf8 Ermal
	global $config, $cpzone;
2311 ac631bba lgcosta
2312 1e0b1727 Phil Davis
	if (!empty($config['captiveportal'][$cpzone]['freelogins_count']) && is_numeric($config['captiveportal'][$cpzone]['freelogins_count'])) {
2313 b4792bf8 Ermal
		$freeloginscount = $config['captiveportal'][$cpzone]['freelogins_count'];
2314 1e0b1727 Phil Davis
	} else {
2315 ac631bba lgcosta
		return false;
2316 1e0b1727 Phil Davis
	}
2317 ac631bba lgcosta
2318 1e0b1727 Phil Davis
	if (!empty($config['captiveportal'][$cpzone]['freelogins_resettimeout']) && is_numeric($config['captiveportal'][$cpzone]['freelogins_resettimeout'])) {
2319 b4792bf8 Ermal
		$resettimeout = $config['captiveportal'][$cpzone]['freelogins_resettimeout'];
2320 1e0b1727 Phil Davis
	} else {
2321 ac631bba lgcosta
		return false;
2322 1e0b1727 Phil Davis
	}
2323 ac631bba lgcosta
2324 1e0b1727 Phil Davis
	if ($freeloginscount < 1 || $resettimeout <= 0 || !$clientmac) {
2325 ac631bba lgcosta
		return false;
2326 1e0b1727 Phil Davis
	}
2327 ac631bba lgcosta
2328 b4792bf8 Ermal
	$updatetimeouts = isset($config['captiveportal'][$cpzone]['freelogins_updatetimeouts']);
2329 ac631bba lgcosta
2330
	/*
2331
	 * Read database of used MACs.  Lines are a comma-separated list
2332
	 * of the time, MAC, then the count of pass-through credits remaining.
2333
	 */
2334
	$usedmacs = captiveportal_read_usedmacs_db();
2335
2336
	$currenttime = time();
2337
	$found = false;
2338
	foreach ($usedmacs as $key => $usedmac) {
2339
		$usedmac = explode(",", $usedmac);
2340
2341
		if ($usedmac[1] == $clientmac) {
2342
			if ($usedmac[0] + ($resettimeout * 3600) > $currenttime) {
2343
				if ($usedmac[2] < 1) {
2344
					if ($updatetimeouts) {
2345
						$usedmac[0] = $currenttime;
2346
						unset($usedmacs[$key]);
2347
						$usedmacs[] = implode(",", $usedmac);
2348
						captiveportal_write_usedmacs_db($usedmacs);
2349
					}
2350
2351
					return false;
2352
				} else {
2353
					$usedmac[2] -= 1;
2354
					$usedmacs[$key] = implode(",", $usedmac);
2355
				}
2356
2357
				$found = true;
2358 1e0b1727 Phil Davis
			} else {
2359 ac631bba lgcosta
				unset($usedmacs[$key]);
2360 1e0b1727 Phil Davis
			}
2361 ac631bba lgcosta
2362
			break;
2363 1e0b1727 Phil Davis
		} else if ($usedmac[0] + ($resettimeout * 3600) <= $currenttime) {
2364
			unset($usedmacs[$key]);
2365
		}
2366 ac631bba lgcosta
	}
2367
2368
	if (!$found) {
2369
		$usedmac = array($currenttime, $clientmac, $freeloginscount - 1);
2370
		$usedmacs[] = implode(",", $usedmac);
2371
	}
2372
2373
	captiveportal_write_usedmacs_db($usedmacs);
2374
	return true;
2375
}
2376
2377
function captiveportal_read_usedmacs_db() {
2378 b4792bf8 Ermal
	global $g, $cpzone;
2379 ac631bba lgcosta
2380 b4792bf8 Ermal
	$cpumaclck = lock("captiveusedmacs{$cpzone}");
2381
	if (file_exists("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db")) {
2382
		$usedmacs = file("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2383 1e0b1727 Phil Davis
		if (!$usedmacs) {
2384 ac631bba lgcosta
			$usedmacs = array();
2385 1e0b1727 Phil Davis
		}
2386
	} else {
2387 ac631bba lgcosta
		$usedmacs = array();
2388 1e0b1727 Phil Davis
	}
2389 ac631bba lgcosta
2390
	unlock($cpumaclck);
2391
	return $usedmacs;
2392
}
2393
2394
function captiveportal_write_usedmacs_db($usedmacs) {
2395 b4792bf8 Ermal
	global $g, $cpzone;
2396 ac631bba lgcosta
2397 b4792bf8 Ermal
	$cpumaclck = lock("captiveusedmacs{$cpzone}", LOCK_EX);
2398
	@file_put_contents("{$g['vardb_path']}/captiveportal_usedmacs_{$cpzone}.db", implode("\n", $usedmacs));
2399 ac631bba lgcosta
	unlock($cpumaclck);
2400
}
2401
2402 81ce28d8 Renato Botelho
function captiveportal_blocked_mac($mac) {
2403
	global $config, $g, $cpzone;
2404 0d33f1fc Renato Botelho
2405 1e0b1727 Phil Davis
	if (empty($mac) || !is_macaddr($mac)) {
2406 81ce28d8 Renato Botelho
		return false;
2407 1e0b1727 Phil Davis
	}
2408 0d33f1fc Renato Botelho
2409 1e0b1727 Phil Davis
	if (!is_array($config['captiveportal'][$cpzone]['passthrumac'])) {
2410 81ce28d8 Renato Botelho
		return false;
2411 1e0b1727 Phil Davis
	}
2412 0d33f1fc Renato Botelho
2413 1e0b1727 Phil Davis
	foreach ($config['captiveportal'][$cpzone]['passthrumac'] as $passthrumac) {
2414 81ce28d8 Renato Botelho
		if (($passthrumac['action'] == 'block') &&
2415 ae52d165 Renato Botelho
		    ($passthrumac['mac'] == strtolower($mac))) {
2416 81ce28d8 Renato Botelho
			return true;
2417 1e0b1727 Phil Davis
		}
2418
	}
2419 0d33f1fc Renato Botelho
2420 81ce28d8 Renato Botelho
	return false;
2421 3b2769be Renato Botelho
2422
}
2423
2424 62f20eab Michael Newton
function captiveportal_send_server_accounting($off = false) {
2425
	global $cpzone, $config;
2426
2427
	if (!isset($config['captiveportal'][$cpzone]['radacct_enable'])) {
2428
		return;
2429
	}
2430
	if ($off) {
2431
		$racct = new Auth_RADIUS_Acct_Off;
2432
	} else {
2433
		$racct = new Auth_RADIUS_Acct_On;
2434
	}
2435
	$radiusservers = captiveportal_get_radius_servers();
2436
	if (empty($radiusservers)) {
2437
		return;
2438
	}
2439
	foreach ($radiusservers['first'] as $radsrv) {
2440
		// Add a new server to our instance
2441
		$racct->addServer($radsrv['ipaddr'], $radsrv['acctport'], $radsrv['key']);
2442
	}
2443
	if (PEAR::isError($racct->start())) {
2444
		$retvalue['acct_val'] = 1;
2445
		$retvalue['error'] = $racct->getMessage();
2446
2447
		// If we encounter an error immediately stop this function and go back
2448
		$racct->close();
2449
		return $retvalue;
2450
	}
2451
	// Send request
2452
	$result = $racct->send();
2453
	// Evaluation of the response
2454
	// 5 -> Accounting-Response
2455
	// See RFC2866 for this.
2456
	if (PEAR::isError($result)) {
2457
		$retvalue['acct_val'] = 1;
2458
		$retvalue['error'] = $result->getMessage();
2459
	} else if ($result === true) {
2460
		$retvalue['acct_val'] = 5 ;
2461
	} else {
2462
		$retvalue['acct_val'] = 1 ;
2463
	}
2464
2465
	$racct->close();
2466
	return $retvalue;
2467
}
2468 d2ecbddc jim-p
2469
function captiveportal_isip_logged($clientip) {
2470
	global $g, $cpzone;
2471
2472
	/* read in client database */
2473
	$query = "WHERE ip = '{$clientip}'";
2474
	$cpdb = captiveportal_read_db($query);
2475
	foreach ($cpdb as $cpentry) {
2476
		return $cpentry;
2477
	}
2478
}
2479 64c0462b Ermal
?>