Project

General

Profile

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